feat(server)!: page the list commands (#4916) GetStreams, GetTopics, GetConsumerGroups and GetUsers answer with the whole list in one reply, so a long list can pass the client reply cap. Only GetTopic returns the partitions of a topic. Each of these requests now ends with a required page block: order, direction, limit, an opaque cursor and a name filter. The new GetPartitions command (code 404) reads one page of partitions. A 0.12.2 client sends no page block, so both protocol versions move to 0.12.3, and every component that embeds the protocol gets a new version. Streams, topics and users page in id or creation order, both ways, under the budgets of GetMetadataChanges. A restore rebuilds the new creation index of streams and users, so the snapshot format stays the same. Consumer groups move from an AHashMap to a BTreeMap, so every replica lists them in the same order. Outside HTTP, a reply of GetClients or of a metadata read above MAX_RECORD_REPLY_SIZE becomes the new error ReplyTooLarge (97), so the client keeps its link. A topics page read with a cursor answers StreamIdNotFound when the stream was deleted during the walk, so the walk cannot end early with a short list. A walk fails with a malformed-reply error when a page answers the cursor it was read with, so it cannot loop forever. Over HTTP, the streams, topics, consumer groups and users routes answer one page only for limit or cursor. Without both, they answer the bare array of the whole list, in the asked order and with the asked name filter. The MCP list tools follow the same rule. The list routes now refuse an unknown or repeated query key with 400, where 0.10.0 ignored an unknown key such as a cache buster. The SDK list methods keep their signatures and still return the whole list. A whole-list call keeps the caller sign-in and the deadline that it started with for all of its pages, so a caller sign-in between two pages ends the call instead of mixing the lists of two users. Every SDK gets five page methods, such as get_streams_page. The partitions method takes a PageQuery and the other four take a NamedPageQuery, which adds the name filter, so a partitions query has no name field. The CLI list commands and the MCP list tools take page parameters, and partition list and get_partitions are new. The API breaks: the five page methods are required on the client traits and interfaces, the Rust *_from_wire list conversions are removed, TopicHeader is now TopicResponse, and the Go and Node list deserializers are removed.
diff --git a/.typos.toml b/.typos.toml index 04b5107..a5f231e 100644 --- a/.typos.toml +++ b/.typos.toml
@@ -159,5 +159,7 @@ "**/resource_options.json", # Metadata change fixture copies in every SDK test tree (hex and base64url payloads) "**/metadata_changes.json", + # List page fixture copies in every SDK test tree (hex and base64url payloads) + "**/list_pages.json", "**/.python-version", ]
diff --git a/Cargo.lock b/Cargo.lock index 57729d7..a5f59cf 100644 --- a/Cargo.lock +++ b/Cargo.lock
@@ -5651,7 +5651,7 @@ [[package]] name = "iggy" -version = "0.12.0" +version = "0.12.1-edge.1" dependencies = [ "async-broadcast", "async-dropper", @@ -5690,7 +5690,7 @@ [[package]] name = "iggy-bench" -version = "0.7.0" +version = "0.7.1-edge.1" dependencies = [ "async-trait", "bench-report", @@ -5750,7 +5750,7 @@ [[package]] name = "iggy-cli" -version = "0.15.0" +version = "0.15.1-edge.1" dependencies = [ "anyhow", "apple-native-keyring-store", @@ -5785,7 +5785,7 @@ [[package]] name = "iggy-gateway-kafka" -version = "0.2.1-edge.1" +version = "0.2.1-edge.2" dependencies = [ "arc-swap", "async-trait", @@ -5824,7 +5824,7 @@ [[package]] name = "iggy-mcp" -version = "0.6.0" +version = "0.6.1-edge.1" dependencies = [ "axum", "axum-server", @@ -5875,7 +5875,7 @@ [[package]] name = "iggy_binary_protocol" -version = "0.12.0" +version = "0.12.1-edge.1" dependencies = [ "aligned-vec", "bytemuck", @@ -5890,7 +5890,7 @@ [[package]] name = "iggy_common" -version = "0.12.0" +version = "0.12.1-edge.1" dependencies = [ "aes-gcm", "aes-gcm-siv", @@ -9836,7 +9836,7 @@ [[package]] name = "server" -version = "0.10.0" +version = "0.10.1-edge.1" dependencies = [ "ahash", "arc-swap",
diff --git a/Cargo.toml b/Cargo.toml index 9526bb8..8c6444a 100644 --- a/Cargo.toml +++ b/Cargo.toml
@@ -163,11 +163,11 @@ hwlocality = "1.0.0-alpha.13" hyper = "1.12.0" hyper-util = { version = "0.1.21", features = ["server-auto", "service"] } -iggy = { path = "core/sdk", version = "0.12.0" } -iggy-cli = { path = "core/cli", version = "0.15.0" } +iggy = { path = "core/sdk", version = "0.12.1-edge.1" } +iggy-cli = { path = "core/cli", version = "0.15.1-edge.1" } iggy-gateway-kafka = { path = "gateways/kafka" } -iggy_binary_protocol = { path = "core/binary_protocol", version = "0.12.0" } -iggy_common = { path = "core/common", version = "0.12.0" } +iggy_binary_protocol = { path = "core/binary_protocol", version = "0.12.1-edge.1" } +iggy_common = { path = "core/common", version = "0.12.1-edge.1" } iggy_kafka_wire = { path = "core/kafka_wire" } iggy_object_store = { path = "core/object_store" } indexmap = "2.14.2"
diff --git a/bdd/python/uv.lock b/bdd/python/uv.lock index 12b3dbb..7c284ae 100644 --- a/bdd/python/uv.lock +++ b/bdd/python/uv.lock
@@ -8,7 +8,7 @@ [[package]] name = "apache-iggy" -version = "0.10.0" +version = "0.10.1.dev1" source = { directory = "../../foreign/python" } [package.metadata]
diff --git a/core/ai/mcp/Cargo.toml b/core/ai/mcp/Cargo.toml index b16f082..729a1da 100644 --- a/core/ai/mcp/Cargo.toml +++ b/core/ai/mcp/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy-mcp" -version = "0.6.0" +version = "0.6.1-edge.1" description = "MCP Server for Iggy message streaming platform" edition = "2024" license = "Apache-2.0"
diff --git a/core/ai/mcp/README.md b/core/ai/mcp/README.md index 0e799f1..b54a130 100644 --- a/core/ai/mcp/README.md +++ b/core/ai/mcp/README.md
@@ -110,7 +110,7 @@ | Permission | Tools | | --- | --- | -| `read` | `ping`, `get_cluster_metadata`, `get_stream`, `get_streams`, `get_topic`, `get_topics`, `poll_messages`, `get_stats`, `get_me`, `get_client`, `get_clients`, `snapshot`, `get_consumer_group`, `get_consumer_groups`, `get_consumer_offset`, `get_personal_access_tokens`, `get_user`, `get_users` | +| `read` | `ping`, `get_cluster_metadata`, `get_stream`, `get_streams`, `get_topic`, `get_topics`, `get_partitions`, `poll_messages`, `get_stats`, `get_me`, `get_client`, `get_clients`, `snapshot`, `get_consumer_group`, `get_consumer_groups`, `get_consumer_offset`, `get_personal_access_tokens`, `get_user`, `get_users` | | `create` | `create_stream`, `create_topic`, `create_partitions`, `send_messages`, `create_consumer_group`, `create_personal_access_token`, `create_user` | | `update` | `update_stream`, `update_topic`, `store_consumer_offset`, `update_user`, `update_permissions`, `change_password` | | `delete` | `delete_stream`, `delete_topic`, `delete_partitions`, `delete_segments`, `delete_consumer_group`, `delete_consumer_offset`, `delete_personal_access_token`, `delete_user` | @@ -119,6 +119,8 @@ The administration tools `get_personal_access_tokens`, `create_personal_access_token`, `delete_personal_access_token`, `get_users`, `get_user`, `create_user`, `update_user`, `delete_user`, `update_permissions`, `change_password` and `snapshot` also require `admin`, which is off by default. They let an agent mint credentials, lock out users or read server diagnostics, so enable `admin` only for a server whose agents administer Iggy. +`get_streams`, `get_topics`, `get_consumer_groups` and `get_users` return the whole list as an array. The array follows `order` and `descending` and holds only the items that match `name`. With `limit` or `cursor`, they return one page as `{items, next}` instead. To read the next page, call the tool again with `next` as `cursor` and the same other parameters. The last page has no `next`. `get_partitions` always returns one page and takes the same page parameters except `name`. + `send_messages` takes UTF-8 payloads, and `poll_messages` returns payloads base64 encoded. A batch with an invalid message, such as an empty payload, is refused and nothing is sent. ## Recovering uncertain writes
diff --git a/core/ai/mcp/src/service/mod.rs b/core/ai/mcp/src/service/mod.rs index 245207b..7f0cb81 100644 --- a/core/ai/mcp/src/service/mod.rs +++ b/core/ai/mcp/src/service/mod.rs
@@ -17,12 +17,12 @@ use iggy::prelude::{ Client, ClusterClient, CommitPolicy, CompressionAlgorithm, Consumer, ConsumerGroupClient, - ConsumerOffsetClient, Identifier, IggyClient, IggyError, IggyExpiry, IggyMessage, - IggyTimestamp, MaxTopicSize, MessageClient, OptionKey, PartitionClient, Partitioning, - PersonalAccessTokenClient, PollOptions, PollingKind, PollingStrategy, SegmentClient, - StreamClient, StreamCreateOptions, StreamUpdateOptions, SystemClient, SystemSnapshotType, - TopicClient, TopicCreateOptions, TopicUpdateOptions, UserClient, UserCreateOptions, UserStatus, - UserUpdateOptions, + ConsumerOffsetClient, DEFAULT_PAGE_LIMIT, Identifier, IggyClient, IggyError, IggyExpiry, + IggyMessage, IggyTimestamp, MAX_PAGE_LIMIT, MaxTopicSize, MessageClient, NamedPageQuery, + OptionKey, Page, PageQuery, PartitionClient, Partitioning, PersonalAccessTokenClient, + PollOptions, PollingKind, PollingStrategy, SegmentClient, StreamClient, StreamCreateOptions, + StreamUpdateOptions, SystemClient, SystemSnapshotType, TopicClient, TopicCreateOptions, + TopicUpdateOptions, UserClient, UserCreateOptions, UserStatus, UserUpdateOptions, }; use requests::*; use rmcp::{ @@ -104,10 +104,18 @@ request(self.client.get_stream(&id(&stream_id)?).await) } - #[tool(description = "Get streams")] - pub async fn get_streams(&self) -> Result<CallToolResult, ErrorData> { + #[tool( + description = "Get streams. With limit or cursor, one page as {items, next}. Without both, every stream as an array, in the asked order and with the asked name filter." + )] + pub async fn get_streams( + &self, + Parameters(page): Parameters<NamedPageParams>, + ) -> Result<CallToolResult, ErrorData> { self.permissions.ensure_read()?; - request(self.client.get_streams().await) + read_list(page, |query| async move { + self.client.get_streams_page(&query).await + }) + .await } #[tool(description = "Create stream")] @@ -146,13 +154,19 @@ request(self.client.delete_stream(&id(&stream_id)?).await) } - #[tool(description = "Get topics")] + #[tool( + description = "Get topics. With limit or cursor, one page as {items, next}. Without both, every topic of the stream as an array, in the asked order and with the asked name filter." + )] pub async fn get_topics( &self, - Parameters(GetTopics { stream_id }): Parameters<GetTopics>, + Parameters(GetTopics { stream_id, page }): Parameters<GetTopics>, ) -> Result<CallToolResult, ErrorData> { self.permissions.ensure_read()?; - request(self.client.get_topics(&id(&stream_id)?).await) + let stream_id = &id(&stream_id)?; + read_list(page, |query| async move { + self.client.get_topics_page(stream_id, &query).await + }) + .await } #[tool(description = "Get topic")] @@ -219,6 +233,24 @@ ) } + #[tool(description = "Get one page of the partitions of a topic as {items, next}")] + pub async fn get_partitions( + &self, + Parameters(GetPartitions { + stream_id, + topic_id, + page, + }): Parameters<GetPartitions>, + ) -> Result<CallToolResult, ErrorData> { + self.permissions.ensure_read()?; + let query = page_query(page)?; + request( + self.client + .get_partitions_page(&id(&stream_id)?, &id(&topic_id)?, &query) + .await, + ) + } + #[tool(description = "Create partitions")] pub async fn create_partitions( &self, @@ -489,20 +521,25 @@ request(self.client.snapshot(compression, types).await) } - #[tool(description = "Get consumer groups")] + #[tool( + description = "Get consumer groups. With limit or cursor, one page as {items, next}. Without both, every group of the topic as an array, in the asked order and with the asked name filter." + )] pub async fn get_consumer_groups( &self, Parameters(GetConsumerGroups { stream_id, topic_id, + page, }): Parameters<GetConsumerGroups>, ) -> Result<CallToolResult, ErrorData> { self.permissions.ensure_read()?; - request( + let (stream_id, topic_id) = (&id(&stream_id)?, &id(&topic_id)?); + read_list(page, |query| async move { self.client - .get_consumer_groups(&id(&stream_id)?, &id(&topic_id)?) - .await, - ) + .get_consumer_groups_page(stream_id, topic_id, &query) + .await + }) + .await } #[tool(description = "Get consumer group")] @@ -663,11 +700,19 @@ request(self.client.delete_personal_access_token(&name).await) } - #[tool(description = "Get users. Requires the admin permission.")] - pub async fn get_users(&self) -> Result<CallToolResult, ErrorData> { + #[tool( + description = "Get users. Requires the admin permission. With limit or cursor, one page as {items, next}. Without both, every user as an array, in the asked order and with the asked name filter." + )] + pub async fn get_users( + &self, + Parameters(page): Parameters<NamedPageParams>, + ) -> Result<CallToolResult, ErrorData> { self.permissions.ensure_read()?; self.permissions.ensure_admin()?; - request(self.client.get_users().await) + read_list(page, |query| async move { + self.client.get_users_page(&query).await + }) + .await } #[tool(description = "Get user. Requires the admin permission.")] @@ -920,6 +965,68 @@ }) } +/// What a list tool of named entities reads for its page parameters. +#[derive(Debug, PartialEq)] +enum ListRead { + /// One page, for parameters with `limit` or `cursor`. + Page(NamedPageQuery), + /// Every page, in pages of [`MAX_PAGE_LIMIT`], in the order and with the + /// name filter of the parameters. + Whole(NamedPageQuery), +} + +impl TryFrom<NamedPageParams> for ListRead { + type Error = ErrorData; + + fn try_from(params: NamedPageParams) -> Result<Self, Self::Error> { + let selects_page = params.page.limit.is_some() || params.page.cursor.is_some(); + let mut query = NamedPageQuery { + page: page_query(params.page)?, + name: params.name, + }; + if selects_page { + return Ok(Self::Page(query)); + } + query.page.limit = MAX_PAGE_LIMIT; + Ok(Self::Whole(query)) + } +} + +/// Answers a list tool of named entities with one page or the whole list, see +/// [`ListRead`]. +async fn read_list<T: Serialize, Fut>( + params: NamedPageParams, + mut read_page: impl FnMut(NamedPageQuery) -> Fut, +) -> Result<CallToolResult, ErrorData> +where + Fut: Future<Output = Result<Page<T>, IggyError>>, +{ + match ListRead::try_from(params)? { + ListRead::Page(query) => request(read_page(query).await), + ListRead::Whole(query) => request(query.read_to_end(read_page).await), + } +} + +/// The page query of the page parameters. A missing parameter keeps its +/// default. +fn page_query(page: PageParams) -> Result<PageQuery, ErrorData> { + let PageParams { + limit, + cursor, + order, + descending, + } = page; + Ok(PageQuery { + order: order + .map(|order| parsed(&order, "order")) + .transpose()? + .unwrap_or_default(), + descending: descending.unwrap_or_default(), + limit: limit.unwrap_or(DEFAULT_PAGE_LIMIT), + cursor: cursor.map(|cursor| parsed(&cursor, "cursor")).transpose()?, + }) +} + fn request(result: Result<impl Sized + Serialize, IggyError>) -> Result<CallToolResult, ErrorData> { let result = result.map_err(|error| { let message = match recovery(&error) { @@ -982,6 +1089,7 @@ #[cfg(test)] mod tests { use super::*; + use iggy::prelude::PageOrder; use std::collections::BTreeMap; #[test] @@ -1084,6 +1192,65 @@ } #[test] + fn given_list_tool_arguments_when_converting_should_read_one_page_only_with_limit_or_cursor() { + let read = |body: &str| { + let params: NamedPageParams = serde_json::from_str(body).expect("valid JSON"); + ListRead::try_from(params).expect("valid page parameters") + }; + let topics: GetTopics = serde_json::from_str( + r#"{"stream_id":"orders","limit":5,"cursor":"pg1_AQcAAAAAAAAA","order":"created","descending":true,"name":"ord"}"#, + ) + .expect("valid get_topics body"); + assert_eq!( + ListRead::try_from(topics.page).expect("valid page parameters"), + ListRead::Page(NamedPageQuery { + page: PageQuery { + order: PageOrder::Created, + descending: true, + limit: 5, + cursor: Some("pg1_AQcAAAAAAAAA".parse().expect("a page cursor")), + }, + name: Some("ord".to_owned()), + }) + ); + assert!(matches!( + read(r#"{"cursor":"pg1_AQcAAAAAAAAA"}"#), + ListRead::Page(_) + )); + + let whole_list = PageQuery { + limit: MAX_PAGE_LIMIT, + ..PageQuery::default() + }; + assert_eq!(read("{}"), ListRead::Whole(whole_list.clone().into())); + assert_eq!( + read(r#"{"descending":false}"#), + ListRead::Whole(whole_list.clone().into()), + "a default value alone keeps the whole list" + ); + assert_eq!( + read(r#"{"order":"created","descending":true,"name":"ord"}"#), + ListRead::Whole(NamedPageQuery { + page: PageQuery { + order: PageOrder::Created, + descending: true, + ..whole_list + }, + name: Some("ord".to_owned()), + }), + "the whole list keeps the order and the name filter" + ); + } + + #[test] + fn given_unparsable_page_parameter_when_converting_should_refuse() { + for body in [r#"{"order":"name"}"#, r#"{"cursor":"mc1_AQcAAAAAAAAA"}"#] { + let page: NamedPageParams = serde_json::from_str(body).expect("valid JSON"); + assert!(ListRead::try_from(page).is_err(), "{body}"); + } + } + + #[test] fn given_update_topic_values_when_converting_should_parse_them_into_typed_options() { let update = update_topic( r#"{"name":"events-v2","message_expiry":"7days","max_size":"15GB","options":{"future_key":"1"}}"#,
diff --git a/core/ai/mcp/src/service/requests.rs b/core/ai/mcp/src/service/requests.rs index 75d703b..74b112d 100644 --- a/core/ai/mcp/src/service/requests.rs +++ b/core/ai/mcp/src/service/requests.rs
@@ -29,6 +29,45 @@ pub operation_id: String, } +/// The page parameters of the list tools. +#[derive(Debug, Default, Deserialize, JsonSchema)] +pub struct PageParams { + #[schemars( + description = "page parameter: most items of the page (optional, 1 to 1000, defaults to 100). \ + With limit or cursor, a list tool returns one page" + )] + pub limit: Option<u32>, + + #[schemars( + description = "page parameter: the next value of a page, to read the page after it (optional). \ + Give the same other parameters as for that page. The last page has no next" + )] + pub cursor: Option<String>, + + #[schemars( + description = "page parameter: order of the items (optional, one of 'id', 'created'; defaults to 'id'). \ + Partitions and consumer groups come in id order for both, because their ids follow creation" + )] + pub order: Option<String>, + + #[schemars(description = "page parameter: descending order (optional, defaults to false)")] + pub descending: Option<bool>, +} + +/// The page parameters of the lists of named entities. A list tool that gets +/// neither `limit` nor `cursor` returns the whole list, in the order and with +/// the name filter of the other parameters. +#[derive(Debug, Default, Deserialize, JsonSchema)] +pub struct NamedPageParams { + #[serde(flatten)] + pub page: PageParams, + + #[schemars( + description = "page parameter: only the items whose name holds this text (optional, case-sensitive)" + )] + pub name: Option<String>, +} + #[derive(Debug, Deserialize, JsonSchema)] pub struct GetStream { #[schemars(description = "stream identifier (name or number)")] @@ -66,6 +105,9 @@ pub struct GetTopics { #[schemars(description = "stream identifier (name or number)")] pub stream_id: String, + + #[serde(flatten)] + pub page: NamedPageParams, } #[derive(Debug, Deserialize, JsonSchema)] @@ -150,6 +192,18 @@ } #[derive(Debug, Deserialize, JsonSchema)] +pub struct GetPartitions { + #[schemars(description = "stream identifier (name or number)")] + pub stream_id: String, + + #[schemars(description = "topic identifier (name or number)")] + pub topic_id: String, + + #[serde(flatten)] + pub page: PageParams, +} + +#[derive(Debug, Deserialize, JsonSchema)] pub struct CreatePartitions { #[schemars(description = "stream identifier (name or number)")] pub stream_id: String, @@ -299,6 +353,9 @@ #[schemars(description = "topic identifier (name or number)")] pub topic_id: String, + + #[serde(flatten)] + pub page: NamedPageParams, } #[derive(Debug, Deserialize, JsonSchema)] @@ -602,7 +659,9 @@ #[cfg(test)] mod tests { use super::*; + use rmcp::handler::server::common::schema_for_type; use rmcp::schemars::schema_for; + use std::collections::BTreeSet; #[test] fn given_stream_tool_schema_when_describing_should_exclude_encryption_key() { @@ -636,6 +695,67 @@ } #[test] + fn given_list_tool_schemas_when_describing_should_hold_optional_page_parameters_at_the_top() { + const PAGE: [&str; 4] = ["limit", "cursor", "order", "descending"]; + for (tool, schema, ids, named) in [ + ( + "get_streams", + schema_for_type::<NamedPageParams>(), + &[][..], + true, + ), + ( + "get_topics", + schema_for_type::<GetTopics>(), + &["stream_id"][..], + true, + ), + ( + "get_consumer_groups", + schema_for_type::<GetConsumerGroups>(), + &["stream_id", "topic_id"][..], + true, + ), + ( + "get_partitions", + schema_for_type::<GetPartitions>(), + &["stream_id", "topic_id"][..], + false, + ), + ] { + let properties: BTreeSet<&str> = schema + .get("properties") + .and_then(|properties| properties.as_object()) + .expect("object schema") + .keys() + .map(String::as_str) + .collect(); + let mut expected: BTreeSet<&str> = ids.iter().chain(&PAGE).copied().collect(); + if named { + expected.insert("name"); + } + assert_eq!(properties, expected, "{tool}"); + + let required: BTreeSet<&str> = schema + .get("required") + .and_then(|required| required.as_array()) + .map(|required| required.iter().filter_map(|id| id.as_str()).collect()) + .unwrap_or_default(); + assert_eq!(required, ids.iter().copied().collect(), "{tool}"); + + let description = schema + .get("description") + .and_then(|description| description.as_str()) + .unwrap_or_default(); + assert_eq!( + description.contains("whole list"), + named, + "{tool}: only a list of named entities is whole without page parameters" + ); + } + } + + #[test] fn given_update_topic_with_retired_compression_when_parsing_should_refuse() { let body = r#"{"stream_id":"orders","topic_id":"events","name":"events-v2","compression_algorithm":"gzip"}"#;
diff --git a/core/bench/Cargo.toml b/core/bench/Cargo.toml index 7fa0f1a..2979258 100644 --- a/core/bench/Cargo.toml +++ b/core/bench/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy-bench" -version = "0.7.0" +version = "0.7.1-edge.1" edition = "2024" license = "Apache-2.0" repository = "https://github.com/apache/iggy"
diff --git a/core/binary_protocol/Cargo.toml b/core/binary_protocol/Cargo.toml index 3fc09b3..a590d8c 100644 --- a/core/binary_protocol/Cargo.toml +++ b/core/binary_protocol/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy_binary_protocol" -version = "0.12.0" +version = "0.12.1-edge.1" description = "Wire protocol types and codec for the Iggy binary protocol. Shared between server and SDK." edition = "2024" rust-version.workspace = true
diff --git a/core/binary_protocol/src/codes.rs b/core/binary_protocol/src/codes.rs index 5d474a0..6ac6569 100644 --- a/core/binary_protocol/src/codes.rs +++ b/core/binary_protocol/src/codes.rs
@@ -96,6 +96,7 @@ // -- Partitions -- pub const CREATE_PARTITIONS_CODE: u32 = 402; pub const DELETE_PARTITIONS_CODE: u32 = 403; +pub const GET_PARTITIONS_CODE: u32 = 404; // -- Segments -- pub const DELETE_SEGMENTS_CODE: u32 = 503; @@ -171,6 +172,7 @@ DELETE_TOPIC_CODE, CREATE_PARTITIONS_CODE, DELETE_PARTITIONS_CODE, + GET_PARTITIONS_CODE, DELETE_SEGMENTS_CODE, GET_CONSUMER_GROUP_CODE, GET_CONSUMER_GROUPS_CODE,
diff --git a/core/binary_protocol/src/dispatch.rs b/core/binary_protocol/src/dispatch.rs index c2ead01..9157db0 100644 --- a/core/binary_protocol/src/dispatch.rs +++ b/core/binary_protocol/src/dispatch.rs
@@ -193,6 +193,8 @@ CommandMeta::non_replicated(POLL_MESSAGES_DEFERRED_CODE, "message.poll_deferred"), CommandMeta::non_replicated(CANCEL_DEFERRED_REQUEST_CODE, "message.cancel_deferred"), CommandMeta::non_replicated(FETCH_MESSAGES_CODE, "message.fetch"), + // Partitions + CommandMeta::non_replicated(GET_PARTITIONS_CODE, "partition.list"), ]; /// Lookup command metadata by command code. @@ -266,6 +268,7 @@ POLL_MESSAGES_DEFERRED_CODE => 49, CANCEL_DEFERRED_REQUEST_CODE => 50, FETCH_MESSAGES_CODE => 51, + GET_PARTITIONS_CODE => 52, _ => return None, }; Some(idx)
diff --git a/core/binary_protocol/src/primitives/mod.rs b/core/binary_protocol/src/primitives/mod.rs index e152999..1c0d471 100644 --- a/core/binary_protocol/src/primitives/mod.rs +++ b/core/binary_protocol/src/primitives/mod.rs
@@ -22,6 +22,7 @@ pub mod identifier; pub mod metadata_changes; pub mod options; +pub mod page; pub mod partition_assignment; pub mod partition_history; pub mod partition_status;
diff --git a/core/binary_protocol/src/primitives/page.rs b/core/binary_protocol/src/primitives/page.rs new file mode 100644 index 0000000..0ba7146 --- /dev/null +++ b/core/binary_protocol/src/primitives/page.rs
@@ -0,0 +1,385 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The page block of the list commands and the cursor inside it. +//! +//! A list request ends with the page block: +//! +//! ```text +//! [order:u8] 0 = id, 1 = created +//! [descending:u8] 0 = ascending, 1 = descending +//! [limit:u32] 1 to MAX_PAGE_LIMIT +//! [cursor_len:u8][cursor] 0 = start of the order +//! [name_len:u8][name] 0 = no filter +//! ``` +//! +//! The decode checks the structure. The server checks the limit range and +//! whether the cursor kind fits the order. + +use crate::codec::{WireDecode, WireEncode, read_u8, read_u32_le, read_u64_le}; +use crate::primitives::metadata_changes::{put_flag, read_flag, read_wire_name}; +use crate::{WireError, WireName}; +use bytes::{BufMut, BytesMut}; +use std::borrow::Cow; + +/// The page size of a request that names no limit. +pub const DEFAULT_PAGE_LIMIT: u32 = 100; +/// The largest page a request can ask for. +pub const MAX_PAGE_LIMIT: u32 = 1000; + +const ID_CURSOR_KIND: u8 = 1; +const CREATED_CURSOR_KIND: u8 = 2; +const ID_CURSOR_SIZE: usize = 1 + 8; +const CREATED_CURSOR_SIZE: usize = 1 + 8 + 8; + +/// The order of a list page. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum WirePageOrder { + /// The numeric id. + #[default] + Id, + /// The creation order, keyed by `(created_at, id)`. + Created, +} + +impl WirePageOrder { + #[must_use] + pub const fn as_u8(self) -> u8 { + match self { + Self::Id => 0, + Self::Created => 1, + } + } + + /// # Errors + /// `WireError::UnknownDiscriminant` for a byte other than 0 and 1. + pub const fn from_u8(value: u8, offset: usize) -> Result<Self, WireError> { + match value { + 0 => Ok(Self::Id), + 1 => Ok(Self::Created), + value => Err(WireError::UnknownDiscriminant { + type_name: "WirePageOrder", + value, + offset, + }), + } + } +} + +/// A position in a list order. The `next` of a page names the last entry +/// that the page walked, and the next page starts after it. Clients return it +/// as it came. It holds no direction, filter or parent. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum WirePageCursor { + /// A position in id order. + Id(u64), + /// A position in creation order. + Created { created_at: u64, id: u64 }, +} + +impl WirePageCursor { + /// Decodes a cursor that fills `buf` exactly: `[kind:u8 = 1][id:u64]` or + /// `[kind:u8 = 2][created_at:u64][id:u64]`, little-endian. + /// + /// # Errors + /// `WireError::UnknownDiscriminant` for an unknown kind, and + /// `WireError::Validation` for a length that does not fit the kind. + pub fn decode_exact(buf: &[u8]) -> Result<Self, WireError> { + let kind = read_u8(buf, 0)?; + match (kind, buf.len()) { + (ID_CURSOR_KIND, ID_CURSOR_SIZE) => Ok(Self::Id(read_u64_le(buf, 1)?)), + (CREATED_CURSOR_KIND, CREATED_CURSOR_SIZE) => Ok(Self::Created { + created_at: read_u64_le(buf, 1)?, + id: read_u64_le(buf, 9)?, + }), + (ID_CURSOR_KIND | CREATED_CURSOR_KIND, length) => { + Err(WireError::Validation(Cow::Owned(format!( + "a page cursor of kind {kind} cannot have {length} bytes" + )))) + } + (value, _) => Err(WireError::UnknownDiscriminant { + type_name: "WirePageCursor", + value, + offset: 0, + }), + } + } +} + +impl WireEncode for WirePageCursor { + fn encoded_size(&self) -> usize { + match self { + Self::Id(_) => ID_CURSOR_SIZE, + Self::Created { .. } => CREATED_CURSOR_SIZE, + } + } + + fn encode(&self, buf: &mut BytesMut) { + match *self { + Self::Id(id) => { + buf.put_u8(ID_CURSOR_KIND); + buf.put_u64_le(id); + } + Self::Created { created_at, id } => { + buf.put_u8(CREATED_CURSOR_KIND); + buf.put_u64_le(created_at); + buf.put_u64_le(id); + } + } + } +} + +/// `[cursor_len:u8][cursor]`, with a length of 0 for no cursor. +pub(crate) fn optional_cursor_size(cursor: Option<&WirePageCursor>) -> usize { + 1 + cursor.map_or(0, WireEncode::encoded_size) +} + +#[allow(clippy::cast_possible_truncation)] +pub(crate) fn put_optional_cursor(buf: &mut BytesMut, cursor: Option<&WirePageCursor>) { + match cursor { + None => buf.put_u8(0), + Some(cursor) => { + buf.put_u8(cursor.encoded_size() as u8); + cursor.encode(buf); + } + } +} + +pub(crate) fn read_optional_cursor( + buf: &[u8], + offset: usize, +) -> Result<(Option<WirePageCursor>, usize), WireError> { + let length = usize::from(read_u8(buf, offset)?); + if length == 0 { + return Ok((None, 1)); + } + let start = offset + 1; + let bytes = buf + .get(start..start + length) + .ok_or_else(|| WireError::UnexpectedEof { + offset: start, + need: length, + have: buf.len().saturating_sub(start), + })?; + Ok((Some(WirePageCursor::decode_exact(bytes)?), 1 + length)) +} + +/// The page block that ends every list request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WirePageQuery { + pub order: WirePageOrder, + pub descending: bool, + /// The most items of the page, 1 to [`MAX_PAGE_LIMIT`]. + pub limit: u32, + /// The `next` of the previous page, `None` for the first page. + pub cursor: Option<WirePageCursor>, + /// Only the entries whose name holds this text, case-sensitive. + pub name: Option<WireName>, +} + +impl Default for WirePageQuery { + fn default() -> Self { + Self { + order: WirePageOrder::Id, + descending: false, + limit: DEFAULT_PAGE_LIMIT, + cursor: None, + name: None, + } + } +} + +impl WireEncode for WirePageQuery { + fn encoded_size(&self) -> usize { + 1 + 1 + + 4 + + optional_cursor_size(self.cursor.as_ref()) + + self.name.as_ref().map_or(1, WireEncode::encoded_size) + } + + fn encode(&self, buf: &mut BytesMut) { + buf.put_u8(self.order.as_u8()); + put_flag(buf, self.descending); + buf.put_u32_le(self.limit); + put_optional_cursor(buf, self.cursor.as_ref()); + match &self.name { + None => buf.put_u8(0), + Some(name) => name.encode(buf), + } + } +} + +impl WireDecode for WirePageQuery { + fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { + let order = WirePageOrder::from_u8(read_u8(buf, 0)?, 0)?; + let descending = read_flag(buf, 1)?; + let limit = read_u32_le(buf, 2)?; + let (cursor, cursor_size) = read_optional_cursor(buf, 6)?; + let mut position = 6 + cursor_size; + let name = if read_u8(buf, position)? == 0 { + position += 1; + None + } else { + let (name, consumed) = read_wire_name(buf, position)?; + position += consumed; + Some(name) + }; + Ok(( + Self { + order, + descending, + limit, + cursor, + name, + }, + position, + )) + } +} + +/// Decodes the page block at `offset`, the last field of a list request. +/// +/// # Errors +/// The decode error of the block, or `WireError::Validation` for bytes after it. +pub(crate) fn decode_trailing_page( + buf: &[u8], + offset: usize, +) -> Result<(WirePageQuery, usize), WireError> { + let rest = buf.get(offset..).ok_or(WireError::UnexpectedEof { + offset, + need: 1, + have: 0, + })?; + let (page, consumed) = WirePageQuery::decode(rest)?; + let end = offset + consumed; + if end != buf.len() { + return Err(WireError::Validation(Cow::Owned(format!( + "{} bytes after the page block", + buf.len() - end + )))); + } + Ok((page, end)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn filtered() -> WirePageQuery { + WirePageQuery { + order: WirePageOrder::Created, + descending: true, + limit: 20, + cursor: Some(WirePageCursor::Created { + created_at: 0x0102_0304_0506_0708, + id: 7, + }), + name: Some(WireName::new("ord").unwrap()), + } + } + + #[test] + fn given_a_first_page_without_a_name_when_encoding_should_pin_the_bytes() { + let query = WirePageQuery { + limit: 100, + ..WirePageQuery::default() + }; + let bytes = query.to_bytes(); + assert_eq!(&bytes[..], &[0, 0, 100, 0, 0, 0, 0, 0]); + assert_eq!(bytes.len(), query.encoded_size()); + assert_eq!(WirePageQuery::decode(&bytes).unwrap(), (query, 8)); + } + + #[test] + fn given_a_cursor_and_a_name_when_encoding_should_pin_the_bytes() { + let query = filtered(); + let bytes = query.to_bytes(); + let mut expected = vec![1, 1, 20, 0, 0, 0, 17, 2, 8, 7, 6, 5, 4, 3, 2, 1]; + expected.extend([7, 0, 0, 0, 0, 0, 0, 0, 3, b'o', b'r', b'd']); + assert_eq!(&bytes[..], &expected[..]); + assert_eq!(bytes.len(), query.encoded_size()); + assert_eq!( + WirePageQuery::decode(&bytes).unwrap(), + (query, expected.len()) + ); + } + + #[test] + fn given_an_id_cursor_when_round_tripping_should_keep_it() { + let query = WirePageQuery { + cursor: Some(WirePageCursor::Id(u64::MAX)), + ..WirePageQuery::default() + }; + let bytes = query.to_bytes(); + assert_eq!(bytes[6], 9); + assert_eq!(bytes[7], 1); + assert_eq!(WirePageQuery::decode(&bytes).unwrap().0, query); + } + + #[test] + fn given_a_bad_order_or_flag_byte_when_decoding_should_refuse() { + let bytes = filtered().to_bytes().to_vec(); + for (offset, value) in [(0, 2), (1, 2)] { + let mut broken = bytes.clone(); + broken[offset] = value; + assert!( + WirePageQuery::decode(&broken).is_err(), + "byte {offset} = {value}" + ); + } + } + + #[test] + fn given_an_unknown_kind_or_a_wrong_length_when_decoding_a_cursor_should_refuse() { + assert!(WirePageCursor::decode_exact(&[0; 9]).is_err()); + let mut kind_three = [0; 9]; + kind_three[0] = 3; + assert!(WirePageCursor::decode_exact(&kind_three).is_err()); + let mut id_too_long = [0; 17]; + id_too_long[0] = 1; + assert!(WirePageCursor::decode_exact(&id_too_long).is_err()); + let mut created_too_short = [0; 9]; + created_too_short[0] = 2; + assert!(WirePageCursor::decode_exact(&created_too_short).is_err()); + assert!(WirePageCursor::decode_exact(&[]).is_err()); + } + + #[test] + fn given_a_truncated_block_when_decoding_should_refuse() { + let bytes = filtered().to_bytes(); + for length in 0..bytes.len() { + assert!( + WirePageQuery::decode(&bytes[..length]).is_err(), + "a block cut at {length} bytes must not decode" + ); + } + } + + #[test] + fn given_bytes_after_the_block_when_decoding_a_trailing_page_should_refuse() { + let mut bytes = vec![9]; + bytes.extend_from_slice(&filtered().to_bytes()); + let (page, end) = decode_trailing_page(&bytes, 1).unwrap(); + assert_eq!((page, end), (filtered(), bytes.len())); + bytes.push(0); + assert!(decode_trailing_page(&bytes, 1).is_err()); + assert!( + decode_trailing_page(&[9], 1).is_err(), + "a request that ends before the block" + ); + } +}
diff --git a/core/binary_protocol/src/requests/consumer_groups/get_consumer_groups.rs b/core/binary_protocol/src/requests/consumer_groups/get_consumer_groups.rs index 2dd65a3..6aea6db 100644 --- a/core/binary_protocol/src/requests/consumer_groups/get_consumer_groups.rs +++ b/core/binary_protocol/src/requests/consumer_groups/get_consumer_groups.rs
@@ -15,44 +15,46 @@ // specific language governing permissions and limitations // under the License. -use crate::WireError; -use crate::WireIdentifier; use crate::codec::{WireDecode, WireEncode}; +use crate::primitives::page::{WirePageQuery, decode_trailing_page}; +use crate::{WireError, WireIdentifier}; use bytes::BytesMut; -/// `GetConsumerGroups` request. +/// `GetConsumerGroups` request: one page of the consumer groups of a topic, +/// in id order. /// -/// Wire format: `[stream_id][topic_id]` +/// Wire format: `[stream_id:WireIdentifier][topic_id:WireIdentifier][page]` #[derive(Debug, Clone, PartialEq, Eq)] pub struct GetConsumerGroupsRequest { pub stream_id: WireIdentifier, pub topic_id: WireIdentifier, + pub page: WirePageQuery, } impl WireEncode for GetConsumerGroupsRequest { fn encoded_size(&self) -> usize { - self.stream_id.encoded_size() + self.topic_id.encoded_size() + self.stream_id.encoded_size() + self.topic_id.encoded_size() + self.page.encoded_size() } fn encode(&self, buf: &mut BytesMut) { self.stream_id.encode(buf); self.topic_id.encode(buf); + self.page.encode(buf); } } impl WireDecode for GetConsumerGroupsRequest { fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { - let mut pos = 0; - let (stream_id, n) = WireIdentifier::decode(&buf[pos..])?; - pos += n; - let (topic_id, n) = WireIdentifier::decode(&buf[pos..])?; - pos += n; + let (stream_id, stream_size) = WireIdentifier::decode(buf)?; + let (topic_id, topic_size) = WireIdentifier::decode(&buf[stream_size..])?; + let (page, consumed) = decode_trailing_page(buf, stream_size + topic_size)?; Ok(( Self { stream_id, topic_id, + page, }, - pos, + consumed, )) } } @@ -60,43 +62,55 @@ #[cfg(test)] mod tests { use super::*; + use crate::WireName; - #[test] - fn roundtrip_numeric() { - let req = GetConsumerGroupsRequest { - stream_id: WireIdentifier::numeric(1), - topic_id: WireIdentifier::numeric(2), - }; - let bytes = req.to_bytes(); - let (decoded, consumed) = GetConsumerGroupsRequest::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, req); - } - - #[test] - fn roundtrip_named() { - let req = GetConsumerGroupsRequest { + fn request() -> GetConsumerGroupsRequest { + GetConsumerGroupsRequest { stream_id: WireIdentifier::named("stream-1").unwrap(), - topic_id: WireIdentifier::named("topic-1").unwrap(), - }; - let bytes = req.to_bytes(); - let (decoded, consumed) = GetConsumerGroupsRequest::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, req); + topic_id: WireIdentifier::numeric(2), + page: WirePageQuery { + descending: true, + name: Some(WireName::new("group").unwrap()), + ..WirePageQuery::default() + }, + } } #[test] - fn truncated_returns_error() { - let req = GetConsumerGroupsRequest { + fn given_a_page_when_round_tripping_should_keep_every_field() { + let request = request(); + let bytes = request.to_bytes(); + assert_eq!(bytes.len(), request.encoded_size()); + assert_eq!( + GetConsumerGroupsRequest::decode(&bytes).unwrap(), + (request, bytes.len()) + ); + } + + #[test] + fn given_a_first_page_when_encoding_should_pin_the_bytes() { + let request = GetConsumerGroupsRequest { stream_id: WireIdentifier::numeric(1), topic_id: WireIdentifier::numeric(2), + page: WirePageQuery::default(), }; - let bytes = req.to_bytes(); - for i in 0..bytes.len() { + let mut expected = WireIdentifier::numeric(1).to_bytes().to_vec(); + expected.extend_from_slice(&WireIdentifier::numeric(2).to_bytes()); + expected.extend_from_slice(&[0, 0, 100, 0, 0, 0, 0, 0]); + assert_eq!(&request.to_bytes()[..], &expected[..]); + } + + #[test] + fn given_a_truncated_request_or_bytes_after_it_when_decoding_should_refuse() { + let bytes = request().to_bytes(); + for length in 0..bytes.len() { assert!( - GetConsumerGroupsRequest::decode(&bytes[..i]).is_err(), - "expected error for truncation at byte {i}" + GetConsumerGroupsRequest::decode(&bytes[..length]).is_err(), + "a request cut at {length} bytes must not decode" ); } + let mut longer = bytes.to_vec(); + longer.push(0); + assert!(GetConsumerGroupsRequest::decode(&longer).is_err()); } }
diff --git a/core/binary_protocol/src/requests/partitions/get_partitions.rs b/core/binary_protocol/src/requests/partitions/get_partitions.rs new file mode 100644 index 0000000..dddc1fe --- /dev/null +++ b/core/binary_protocol/src/requests/partitions/get_partitions.rs
@@ -0,0 +1,113 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::codec::{WireDecode, WireEncode}; +use crate::primitives::page::{WirePageQuery, decode_trailing_page}; +use crate::{WireError, WireIdentifier}; +use bytes::BytesMut; + +/// `GetPartitions` request: one page of the partitions of a topic, in id +/// order. +/// +/// Wire format: `[stream_id:WireIdentifier][topic_id:WireIdentifier][page]` +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GetPartitionsRequest { + pub stream_id: WireIdentifier, + pub topic_id: WireIdentifier, + pub page: WirePageQuery, +} + +impl WireEncode for GetPartitionsRequest { + fn encoded_size(&self) -> usize { + self.stream_id.encoded_size() + self.topic_id.encoded_size() + self.page.encoded_size() + } + + fn encode(&self, buf: &mut BytesMut) { + self.stream_id.encode(buf); + self.topic_id.encode(buf); + self.page.encode(buf); + } +} + +impl WireDecode for GetPartitionsRequest { + fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { + let (stream_id, stream_size) = WireIdentifier::decode(buf)?; + let (topic_id, topic_size) = WireIdentifier::decode(&buf[stream_size..])?; + let (page, consumed) = decode_trailing_page(buf, stream_size + topic_size)?; + Ok(( + Self { + stream_id, + topic_id, + page, + }, + consumed, + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives::page::WirePageCursor; + + fn request() -> GetPartitionsRequest { + GetPartitionsRequest { + stream_id: WireIdentifier::numeric(1), + topic_id: WireIdentifier::named("events").unwrap(), + page: WirePageQuery { + descending: true, + limit: 100, + cursor: Some(WirePageCursor::Id(41)), + ..WirePageQuery::default() + }, + } + } + + #[test] + fn given_a_page_when_round_tripping_should_keep_every_field() { + let request = request(); + let bytes = request.to_bytes(); + assert_eq!(bytes.len(), request.encoded_size()); + assert_eq!( + GetPartitionsRequest::decode(&bytes).unwrap(), + (request, bytes.len()) + ); + } + + #[test] + fn given_a_first_page_when_encoding_should_pin_the_bytes() { + let request = GetPartitionsRequest { + stream_id: WireIdentifier::numeric(1), + topic_id: WireIdentifier::numeric(2), + page: WirePageQuery::default(), + }; + let mut expected = WireIdentifier::numeric(1).to_bytes().to_vec(); + expected.extend_from_slice(&WireIdentifier::numeric(2).to_bytes()); + expected.extend_from_slice(&[0, 0, 100, 0, 0, 0, 0, 0]); + assert_eq!(&request.to_bytes()[..], &expected[..]); + } + + #[test] + fn given_bytes_after_the_page_or_no_page_when_decoding_should_refuse() { + let mut bytes = request().to_bytes().to_vec(); + bytes.push(0); + assert!(GetPartitionsRequest::decode(&bytes).is_err()); + let mut parents = WireIdentifier::numeric(1).to_bytes().to_vec(); + parents.extend_from_slice(&WireIdentifier::numeric(2).to_bytes()); + assert!(GetPartitionsRequest::decode(&parents).is_err()); + } +}
diff --git a/core/binary_protocol/src/requests/partitions/mod.rs b/core/binary_protocol/src/requests/partitions/mod.rs index 85bb37f..459de1a 100644 --- a/core/binary_protocol/src/requests/partitions/mod.rs +++ b/core/binary_protocol/src/requests/partitions/mod.rs
@@ -18,6 +18,7 @@ pub mod create_partitions; pub mod create_partitions_with_assignments; pub mod delete_partitions; +pub mod get_partitions; pub mod install_consumer_group_owner; pub mod retire_consumer_group_owners; pub mod transition_partition_history; @@ -26,6 +27,7 @@ pub use create_partitions::CreatePartitionsRequest; pub use create_partitions_with_assignments::CreatePartitionsWithAssignmentsRequest; pub use delete_partitions::DeletePartitionsRequest; +pub use get_partitions::GetPartitionsRequest; pub use install_consumer_group_owner::InstallConsumerGroupOwnerRequest; pub use retire_consumer_group_owners::RetireConsumerGroupOwnersRequest; pub use transition_partition_history::TransitionPartitionHistoryRequest;
diff --git a/core/binary_protocol/src/requests/streams/get_streams.rs b/core/binary_protocol/src/requests/streams/get_streams.rs index 897e898..5b28c15 100644 --- a/core/binary_protocol/src/requests/streams/get_streams.rs +++ b/core/binary_protocol/src/requests/streams/get_streams.rs
@@ -17,37 +17,79 @@ use crate::WireError; use crate::codec::{WireDecode, WireEncode}; +use crate::primitives::page::{WirePageQuery, decode_trailing_page}; use bytes::BytesMut; -/// `GetStreams` request. Wire format: empty. +/// `GetStreams` request: one page of the streams. +/// +/// Wire format: `[page]` #[derive(Debug, Clone, PartialEq, Eq)] -pub struct GetStreamsRequest; +pub struct GetStreamsRequest { + pub page: WirePageQuery, +} impl WireEncode for GetStreamsRequest { fn encoded_size(&self) -> usize { - 0 + self.page.encoded_size() } - fn encode(&self, _buf: &mut BytesMut) {} + fn encode(&self, buf: &mut BytesMut) { + self.page.encode(buf); + } } impl WireDecode for GetStreamsRequest { - fn decode(_buf: &[u8]) -> Result<(Self, usize), WireError> { - Ok((Self, 0)) + fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { + let (page, consumed) = decode_trailing_page(buf, 0)?; + Ok((Self { page }, consumed)) } } #[cfg(test)] mod tests { use super::*; + use crate::WireName; + use crate::primitives::page::{WirePageCursor, WirePageOrder}; #[test] - fn roundtrip() { - let req = GetStreamsRequest; - let bytes = req.to_bytes(); - assert!(bytes.is_empty()); - let (decoded, consumed) = GetStreamsRequest::decode(&bytes).unwrap(); - assert_eq!(consumed, 0); - assert_eq!(decoded, req); + fn given_a_page_when_round_tripping_should_keep_every_field() { + let request = GetStreamsRequest { + page: WirePageQuery { + order: WirePageOrder::Created, + descending: true, + limit: 20, + cursor: Some(WirePageCursor::Created { + created_at: 9, + id: 4, + }), + name: Some(WireName::new("ord").unwrap()), + }, + }; + let bytes = request.to_bytes(); + assert_eq!(bytes.len(), request.encoded_size()); + assert_eq!( + GetStreamsRequest::decode(&bytes).unwrap(), + (request, bytes.len()) + ); + } + + #[test] + fn given_a_first_page_when_encoding_should_pin_the_bytes() { + let request = GetStreamsRequest { + page: WirePageQuery::default(), + }; + assert_eq!(&request.to_bytes()[..], &[0, 0, 100, 0, 0, 0, 0, 0]); + } + + #[test] + fn given_no_page_or_bytes_after_it_when_decoding_should_refuse() { + assert!(GetStreamsRequest::decode(&[]).is_err()); + let mut bytes = GetStreamsRequest { + page: WirePageQuery::default(), + } + .to_bytes() + .to_vec(); + bytes.push(0); + assert!(GetStreamsRequest::decode(&bytes).is_err()); } }
diff --git a/core/binary_protocol/src/requests/topics/get_topics.rs b/core/binary_protocol/src/requests/topics/get_topics.rs index 1c52fd3..b0bf0ab 100644 --- a/core/binary_protocol/src/requests/topics/get_topics.rs +++ b/core/binary_protocol/src/requests/topics/get_topics.rs
@@ -15,57 +15,84 @@ // specific language governing permissions and limitations // under the License. -use crate::WireError; -use crate::WireIdentifier; use crate::codec::{WireDecode, WireEncode}; +use crate::primitives::page::{WirePageQuery, decode_trailing_page}; +use crate::{WireError, WireIdentifier}; use bytes::BytesMut; -/// `GetTopics` request. Wire format: `[stream_id:WireIdentifier]` +/// `GetTopics` request: one page of the topics of a stream. +/// +/// Wire format: `[stream_id:WireIdentifier][page]` #[derive(Debug, Clone, PartialEq, Eq)] pub struct GetTopicsRequest { pub stream_id: WireIdentifier, + pub page: WirePageQuery, } impl WireEncode for GetTopicsRequest { fn encoded_size(&self) -> usize { - self.stream_id.encoded_size() + self.stream_id.encoded_size() + self.page.encoded_size() } fn encode(&self, buf: &mut BytesMut) { self.stream_id.encode(buf); + self.page.encode(buf); } } impl WireDecode for GetTopicsRequest { fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { - let (stream_id, consumed) = WireIdentifier::decode(buf)?; - Ok((Self { stream_id }, consumed)) + let (stream_id, stream_size) = WireIdentifier::decode(buf)?; + let (page, consumed) = decode_trailing_page(buf, stream_size)?; + Ok((Self { stream_id, page }, consumed)) } } #[cfg(test)] mod tests { use super::*; + use crate::primitives::page::WirePageCursor; #[test] - fn roundtrip_numeric() { - let req = GetTopicsRequest { - stream_id: WireIdentifier::numeric(42), + fn given_a_page_when_round_tripping_should_keep_every_field() { + let request = GetTopicsRequest { + stream_id: WireIdentifier::named("my-stream").unwrap(), + page: WirePageQuery { + limit: 3, + cursor: Some(WirePageCursor::Id(7)), + ..WirePageQuery::default() + }, }; - let bytes = req.to_bytes(); - let (decoded, consumed) = GetTopicsRequest::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, req); + let bytes = request.to_bytes(); + assert_eq!(bytes.len(), request.encoded_size()); + assert_eq!( + GetTopicsRequest::decode(&bytes).unwrap(), + (request, bytes.len()) + ); } #[test] - fn roundtrip_named() { - let req = GetTopicsRequest { - stream_id: WireIdentifier::named("my-stream").unwrap(), + fn given_a_first_page_when_encoding_should_pin_the_bytes() { + let request = GetTopicsRequest { + stream_id: WireIdentifier::numeric(42), + page: WirePageQuery::default(), }; - let bytes = req.to_bytes(); - let (decoded, consumed) = GetTopicsRequest::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, req); + let mut expected = WireIdentifier::numeric(42).to_bytes().to_vec(); + expected.extend_from_slice(&[0, 0, 100, 0, 0, 0, 0, 0]); + assert_eq!(&request.to_bytes()[..], &expected[..]); + } + + #[test] + fn given_no_page_or_bytes_after_it_when_decoding_should_refuse() { + let stream = WireIdentifier::numeric(42).to_bytes(); + assert!(GetTopicsRequest::decode(&stream).is_err()); + let mut bytes = GetTopicsRequest { + stream_id: WireIdentifier::numeric(42), + page: WirePageQuery::default(), + } + .to_bytes() + .to_vec(); + bytes.push(0); + assert!(GetTopicsRequest::decode(&bytes).is_err()); } }
diff --git a/core/binary_protocol/src/requests/users/get_users.rs b/core/binary_protocol/src/requests/users/get_users.rs index edc3f86..ec81801 100644 --- a/core/binary_protocol/src/requests/users/get_users.rs +++ b/core/binary_protocol/src/requests/users/get_users.rs
@@ -17,37 +17,79 @@ use crate::WireError; use crate::codec::{WireDecode, WireEncode}; +use crate::primitives::page::{WirePageQuery, decode_trailing_page}; use bytes::BytesMut; -/// `GetUsers` request. Wire format: empty. +/// `GetUsers` request: one page of the users. +/// +/// Wire format: `[page]` #[derive(Debug, Clone, PartialEq, Eq)] -pub struct GetUsersRequest; +pub struct GetUsersRequest { + pub page: WirePageQuery, +} impl WireEncode for GetUsersRequest { fn encoded_size(&self) -> usize { - 0 + self.page.encoded_size() } - fn encode(&self, _buf: &mut BytesMut) {} + fn encode(&self, buf: &mut BytesMut) { + self.page.encode(buf); + } } impl WireDecode for GetUsersRequest { - fn decode(_buf: &[u8]) -> Result<(Self, usize), WireError> { - Ok((Self, 0)) + fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { + let (page, consumed) = decode_trailing_page(buf, 0)?; + Ok((Self { page }, consumed)) } } #[cfg(test)] mod tests { use super::*; + use crate::WireName; + use crate::primitives::page::{WirePageCursor, WirePageOrder}; #[test] - fn roundtrip() { - let req = GetUsersRequest; - let bytes = req.to_bytes(); - assert!(bytes.is_empty()); - let (decoded, consumed) = GetUsersRequest::decode(&bytes).unwrap(); - assert_eq!(consumed, 0); - assert_eq!(decoded, req); + fn given_a_page_when_round_tripping_should_keep_every_field() { + let request = GetUsersRequest { + page: WirePageQuery { + order: WirePageOrder::Created, + descending: true, + limit: 20, + cursor: Some(WirePageCursor::Created { + created_at: 9, + id: 4, + }), + name: Some(WireName::new("ord").unwrap()), + }, + }; + let bytes = request.to_bytes(); + assert_eq!(bytes.len(), request.encoded_size()); + assert_eq!( + GetUsersRequest::decode(&bytes).unwrap(), + (request, bytes.len()) + ); + } + + #[test] + fn given_a_first_page_when_encoding_should_pin_the_bytes() { + let request = GetUsersRequest { + page: WirePageQuery::default(), + }; + assert_eq!(&request.to_bytes()[..], &[0, 0, 100, 0, 0, 0, 0, 0]); + } + + #[test] + fn given_no_page_or_bytes_after_it_when_decoding_should_refuse() { + assert!(GetUsersRequest::decode(&[]).is_err()); + let mut bytes = GetUsersRequest { + page: WirePageQuery::default(), + } + .to_bytes() + .to_vec(); + bytes.push(0); + assert!(GetUsersRequest::decode(&bytes).is_err()); } }
diff --git a/core/binary_protocol/src/responses/consumer_groups/get_consumer_groups.rs b/core/binary_protocol/src/responses/consumer_groups/get_consumer_groups.rs deleted file mode 100644 index bc43247..0000000 --- a/core/binary_protocol/src/responses/consumer_groups/get_consumer_groups.rs +++ /dev/null
@@ -1,109 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -use super::consumer_group_response::ConsumerGroupResponse; -use crate::WireError; -use crate::codec::{WireDecode, WireEncode}; -use bytes::BytesMut; - -/// `GetConsumerGroups` response: sequential consumer group headers. -/// -/// Wire format: -/// ```text -/// [ConsumerGroupResponse]* -/// ``` -/// -/// Empty payload means zero groups. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct GetConsumerGroupsResponse { - pub groups: Vec<ConsumerGroupResponse>, -} - -impl WireEncode for GetConsumerGroupsResponse { - fn encoded_size(&self) -> usize { - self.groups.iter().map(WireEncode::encoded_size).sum() - } - - fn encode(&self, buf: &mut BytesMut) { - for group in &self.groups { - group.encode(buf); - } - } -} - -impl WireDecode for GetConsumerGroupsResponse { - fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { - let mut groups = Vec::new(); - let mut pos = 0; - while pos < buf.len() { - let (group, consumed) = ConsumerGroupResponse::decode(&buf[pos..])?; - pos += consumed; - groups.push(group); - } - Ok((Self { groups }, pos)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::WireName; - - fn sample_group(id: u32, name: &str) -> ConsumerGroupResponse { - ConsumerGroupResponse { - id, - partitions_count: 4, - members_count: 2, - name: WireName::new(name).unwrap(), - } - } - - #[test] - fn roundtrip_empty() { - let resp = GetConsumerGroupsResponse { groups: vec![] }; - let bytes = resp.to_bytes(); - assert!(bytes.is_empty()); - let (decoded, consumed) = GetConsumerGroupsResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, 0); - assert_eq!(decoded, resp); - } - - #[test] - fn roundtrip_multiple() { - let resp = GetConsumerGroupsResponse { - groups: vec![sample_group(1, "group-a"), sample_group(2, "group-b")], - }; - let bytes = resp.to_bytes(); - let (decoded, consumed) = GetConsumerGroupsResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, resp); - } - - #[test] - fn truncated_returns_error() { - let resp = GetConsumerGroupsResponse { - groups: vec![sample_group(1, "g")], - }; - let bytes = resp.to_bytes(); - for i in 1..bytes.len() { - assert!( - GetConsumerGroupsResponse::decode(&bytes[..i]).is_err(), - "expected error for truncation at byte {i}" - ); - } - } -}
diff --git a/core/binary_protocol/src/responses/consumer_groups/mod.rs b/core/binary_protocol/src/responses/consumer_groups/mod.rs index 5abd62f..ccc850e 100644 --- a/core/binary_protocol/src/responses/consumer_groups/mod.rs +++ b/core/binary_protocol/src/responses/consumer_groups/mod.rs
@@ -19,7 +19,6 @@ mod create_consumer_group; mod delete_consumer_group; pub mod get_consumer_group; -pub mod get_consumer_groups; mod join_consumer_group; mod leave_consumer_group; pub mod sync_consumer_group; @@ -29,7 +28,6 @@ pub use create_consumer_group::CreateConsumerGroupResponse; pub use delete_consumer_group::DeleteConsumerGroupResponse; pub use get_consumer_group::{ConsumerGroupDetailsResponse, ConsumerGroupMemberResponse}; -pub use get_consumer_groups::GetConsumerGroupsResponse; pub use join_consumer_group::JoinConsumerGroupResponse; pub use leave_consumer_group::LeaveConsumerGroupResponse; pub use sync_consumer_group::SyncConsumerGroupResponse;
diff --git a/core/binary_protocol/src/responses/mod.rs b/core/binary_protocol/src/responses/mod.rs index a009c15..c9ead5e 100644 --- a/core/binary_protocol/src/responses/mod.rs +++ b/core/binary_protocol/src/responses/mod.rs
@@ -19,12 +19,15 @@ pub mod consumer_groups; pub mod consumer_offsets; pub mod messages; +pub mod page; pub mod personal_access_tokens; pub mod streams; pub mod system; pub mod topics; pub mod users; +pub use page::PageResponse; + use crate::WireError; use crate::codec::{WireDecode, WireEncode}; use bytes::BytesMut;
diff --git a/core/binary_protocol/src/responses/page.rs b/core/binary_protocol/src/responses/page.rs new file mode 100644 index 0000000..4334fc3 --- /dev/null +++ b/core/binary_protocol/src/responses/page.rs
@@ -0,0 +1,212 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::WireError; +use crate::codec::{WireDecode, WireEncode, read_u32_le}; +use crate::primitives::page::{ + MAX_PAGE_LIMIT, WirePageCursor, optional_cursor_size, put_optional_cursor, read_optional_cursor, +}; +use bytes::{BufMut, BytesMut}; +use std::borrow::Cow; + +/// One page of a list command around the item codec of that list. +/// +/// Wire format: +/// ```text +/// [next_len:u8][next] 0 = last page +/// [count:u32] +/// [item] * count +/// ``` +/// +/// A page is a whole reply body, so a decode refuses bytes after the last item. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PageResponse<T> { + pub items: Vec<T>, + /// The position to continue after, `None` on the last page. A page can be + /// short or empty and still carry it. + pub next: Option<WirePageCursor>, +} + +impl<T: WireEncode> WireEncode for PageResponse<T> { + fn encoded_size(&self) -> usize { + optional_cursor_size(self.next.as_ref()) + + 4 + + self + .items + .iter() + .map(WireEncode::encoded_size) + .sum::<usize>() + } + + #[allow(clippy::cast_possible_truncation)] + fn encode(&self, buf: &mut BytesMut) { + put_optional_cursor(buf, self.next.as_ref()); + buf.put_u32_le(self.items.len() as u32); + for item in &self.items { + item.encode(buf); + } + } +} + +impl<T: WireDecode> WireDecode for PageResponse<T> { + fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { + let (next, mut position) = read_optional_cursor(buf, 0)?; + let count = read_u32_le(buf, position)? as usize; + position += 4; + // A server never sends more than `MAX_PAGE_LIMIT` items, so a corrupt + // count cannot make the decoder reserve more than that. + let mut items = Vec::with_capacity(count.min(MAX_PAGE_LIMIT as usize)); + for _ in 0..count { + let (item, consumed) = T::decode(&buf[position..])?; + position += consumed; + items.push(item); + } + if position != buf.len() { + return Err(WireError::Validation(Cow::Owned(format!( + "{} bytes after the last item of a page", + buf.len() - position + )))); + } + Ok((Self { items, next }, position)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::WireName; + use crate::primitives::partition_history::PartitionContext; + use crate::responses::consumer_groups::ConsumerGroupResponse; + use crate::responses::topics::get_topic::PartitionResponse; + + fn group(id: u32, name: &str) -> ConsumerGroupResponse { + ConsumerGroupResponse { + id, + partitions_count: 3, + members_count: 1, + name: WireName::new(name).unwrap(), + } + } + + #[test] + fn given_items_and_a_cursor_when_round_tripping_should_keep_both() { + let page = PageResponse { + items: vec![group(1, "first"), group(4, "second")], + next: Some(WirePageCursor::Id(4)), + }; + let bytes = page.to_bytes(); + assert_eq!(bytes.len(), page.encoded_size()); + assert_eq!(&bytes[..15], &[9, 1, 4, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1]); + assert_eq!( + PageResponse::<ConsumerGroupResponse>::decode(&bytes).unwrap(), + (page, bytes.len()) + ); + } + + #[test] + fn given_an_empty_last_page_when_encoding_should_pin_the_bytes() { + let page = PageResponse::<ConsumerGroupResponse> { + items: Vec::new(), + next: None, + }; + let bytes = page.to_bytes(); + assert_eq!(&bytes[..], &[0, 0, 0, 0, 0]); + assert_eq!( + PageResponse::<ConsumerGroupResponse>::decode(&bytes).unwrap(), + (page, 5) + ); + } + + #[test] + fn given_a_count_above_the_items_when_decoding_should_refuse_without_reserving_it() { + let mut bytes = PageResponse { + items: vec![group(1, "first")], + next: None, + } + .to_bytes() + .to_vec(); + bytes[1..5].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(PageResponse::<ConsumerGroupResponse>::decode(&bytes).is_err()); + } + + #[test] + fn given_bytes_after_the_last_item_when_decoding_should_refuse() { + let mut bytes = PageResponse { + items: vec![group(1, "first")], + next: Some(WirePageCursor::Id(1)), + } + .to_bytes() + .to_vec(); + bytes.push(0); + assert!(PageResponse::<ConsumerGroupResponse>::decode(&bytes).is_err()); + assert!(PageResponse::<ConsumerGroupResponse>::decode_from(&bytes).is_err()); + } + + #[test] + fn given_a_truncated_page_when_decoding_should_refuse() { + let bytes = PageResponse { + items: vec![group(1, "first"), group(2, "second")], + next: Some(WirePageCursor::Created { + created_at: 9, + id: 2, + }), + } + .to_bytes(); + for length in 0..bytes.len() { + assert!( + PageResponse::<ConsumerGroupResponse>::decode(&bytes[..length]).is_err(), + "a page cut at {length} bytes must not decode" + ); + } + } + + #[test] + fn given_a_partitions_page_when_round_tripping_or_truncating_should_keep_it_or_refuse() { + let partition = |id: u32, members: Vec<u8>| PartitionResponse { + id, + created_at: 7, + segments_count: 1, + current_offset: 0, + size_bytes: 0, + messages_count: 0, + context: PartitionContext { + incarnation: 3, + owner_generation: 0, + metadata_op: 11, + }, + in_sync_members: members.clone(), + members, + }; + let page = PageResponse { + items: vec![partition(0, vec![1, 2]), partition(1, Vec::new())], + next: Some(WirePageCursor::Id(1)), + }; + let bytes = page.to_bytes(); + assert_eq!(bytes.len(), 10 + 4 + (66 + 4) + 66); + assert_eq!(&bytes[..14], &[9, 1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0]); + assert_eq!( + PageResponse::<PartitionResponse>::decode(&bytes).unwrap(), + (page, bytes.len()) + ); + for length in 0..bytes.len() { + assert!( + PageResponse::<PartitionResponse>::decode(&bytes[..length]).is_err(), + "a page cut at {length} bytes must not decode" + ); + } + } +}
diff --git a/core/binary_protocol/src/responses/streams/get_stream.rs b/core/binary_protocol/src/responses/streams/get_stream.rs index b8b6aa3..b7eedfd 100644 --- a/core/binary_protocol/src/responses/streams/get_stream.rs +++ b/core/binary_protocol/src/responses/streams/get_stream.rs
@@ -24,7 +24,8 @@ use crate::responses::streams::StreamResponse; use bytes::{BufMut, BytesMut}; -/// Topic header within a `GetStream` response. +/// Topic header on the wire. Used in the `GetStream`, `GetTopic` and +/// `CreateTopic` responses and in a `GetTopics` page. /// /// Wire format (33 + `name_len` + options bytes): /// ```text @@ -39,7 +40,7 @@ /// re-sends only `options`; the effective configuration is the union. /// Message expiry, compression and the size cap live in those blocks only. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct TopicHeader { +pub struct TopicResponse { pub id: u32, pub created_at: u64, pub partitions_count: u32, @@ -50,11 +51,11 @@ pub derived_options: WireOptions, } -impl TopicHeader { +impl TopicResponse { pub(crate) const FIXED_SIZE: usize = 4 + 8 + 4 + 8 + 8 + 1; // 33 } -impl WireEncode for TopicHeader { +impl WireEncode for TopicResponse { fn encoded_size(&self) -> usize { Self::FIXED_SIZE + self.name.len() @@ -74,7 +75,7 @@ } } -impl WireDecode for TopicHeader { +impl WireDecode for TopicResponse { fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { let id = read_u32_le(buf, 0)?; let created_at = read_u64_le(buf, 4)?; @@ -108,7 +109,7 @@ /// /// Wire format: /// ```text -/// [StreamResponse][TopicHeader]* +/// [StreamResponse][TopicResponse]* /// ``` /// /// The number of topics is determined by `stream.topics_count` or by @@ -116,7 +117,7 @@ #[derive(Debug, Clone, PartialEq, Eq)] pub struct GetStreamResponse { pub stream: StreamResponse, - pub topics: Vec<TopicHeader>, + pub topics: Vec<TopicResponse>, } impl WireEncode for GetStreamResponse { @@ -140,7 +141,7 @@ /// Smallest a topic header can encode as: the fixed ids, timestamps, sizes, /// counts and name length, plus the shortest name `WireName` accepts (one byte, /// since it rejects an empty one) and two empty length-prefixed option blocks. -const MIN_TOPIC_HEADER_SIZE: usize = TopicHeader::FIXED_SIZE + 1 + 4 + 4; +const MIN_TOPIC_RESPONSE_SIZE: usize = TopicResponse::FIXED_SIZE + 1 + 4 + 4; impl WireDecode for GetStreamResponse { fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { @@ -150,10 +151,10 @@ let mut topics = Vec::with_capacity(crate::codec::bounded_capacity( stream.topics_count as usize, buf.len().saturating_sub(pos), - MIN_TOPIC_HEADER_SIZE, + MIN_TOPIC_RESPONSE_SIZE, )); for _ in 0..stream.topics_count { - let (topic, consumed) = TopicHeader::decode(&buf[pos..])?; + let (topic, consumed) = TopicResponse::decode(&buf[pos..])?; pos += consumed; topics.push(topic); } @@ -178,8 +179,8 @@ } } - fn sample_topic(id: u32, name: &str) -> TopicHeader { - TopicHeader { + fn sample_topic(id: u32, name: &str) -> TopicResponse { + TopicResponse { id, created_at: 1_710_000_000_000, partitions_count: 3, @@ -219,28 +220,28 @@ } #[test] - fn topic_header_roundtrip() { + fn topic_response_roundtrip() { let topic = sample_topic(5, "events"); let bytes = topic.to_bytes(); - assert_eq!(bytes.len(), TopicHeader::FIXED_SIZE + 6 + 4 + 4); - let (decoded, consumed) = TopicHeader::decode(&bytes).unwrap(); + assert_eq!(bytes.len(), TopicResponse::FIXED_SIZE + 6 + 4 + 4); + let (decoded, consumed) = TopicResponse::decode(&bytes).unwrap(); assert_eq!(consumed, bytes.len()); assert_eq!(decoded, topic); } #[test] - fn min_topic_header_size_matches_the_shortest_encoding() { + fn min_topic_response_size_matches_the_shortest_encoding() { let bytes = sample_topic(1, "t").to_bytes(); - assert_eq!(bytes.len(), MIN_TOPIC_HEADER_SIZE); + assert_eq!(bytes.len(), MIN_TOPIC_RESPONSE_SIZE); } #[test] - fn topic_header_truncated_returns_error() { + fn topic_response_truncated_returns_error() { let topic = sample_topic(1, "t"); let bytes = topic.to_bytes(); for i in 0..bytes.len() { assert!( - TopicHeader::decode(&bytes[..i]).is_err(), + TopicResponse::decode(&bytes[..i]).is_err(), "expected error for truncation at byte {i}" ); }
diff --git a/core/binary_protocol/src/responses/streams/get_streams.rs b/core/binary_protocol/src/responses/streams/get_streams.rs deleted file mode 100644 index 33d3acd..0000000 --- a/core/binary_protocol/src/responses/streams/get_streams.rs +++ /dev/null
@@ -1,107 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -use crate::WireError; -use crate::codec::{WireDecode, WireEncode}; -use crate::responses::streams::StreamResponse; -use bytes::BytesMut; - -/// `GetStreams` response: sequential stream headers. -/// -/// Wire format: -/// ```text -/// [StreamResponse]* -/// ``` -/// -/// Empty payload means zero streams. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct GetStreamsResponse { - pub streams: Vec<StreamResponse>, -} - -impl WireEncode for GetStreamsResponse { - fn encoded_size(&self) -> usize { - self.streams.iter().map(WireEncode::encoded_size).sum() - } - - fn encode(&self, buf: &mut BytesMut) { - for stream in &self.streams { - stream.encode(buf); - } - } -} - -impl WireDecode for GetStreamsResponse { - fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { - let mut streams = Vec::new(); - let mut pos = 0; - while pos < buf.len() { - let (stream, consumed) = StreamResponse::decode(&buf[pos..])?; - pos += consumed; - streams.push(stream); - } - Ok((Self { streams }, pos)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{WireName, WireOptions}; - - #[test] - fn roundtrip_empty() { - let resp = GetStreamsResponse { streams: vec![] }; - let bytes = resp.to_bytes(); - assert!(bytes.is_empty()); - let (decoded, consumed) = GetStreamsResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, 0); - assert_eq!(decoded, resp); - } - - #[test] - fn roundtrip_multiple() { - let resp = GetStreamsResponse { - streams: vec![ - StreamResponse { - id: 1, - created_at: 100, - topics_count: 2, - size_bytes: 512, - messages_count: 50, - name: WireName::new("s1").unwrap(), - options: WireOptions::empty(), - derived_options: WireOptions::empty(), - }, - StreamResponse { - id: 2, - created_at: 200, - topics_count: 0, - size_bytes: 0, - messages_count: 0, - name: WireName::new("stream-two").unwrap(), - options: WireOptions::empty(), - derived_options: WireOptions::empty(), - }, - ], - }; - let bytes = resp.to_bytes(); - let (decoded, consumed) = GetStreamsResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, resp); - } -}
diff --git a/core/binary_protocol/src/responses/streams/mod.rs b/core/binary_protocol/src/responses/streams/mod.rs index 09fe7ec..e8e06cf 100644 --- a/core/binary_protocol/src/responses/streams/mod.rs +++ b/core/binary_protocol/src/responses/streams/mod.rs
@@ -18,12 +18,10 @@ mod create_stream; mod delete_stream; pub mod get_stream; -pub mod get_streams; mod stream_response; pub use super::EmptyResponse; pub use create_stream::CreateStreamResponse; pub use delete_stream::DeleteStreamResponse; -pub use get_stream::{GetStreamResponse, TopicHeader}; -pub use get_streams::GetStreamsResponse; +pub use get_stream::{GetStreamResponse, TopicResponse}; pub use stream_response::StreamResponse;
diff --git a/core/binary_protocol/src/responses/topics/create_topic.rs b/core/binary_protocol/src/responses/topics/create_topic.rs index 397cc15..89148c0 100644 --- a/core/binary_protocol/src/responses/topics/create_topic.rs +++ b/core/binary_protocol/src/responses/topics/create_topic.rs
@@ -17,7 +17,7 @@ /// `CreateTopic` reply ships the freshly-created topic. /// -/// Same `[TopicHeader][PartitionResponse]*` layout as `GetTopicResponse`, +/// Same `[TopicResponse][PartitionResponse]*` layout as `GetTopicResponse`, /// so the SDK reuses one decoder for both calls. Legacy server's /// `create_topic_handler` builds this shape directly; the server's metadata /// STM emits the same bytes from `apply`.
diff --git a/core/binary_protocol/src/responses/topics/get_topic.rs b/core/binary_protocol/src/responses/topics/get_topic.rs index b936456..516ed8b 100644 --- a/core/binary_protocol/src/responses/topics/get_topic.rs +++ b/core/binary_protocol/src/responses/topics/get_topic.rs
@@ -18,7 +18,7 @@ use crate::WireError; use crate::codec::{WireDecode, WireEncode, read_u8, read_u32_le, read_u64_le}; use crate::primitives::partition_history::PartitionContext; -use crate::responses::streams::get_stream::TopicHeader; +use crate::responses::streams::get_stream::TopicResponse; use bytes::{BufMut, BytesMut}; /// Partition details within a `GetTopic` response. @@ -124,13 +124,13 @@ /// /// Wire format: /// ```text -/// [TopicHeader][PartitionResponse]* +/// [TopicResponse][PartitionResponse]* /// ``` /// /// The number of partitions must match `topic.partitions_count`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct GetTopicResponse { - pub topic: TopicHeader, + pub topic: TopicResponse, pub partitions: Vec<PartitionResponse>, } @@ -154,7 +154,7 @@ impl WireDecode for GetTopicResponse { fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { - let (topic, mut pos) = TopicHeader::decode(buf)?; + let (topic, mut pos) = TopicResponse::decode(buf)?; // Count-driven so the element stays delimited even when embedded in a // larger payload; the header's variable-length options blocks removed // the old "everything after the header is partitions" property. @@ -178,8 +178,8 @@ use crate::{WireName, WireOptions}; use std::fmt::Write; - fn sample_topic(partitions_count: u32) -> TopicHeader { - TopicHeader { + fn sample_topic(partitions_count: u32) -> TopicResponse { + TopicResponse { id: 1, created_at: 1_710_000_000_000, partitions_count,
diff --git a/core/binary_protocol/src/responses/topics/get_topics.rs b/core/binary_protocol/src/responses/topics/get_topics.rs deleted file mode 100644 index d8f5d9d..0000000 --- a/core/binary_protocol/src/responses/topics/get_topics.rs +++ /dev/null
@@ -1,134 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -use crate::WireError; -use crate::codec::{WireDecode, WireEncode, read_u32_le}; -use crate::responses::streams::get_stream::TopicHeader; -use bytes::{BufMut, BytesMut}; - -/// `GetTopics` response: count-prefixed topic headers. -/// -/// Wire format: -/// ```text -/// [topics_count:u32_le][TopicHeader]* -/// ``` -/// -/// The count prefix is what lets a decoder pre-size its `Vec`: an element -/// carries two variable-length option blocks, so the payload length alone says -/// nothing useful about how many elements are in it. Detecting a short read -/// does not need it - the element decoder errors on one, which is how -/// `GetStreams` and `GetUsers` still run their loops to end-of-payload. This -/// response is the odd one out of the three, and every SDK special-cases it. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct GetTopicsResponse { - pub topics: Vec<TopicHeader>, -} - -impl WireEncode for GetTopicsResponse { - fn encoded_size(&self) -> usize { - 4 + self - .topics - .iter() - .map(WireEncode::encoded_size) - .sum::<usize>() - } - - fn encode(&self, buf: &mut BytesMut) { - #[allow(clippy::cast_possible_truncation)] - buf.put_u32_le(self.topics.len() as u32); - for topic in &self.topics { - topic.encode(buf); - } - } -} - -/// Smallest a topic header can encode as: the fixed ids, timestamps, sizes, -/// counts and name length, plus the shortest name `WireName` accepts (one byte, -/// since it rejects an empty one) and two empty length-prefixed option blocks. -const MIN_TOPIC_HEADER_SIZE: usize = TopicHeader::FIXED_SIZE + 1 + 4 + 4; - -impl WireDecode for GetTopicsResponse { - fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { - let topics_count = read_u32_le(buf, 0)? as usize; - let mut pos = 4; - let mut topics = Vec::with_capacity(crate::codec::bounded_capacity( - topics_count, - buf.len().saturating_sub(pos), - MIN_TOPIC_HEADER_SIZE, - )); - for _ in 0..topics_count { - let (topic, consumed) = TopicHeader::decode(&buf[pos..])?; - pos += consumed; - topics.push(topic); - } - Ok((Self { topics }, pos)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{WireName, WireOptions}; - - fn sample_topic(id: u32, name: &str) -> TopicHeader { - TopicHeader { - id, - created_at: 1_710_000_000_000, - partitions_count: 3, - size_bytes: 1024, - messages_count: 100, - name: WireName::new(name).unwrap(), - options: WireOptions::empty(), - derived_options: WireOptions::empty(), - } - } - - #[test] - fn roundtrip_empty() { - let resp = GetTopicsResponse { topics: vec![] }; - let bytes = resp.to_bytes(); - assert_eq!(bytes.len(), 4); - let (decoded, consumed) = GetTopicsResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, resp); - } - - #[test] - fn roundtrip_multiple() { - let resp = GetTopicsResponse { - topics: vec![sample_topic(1, "events"), sample_topic(2, "logs")], - }; - let bytes = resp.to_bytes(); - let (decoded, consumed) = GetTopicsResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, resp); - } - - #[test] - fn truncated_returns_error() { - let resp = GetTopicsResponse { - topics: vec![sample_topic(1, "t")], - }; - let bytes = resp.to_bytes(); - for i in 1..bytes.len() { - assert!( - GetTopicsResponse::decode(&bytes[..i]).is_err(), - "expected error for truncation at byte {i}" - ); - } - } -}
diff --git a/core/binary_protocol/src/responses/topics/mod.rs b/core/binary_protocol/src/responses/topics/mod.rs index f1279ee..779eddd 100644 --- a/core/binary_protocol/src/responses/topics/mod.rs +++ b/core/binary_protocol/src/responses/topics/mod.rs
@@ -18,10 +18,8 @@ mod create_topic; mod delete_topic; pub mod get_topic; -pub mod get_topics; pub use super::EmptyResponse; pub use create_topic::CreateTopicResponse; pub use delete_topic::DeleteTopicResponse; pub use get_topic::{GetTopicResponse, PartitionResponse}; -pub use get_topics::GetTopicsResponse;
diff --git a/core/binary_protocol/src/responses/users/get_users.rs b/core/binary_protocol/src/responses/users/get_users.rs deleted file mode 100644 index 556f9ed..0000000 --- a/core/binary_protocol/src/responses/users/get_users.rs +++ /dev/null
@@ -1,101 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -use crate::WireError; -use crate::codec::{WireDecode, WireEncode}; -use crate::responses::users::user_response::UserResponse; -use bytes::BytesMut; - -/// `GetUsers` response: sequential user headers. -/// -/// Wire format: -/// ```text -/// [UserResponse]* -/// ``` -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct GetUsersResponse { - pub users: Vec<UserResponse>, -} - -impl WireEncode for GetUsersResponse { - fn encoded_size(&self) -> usize { - self.users.iter().map(WireEncode::encoded_size).sum() - } - - fn encode(&self, buf: &mut BytesMut) { - for user in &self.users { - user.encode(buf); - } - } -} - -impl WireDecode for GetUsersResponse { - fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> { - let mut users = Vec::new(); - let mut pos = 0; - while pos < buf.len() { - let (user, consumed) = UserResponse::decode(&buf[pos..])?; - pos += consumed; - users.push(user); - } - Ok((Self { users }, pos)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{WireName, WireOptions}; - - #[test] - fn roundtrip_empty() { - let resp = GetUsersResponse { users: vec![] }; - let bytes = resp.to_bytes(); - assert!(bytes.is_empty()); - let (decoded, consumed) = GetUsersResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, 0); - assert_eq!(decoded, resp); - } - - #[test] - fn roundtrip_multiple() { - let resp = GetUsersResponse { - users: vec![ - UserResponse { - id: 1, - created_at: 100, - status: 1, - username: WireName::new("admin").unwrap(), - options: WireOptions::empty(), - derived_options: WireOptions::empty(), - }, - UserResponse { - id: 2, - created_at: 200, - status: 2, - username: WireName::new("alice").unwrap(), - options: WireOptions::empty(), - derived_options: WireOptions::empty(), - }, - ], - }; - let bytes = resp.to_bytes(); - let (decoded, consumed) = GetUsersResponse::decode(&bytes).unwrap(); - assert_eq!(consumed, bytes.len()); - assert_eq!(decoded, resp); - } -}
diff --git a/core/binary_protocol/src/responses/users/mod.rs b/core/binary_protocol/src/responses/users/mod.rs index e7a8565..9ad7b0d 100644 --- a/core/binary_protocol/src/responses/users/mod.rs +++ b/core/binary_protocol/src/responses/users/mod.rs
@@ -19,7 +19,6 @@ mod create_user; mod delete_user; pub mod get_user; -pub mod get_users; pub mod login_register; pub mod login_user; mod logout_user; @@ -31,7 +30,6 @@ pub use create_user::CreateUserResponse; pub use delete_user::DeleteUserResponse; pub use get_user::UserDetailsResponse; -pub use get_users::GetUsersResponse; pub use login_register::LoginRegisterResponse; pub use login_user::IdentityResponse; pub use logout_user::LogoutUserResponse;
diff --git a/core/binary_protocol/src/version.rs b/core/binary_protocol/src/version.rs index 67f0e0e..1ca96ea 100644 --- a/core/binary_protocol/src/version.rs +++ b/core/binary_protocol/src/version.rs
@@ -110,10 +110,13 @@ /// Version 0.12.1 replaces `WaitForMessages` (107) with `FetchMessages` (109). /// Version 0.12.2 gives each `GetTopic` partition its `members` and /// `in_sync_members` node lists, so a partition record is no longer 64 bytes. +/// Version 0.12.3 adds a required page block to `GetStreams`, `GetTopics`, +/// `GetConsumerGroups` and `GetUsers`, answers each of them with one page, and +/// adds `GetPartitions` (404). /// Finalize this number and the minimum during stable release preparation. /// Released servers using protocol 0.11.0 accept every 0.11.x patch, so an /// incompatible release needs a new minor version for those servers to reject it. -pub const IGGY_PROTOCOL_VERSION: u32 = pack_protocol_version(0, 12, 2); +pub const IGGY_PROTOCOL_VERSION: u32 = pack_protocol_version(0, 12, 3); /// Revision of what replicas send each other, which clients never see. /// @@ -134,8 +137,10 @@ /// released protocols has been verified. Decide the range per stable release. /// /// Version 0.12.0 clients can send the retired `WaitForMessages` (107) command, -/// and 0.12.1 clients read every `GetTopic` partition as a 64-byte record. -pub const IGGY_PROTOCOL_VERSION_MIN: u32 = pack_protocol_version(0, 12, 2); +/// 0.12.1 clients read every `GetTopic` partition as a 64-byte record, and +/// 0.12.2 clients send the list commands without a page block and read each +/// list whole. +pub const IGGY_PROTOCOL_VERSION_MIN: u32 = pack_protocol_version(0, 12, 3); const _: () = assert!(IGGY_PROTOCOL_VERSION_MIN > 0 && IGGY_PROTOCOL_VERSION_MIN <= IGGY_PROTOCOL_VERSION); @@ -283,8 +288,9 @@ assert!(!is_protocol_compatible(pack_protocol_version(0, 11, 1))); assert!(!is_protocol_compatible(pack_protocol_version(0, 12, 0))); assert!(!is_protocol_compatible(pack_protocol_version(0, 12, 1))); - assert!(is_protocol_compatible(pack_protocol_version(0, 12, 2))); - assert!(!is_protocol_compatible(pack_protocol_version(0, 12, 3))); + assert!(!is_protocol_compatible(pack_protocol_version(0, 12, 2))); + assert!(is_protocol_compatible(pack_protocol_version(0, 12, 3))); + assert!(!is_protocol_compatible(pack_protocol_version(0, 12, 4))); } #[test] @@ -294,8 +300,8 @@ } #[test] - fn min_requires_the_partition_member_protocol() { - assert_eq!(IGGY_PROTOCOL_VERSION_MIN, pack_protocol_version(0, 12, 2)); + fn min_requires_the_page_block_protocol() { + assert_eq!(IGGY_PROTOCOL_VERSION_MIN, pack_protocol_version(0, 12, 3)); } #[test]
diff --git a/core/cli/Cargo.toml b/core/cli/Cargo.toml index 470c2b4..a7f2695 100644 --- a/core/cli/Cargo.toml +++ b/core/cli/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy-cli" -version = "0.15.0" +version = "0.15.1-edge.1" edition = "2024" rust-version.workspace = true authors = ["bartosz.ciesla@gmail.com"]
diff --git a/core/cli/src/args/common.rs b/core/cli/src/args/common.rs index 706fead..a1e689f 100644 --- a/core/cli/src/args/common.rs +++ b/core/cli/src/args/common.rs
@@ -15,12 +15,16 @@ // specific language governing permissions and limitations // under the License. +use clap::builder::{NonEmptyStringValueParser, RangedU64ValueParser}; use clap::{Args, ValueEnum}; -use iggy::prelude::OptionKey; +use iggy::prelude::{ + NamedPageQuery, OptionKey, PAGE_CURSOR_PREFIX, PageCursor, PageOrder, PageQuery, +}; use iggy_cli::commands::binary_client::get_clients::GetClientsOutput; use iggy_cli::commands::binary_cluster::get_cluster_metadata::GetClusterMetadataOutput; use iggy_cli::commands::binary_consumer_groups::get_consumer_groups::GetConsumerGroupsOutput; use iggy_cli::commands::binary_context::get_contexts::GetContextsOutput; +use iggy_cli::commands::binary_partitions::get_partitions::GetPartitionsOutput; use iggy_cli::commands::binary_personal_access_tokens::get_personal_access_tokens::GetPersonalAccessTokensOutput; use iggy_cli::commands::binary_streams::get_stream::GetStreamOutput; use iggy_cli::commands::binary_streams::get_streams::GetStreamsOutput; @@ -28,6 +32,7 @@ use iggy_cli::commands::binary_topics::get_topic::GetTopicOutput; use iggy_cli::commands::binary_topics::get_topics::GetTopicsOutput; use iggy_cli::commands::binary_users::get_users::GetUsersOutput; +use iggy_cli::commands::utils::list_rows::ListRows; use std::collections::BTreeSet; #[derive(Debug, Clone, Copy, ValueEnum)] @@ -172,6 +177,97 @@ } } +impl From<ListMode> for GetPartitionsOutput { + fn from(mode: ListMode) -> Self { + match mode { + ListMode::Table => GetPartitionsOutput::Table, + ListMode::List => GetPartitionsOutput::List, + } + } +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +pub(crate) enum ListOrder { + Id, + Created, +} + +impl From<ListOrder> for PageOrder { + fn from(order: ListOrder) -> Self { + match order { + ListOrder::Id => PageOrder::Id, + ListOrder::Created => PageOrder::Created, + } + } +} + +/// The page flags of every list command that reads pages. +#[derive(Debug, Clone, Args)] +pub(crate) struct PageArgs { + /// Print the rows in descending order + #[arg(long)] + pub(crate) desc: bool, + + /// Print at most N rows + /// + /// If more rows follow them, the last line is `next: <CURSOR>`. + /// Pass that cursor to --after to print the rows that follow. + #[arg(long, value_name = "N", value_parser = RangedU64ValueParser::<usize>::new().range(1..))] + pub(crate) limit: Option<usize>, + + /// Print the rows after this cursor + /// + /// The cursor comes from the `next:` line of a list with --limit. + /// Use the same other flags as that list. + #[arg(long, value_name = "CURSOR", value_parser = parse_page_cursor)] + pub(crate) after: Option<PageCursor>, +} + +/// The cursor error of the SDK is `InvalidCommand`, which names no flag. +fn parse_page_cursor(text: &str) -> Result<PageCursor, String> { + text.parse().map_err(|_| { + format!("not a page cursor, expected the {PAGE_CURSOR_PREFIX} text of a \"next:\" line") + }) +} + +/// The page flags of the lists of named entities: streams, topics, consumer +/// groups and users. +#[derive(Debug, Clone, Args)] +pub(crate) struct NamedPageArgs { + /// Order of the rows, by ID or by creation time + #[arg(long, value_enum, default_value_t = ListOrder::Id)] + pub(crate) sort: ListOrder, + + #[command(flatten)] + pub(crate) page: PageArgs, + + /// Print only the rows whose name holds this text (case-sensitive) + #[arg(long, value_name = "TEXT", value_parser = NonEmptyStringValueParser::new())] + pub(crate) name: Option<String>, +} + +impl From<PageArgs> for ListRows { + fn from(args: PageArgs) -> Self { + ListRows { + query: NamedPageQuery::from(PageQuery { + descending: args.desc, + cursor: args.after, + ..PageQuery::default() + }), + row_limit: args.limit, + } + } +} + +impl From<NamedPageArgs> for ListRows { + fn from(args: NamedPageArgs) -> Self { + let mut rows = ListRows::from(args.page); + rows.query.page.order = args.sort.into(); + rows.query.name = args.name; + rows + } +} + #[derive(Debug, Clone, Copy, ValueEnum)] pub(crate) enum ListModeExt { Table,
diff --git a/core/cli/src/args/consumer_group.rs b/core/cli/src/args/consumer_group.rs index efdb502..944de4b 100644 --- a/core/cli/src/args/consumer_group.rs +++ b/core/cli/src/args/consumer_group.rs
@@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::args::common::ListMode; +use crate::args::common::{ListMode, NamedPageArgs}; use clap::{Args, Subcommand}; use iggy::prelude::Identifier; @@ -77,6 +77,7 @@ /// iggy consumer-group list stream 2 --list-mode table /// iggy consumer-group list 3 topic -l table /// iggy consumer-group list production sensor -l table + /// iggy consumer-group list production sensor --desc --limit 20 #[clap(verbatim_doc_comment, visible_alias = "l")] List(ConsumerGroupListArgs), } @@ -150,4 +151,6 @@ /// List mode (table or list) #[clap(short, long, value_enum, default_value_t = ListMode::Table)] pub(crate) list_mode: ListMode, + #[command(flatten)] + pub(crate) page: NamedPageArgs, }
diff --git a/core/cli/src/args/partition.rs b/core/cli/src/args/partition.rs index ccc6977..81a8bb7 100644 --- a/core/cli/src/args/partition.rs +++ b/core/cli/src/args/partition.rs
@@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. +use crate::args::common::{ListMode, PageArgs}; use clap::{Args, Subcommand}; use iggy::prelude::Identifier; @@ -46,6 +47,18 @@ /// iggy partition delete 1 sensor 16 #[clap(verbatim_doc_comment, visible_alias = "d")] Delete(PartitionDeleteArgs), + /// List partitions for the specified topic ID + /// and stream ID. + /// + /// Stream ID can be specified as a stream name or ID + /// Topic ID can be specified as a topic name or ID + /// + /// Examples + /// iggy partition list 1 1 + /// iggy partition list prod sensor -l list + /// iggy partition list prod sensor --desc --limit 100 + #[clap(verbatim_doc_comment, visible_alias = "l")] + List(PartitionListArgs), } #[derive(Debug, Clone, Args)] @@ -81,3 +94,22 @@ #[arg(value_parser = clap::value_parser!(u32).range(1..100_001))] pub(crate) partitions_count: u32, } + +#[derive(Debug, Clone, Args)] +pub(crate) struct PartitionListArgs { + /// Stream ID to list partitions + /// + /// Stream ID can be specified as a stream name or ID + #[arg(value_parser = clap::value_parser!(Identifier))] + pub(crate) stream_id: Identifier, + /// Topic ID to list partitions + /// + /// Topic ID can be specified as a topic name or ID + #[arg(value_parser = clap::value_parser!(Identifier))] + pub(crate) topic_id: Identifier, + /// List mode (table or list) + #[clap(short, long, value_enum, default_value_t = ListMode::Table)] + pub(crate) list_mode: ListMode, + #[command(flatten)] + pub(crate) page: PageArgs, +}
diff --git a/core/cli/src/args/stream.rs b/core/cli/src/args/stream.rs index 2d03c43..37457f1 100644 --- a/core/cli/src/args/stream.rs +++ b/core/cli/src/args/stream.rs
@@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::args::common::{GetOutput, ListOutputArgs, parse_key_value, split_reset}; +use crate::args::common::{GetOutput, ListOutputArgs, NamedPageArgs, parse_key_value, split_reset}; use clap::{Args, Subcommand}; use iggy::prelude::{Identifier, StreamUpdateOptions}; use std::path::PathBuf; @@ -66,6 +66,8 @@ /// iggy stream list /// iggy stream list --list-mode table /// iggy stream list -l table + /// iggy stream list --sort created --desc --limit 20 + /// iggy stream list --name prod --limit 50 --after pg1_AQcAAAAAAAAA #[clap(verbatim_doc_comment, visible_alias = "l")] List(StreamListArgs), } @@ -146,6 +148,9 @@ pub(crate) struct StreamListArgs { #[command(flatten)] pub(crate) list_output: ListOutputArgs, + + #[command(flatten)] + pub(crate) page: NamedPageArgs, } #[cfg(test)]
diff --git a/core/cli/src/args/topic.rs b/core/cli/src/args/topic.rs index 23584fa..127d289 100644 --- a/core/cli/src/args/topic.rs +++ b/core/cli/src/args/topic.rs
@@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::args::common::{GetOutput, ListOutputArgs, parse_key_value, split_reset}; +use crate::args::common::{GetOutput, ListOutputArgs, NamedPageArgs, parse_key_value, split_reset}; use clap::{Args, Subcommand}; use iggy::prelude::{ CompressionAlgorithm, Identifier, IggyExpiry, MaxTopicSize, TopicUpdateOptions, @@ -81,6 +81,8 @@ /// Examples /// iggy topic list 1 /// iggy topic list prod + /// iggy topic list prod --sort created --desc --limit 20 + /// iggy topic list prod --name sensor --limit 50 #[clap(verbatim_doc_comment, visible_alias = "l")] List(TopicListArgs), } @@ -225,6 +227,9 @@ #[command(flatten)] pub(crate) list_output: ListOutputArgs, + + #[command(flatten)] + pub(crate) page: NamedPageArgs, } #[cfg(test)]
diff --git a/core/cli/src/args/user.rs b/core/cli/src/args/user.rs index d947ef5..cbf77be 100644 --- a/core/cli/src/args/user.rs +++ b/core/cli/src/args/user.rs
@@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::args::common::ListMode; +use crate::args::common::{ListMode, NamedPageArgs}; use crate::args::permissions::UserStatusArg; use crate::args::permissions::stream::StreamPermissionsArg; use clap::{Args, Subcommand}; @@ -56,6 +56,7 @@ /// iggy user list /// iggy user list --list-mode table /// iggy user list -l table + /// iggy user list --sort created --desc --limit 20 #[clap(verbatim_doc_comment, visible_alias = "l")] List(UserListArgs), /// Change username for user with given ID @@ -197,6 +198,9 @@ /// List mode (table or list) #[clap(short, long, value_enum, default_value_t = ListMode::Table)] pub(crate) list_mode: ListMode, + + #[command(flatten)] + pub(crate) page: NamedPageArgs, } #[derive(Debug, Clone, Args)]
diff --git a/core/cli/src/commands/binary_consumer_groups/get_consumer_groups.rs b/core/cli/src/commands/binary_consumer_groups/get_consumer_groups.rs index c0b01a6..545cc0f 100644 --- a/core/cli/src/commands/binary_consumer_groups/get_consumer_groups.rs +++ b/core/cli/src/commands/binary_consumer_groups/get_consumer_groups.rs
@@ -16,6 +16,7 @@ // under the License. use crate::commands::cli_command::{CliCommand, PRINT_TARGET}; +use crate::commands::utils::list_rows::{ListRows, print_next}; use anyhow::Context; use async_trait::async_trait; use comfy_table::Table; @@ -44,6 +45,7 @@ stream_id: Identifier, topic_id: Identifier, output: GetConsumerGroupsOutput, + rows: ListRows, } impl GetConsumerGroupsCmd { @@ -51,11 +53,13 @@ stream_id: Identifier, topic_id: Identifier, output: GetConsumerGroupsOutput, + rows: ListRows, ) -> Self { Self { stream_id, topic_id, output, + rows, } } } @@ -70,13 +74,18 @@ } async fn execute_cmd(&mut self, client: &dyn Client) -> anyhow::Result<(), anyhow::Error> { - let consumer_groups = client - .get_consumer_groups(&self.stream_id, &self.topic_id) + let (stream_id, topic_id) = (&self.stream_id, &self.topic_id); + let (consumer_groups, next) = self + .rows + .read(|query| async move { + client + .get_consumer_groups_page(stream_id, topic_id, &query) + .await + }) .await .with_context(|| { format!( - "Problem getting consumer groups for stream with ID: {} and topic with ID: {}", - self.stream_id, self.topic_id + "Problem getting consumer groups for stream with ID: {stream_id} and topic with ID: {topic_id}" ) })?; @@ -107,6 +116,7 @@ }); } } + print_next(next); Ok(()) }
diff --git a/core/cli/src/commands/binary_partitions/get_partitions.rs b/core/cli/src/commands/binary_partitions/get_partitions.rs new file mode 100644 index 0000000..5f6f90e --- /dev/null +++ b/core/cli/src/commands/binary_partitions/get_partitions.rs
@@ -0,0 +1,150 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::commands::cli_command::{CliCommand, PRINT_TARGET}; +use crate::commands::utils::list_rows::{ListRows, print_next}; +use anyhow::Context; +use async_trait::async_trait; +use comfy_table::Table; +use iggy_common::{Client, Identifier, Partition}; +use std::fmt::{self, Display, Formatter}; +use tracing::{Level, event}; + +pub enum GetPartitionsOutput { + Table, + List, +} + +impl Display for GetPartitionsOutput { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + match self { + GetPartitionsOutput::Table => write!(f, "table"), + GetPartitionsOutput::List => write!(f, "list"), + } + } +} + +pub struct GetPartitionsCmd { + stream_id: Identifier, + topic_id: Identifier, + output: GetPartitionsOutput, + rows: ListRows, +} + +impl GetPartitionsCmd { + pub fn new( + stream_id: Identifier, + topic_id: Identifier, + output: GetPartitionsOutput, + rows: ListRows, + ) -> Self { + Self { + stream_id, + topic_id, + output, + rows, + } + } +} + +#[async_trait] +impl CliCommand for GetPartitionsCmd { + fn explain(&self) -> String { + format!( + "list partitions for stream with ID: {} and topic with ID: {} in {} mode", + self.stream_id, self.topic_id, self.output + ) + } + + async fn execute_cmd(&mut self, client: &dyn Client) -> anyhow::Result<(), anyhow::Error> { + let (stream_id, topic_id) = (&self.stream_id, &self.topic_id); + let (partitions, next) = self + .rows + // The partitions flags have no name filter, so the name is always + // `None`. + .read(|query| async move { + client + .get_partitions_page(stream_id, topic_id, &query.page) + .await + }) + .await + .with_context(|| { + format!( + "Problem getting partitions for stream with ID: {stream_id} and topic with ID: {topic_id}" + ) + })?; + + match self.output { + GetPartitionsOutput::Table => { + let table = partitions_table(&partitions); + event!(target: PRINT_TARGET, Level::INFO, "{table}"); + } + GetPartitionsOutput::List => { + for partition in &partitions { + event!(target: PRINT_TARGET, Level::INFO, "{}", partition_row(partition).join("|")); + } + } + } + print_next(next); + + Ok(()) + } +} + +/// The partition table of `partition list`, and the nested one of `topic get`. +pub(crate) fn partitions_table(partitions: &[Partition]) -> Table { + let mut table = Table::new(); + table.set_header(vec![ + "Partition id", + "Created", + "Segments count", + "Current offset", + "Size", + "Messages count", + "Members", + "In sync", + ]); + for partition in partitions { + table.add_row(partition_row(partition)); + } + table +} + +fn partition_row(partition: &Partition) -> Vec<String> { + vec![ + partition.id.to_string(), + partition.created_at.to_utc_string("%Y-%m-%d %H:%M:%S"), + partition.segments_count.to_string(), + partition.current_offset.to_string(), + partition.size.to_string(), + partition.messages_count.to_string(), + node_list(&partition.members), + node_list(&partition.in_sync_members), + ] +} + +/// Node ids as `0,2,4`, or `-` for none. +fn node_list(nodes: &[u8]) -> String { + if nodes.is_empty() { + return "-".to_owned(); + } + nodes + .iter() + .map(u8::to_string) + .collect::<Vec<_>>() + .join(",") +}
diff --git a/core/cli/src/commands/binary_partitions/mod.rs b/core/cli/src/commands/binary_partitions/mod.rs index 5c4c791..f0b6af7 100644 --- a/core/cli/src/commands/binary_partitions/mod.rs +++ b/core/cli/src/commands/binary_partitions/mod.rs
@@ -17,3 +17,4 @@ pub mod create_partitions; pub mod delete_partitions; +pub mod get_partitions;
diff --git a/core/cli/src/commands/binary_streams/get_streams.rs b/core/cli/src/commands/binary_streams/get_streams.rs index 01f8014..88302d6 100644 --- a/core/cli/src/commands/binary_streams/get_streams.rs +++ b/core/cli/src/commands/binary_streams/get_streams.rs
@@ -16,7 +16,8 @@ // under the License. use crate::commands::binary_streams::get_stream::encryption_source; -use crate::commands::cli_command::{CliCommand, PRINT_TARGET, print_json}; +use crate::commands::cli_command::{CliCommand, PRINT_TARGET}; +use crate::commands::utils::list_rows::{ListRows, print_next}; use anyhow::Context; use async_trait::async_trait; use comfy_table::Table; @@ -31,11 +32,12 @@ pub struct GetStreamsCmd { output: GetStreamsOutput, + rows: ListRows, } impl GetStreamsCmd { - pub fn new(output: GetStreamsOutput) -> Self { - GetStreamsCmd { output } + pub fn new(output: GetStreamsOutput, rows: ListRows) -> Self { + GetStreamsCmd { output, rows } } } @@ -43,6 +45,7 @@ fn default() -> Self { GetStreamsCmd { output: GetStreamsOutput::Table, + rows: ListRows::default(), } } } @@ -63,8 +66,9 @@ } async fn execute_cmd(&mut self, client: &dyn Client) -> anyhow::Result<(), anyhow::Error> { - let streams = client - .get_streams() + let (streams, next) = self + .rows + .read(|query| async move { client.get_streams_page(&query).await }) .await .with_context(|| String::from("Problem getting list of streams"))?; @@ -115,8 +119,9 @@ ); }); } - GetStreamsOutput::Json => print_json(&streams)?, + GetStreamsOutput::Json => return self.rows.print_json(streams, next), } + print_next(next); Ok(()) }
diff --git a/core/cli/src/commands/binary_topics/get_topic.rs b/core/cli/src/commands/binary_topics/get_topic.rs index 3f4dfe5..3f027e2 100644 --- a/core/cli/src/commands/binary_topics/get_topic.rs +++ b/core/cli/src/commands/binary_topics/get_topic.rs
@@ -15,6 +15,7 @@ // specific language governing permissions and limitations // under the License. +use crate::commands::binary_partitions::get_partitions::partitions_table; use crate::commands::cli_command::{CliCommand, PRINT_TARGET, print_json}; use anyhow::{Context, bail}; use async_trait::async_trait; @@ -133,32 +134,9 @@ ]); if !topic.partitions.is_empty() { - let mut partitions_table = Table::new(); - partitions_table.load_style(ASCII_NO_BORDERS); - partitions_table.set_header(vec![ - "Partition id", - "Created", - "Segments count", - "Current offset", - "Size", - "Messages count", - "Members", - "In sync", - ]); - - for partition in &topic.partitions { - partitions_table.add_row(vec![ - partition.id.to_string(), - partition.created_at.to_utc_string("%Y-%m-%d %H:%M:%S"), - partition.segments_count.to_string(), - partition.current_offset.to_string(), - partition.size.to_string(), - partition.messages_count.to_string(), - node_list(&partition.members), - node_list(&partition.in_sync_members), - ]); - } - table.add_row(vec!["Partitions", partitions_table.to_string().as_str()]); + let mut partitions = partitions_table(&topic.partitions); + partitions.load_style(ASCII_NO_BORDERS); + table.add_row(vec!["Partitions", partitions.to_string().as_str()]); } if !topic.options.is_empty() { @@ -183,18 +161,6 @@ table } -/// Node ids as `0,2,4`, or `-` for none. -fn node_list(nodes: &[u8]) -> String { - if nodes.is_empty() { - return "-".to_owned(); - } - nodes - .iter() - .map(u8::to_string) - .collect::<Vec<_>>() - .join(",") -} - #[cfg(test)] mod tests { use super::topic_table;
diff --git a/core/cli/src/commands/binary_topics/get_topics.rs b/core/cli/src/commands/binary_topics/get_topics.rs index 7088fa5..1f53ddc 100644 --- a/core/cli/src/commands/binary_topics/get_topics.rs +++ b/core/cli/src/commands/binary_topics/get_topics.rs
@@ -15,7 +15,8 @@ // specific language governing permissions and limitations // under the License. -use crate::commands::cli_command::{CliCommand, PRINT_TARGET, print_json}; +use crate::commands::cli_command::{CliCommand, PRINT_TARGET}; +use crate::commands::utils::list_rows::{ListRows, print_next}; use anyhow::Context; use async_trait::async_trait; use comfy_table::Table; @@ -45,11 +46,16 @@ pub struct GetTopicsCmd { stream_id: Identifier, output: GetTopicsOutput, + rows: ListRows, } impl GetTopicsCmd { - pub fn new(stream_id: Identifier, output: GetTopicsOutput) -> Self { - Self { stream_id, output } + pub fn new(stream_id: Identifier, output: GetTopicsOutput, rows: ListRows) -> Self { + Self { + stream_id, + output, + rows, + } } } @@ -67,10 +73,12 @@ } async fn execute_cmd(&mut self, client: &dyn Client) -> anyhow::Result<(), anyhow::Error> { - let topics = client - .get_topics(&self.stream_id) + let stream_id = &self.stream_id; + let (topics, next) = self + .rows + .read(|query| async move { client.get_topics_page(stream_id, &query).await }) .await - .with_context(|| format!("Problem getting topics from stream {}", self.stream_id))?; + .with_context(|| format!("Problem getting topics from stream {stream_id}"))?; match self.output { GetTopicsOutput::Table => { @@ -130,8 +138,9 @@ ); }); } - GetTopicsOutput::Json => print_json(&topics)?, + GetTopicsOutput::Json => return self.rows.print_json(topics, next), } + print_next(next); Ok(()) }
diff --git a/core/cli/src/commands/binary_users/get_users.rs b/core/cli/src/commands/binary_users/get_users.rs index 9f75fd1..4cd555f 100644 --- a/core/cli/src/commands/binary_users/get_users.rs +++ b/core/cli/src/commands/binary_users/get_users.rs
@@ -16,6 +16,7 @@ // under the License. use crate::commands::cli_command::{CliCommand, PRINT_TARGET}; +use crate::commands::utils::list_rows::{ListRows, print_next}; use anyhow::Context; use async_trait::async_trait; use comfy_table::Table; @@ -29,11 +30,12 @@ pub struct GetUsersCmd { output: GetUsersOutput, + rows: ListRows, } impl GetUsersCmd { - pub fn new(output: GetUsersOutput) -> Self { - GetUsersCmd { output } + pub fn new(output: GetUsersOutput, rows: ListRows) -> Self { + GetUsersCmd { output, rows } } } @@ -41,6 +43,7 @@ fn default() -> Self { GetUsersCmd { output: GetUsersOutput::Table, + rows: ListRows::default(), } } } @@ -56,8 +59,9 @@ } async fn execute_cmd(&mut self, client: &dyn Client) -> anyhow::Result<(), anyhow::Error> { - let users = client - .get_users() + let (users, next) = self + .rows + .read(|query| async move { client.get_users_page(&query).await }) .await .with_context(|| String::from("Problem getting list of users"))?; @@ -95,6 +99,7 @@ }); } } + print_next(next); Ok(()) }
diff --git a/core/cli/src/commands/utils/list_rows.rs b/core/cli/src/commands/utils/list_rows.rs new file mode 100644 index 0000000..cb25f6b --- /dev/null +++ b/core/cli/src/commands/utils/list_rows.rs
@@ -0,0 +1,251 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The rows of a list command, read page by page. + +use crate::commands::cli_command::{PRINT_TARGET, print_json}; +use iggy_common::{IggyError, MAX_PAGE_LIMIT, NamedPageQuery, Page, PageCursor}; +use serde::Serialize; +use tracing::{Level, event}; + +/// The rows that a list command reads. +/// +/// `query` gives the order, the direction, the start and the name filter. +/// Each read sets the limit of its own page, so the limit of `query` has no +/// effect. +#[derive(Debug, Clone, Default)] +pub struct ListRows { + pub query: NamedPageQuery, + /// The most rows to print. Without it, the command reads every row. + pub row_limit: Option<usize>, +} + +impl ListRows { + /// Reads the rows page by page. With a row limit, it also returns the + /// cursor of the rows after the last one it read, if more rows follow. + /// + /// A page can hold fewer rows than it asks for, so the read goes on + /// until it holds the row limit or the list ends. + /// + /// # Errors + /// + /// The error of the first page read that fails, or of + /// [`NamedPageQuery::next`]. + pub async fn read<T, Fut>( + &self, + mut read_page: impl FnMut(NamedPageQuery) -> Fut, + ) -> Result<(Vec<T>, Option<PageCursor>), IggyError> + where + Fut: Future<Output = Result<Page<T>, IggyError>>, + { + let Some(row_limit) = self.row_limit else { + let mut query = self.query.clone(); + query.page.limit = MAX_PAGE_LIMIT; + return query.read_to_end(read_page).await.map(|rows| (rows, None)); + }; + let mut query = self.query.clone(); + let mut rows = Vec::new(); + loop { + // A page asks only for the missing rows: its cursor marks the + // position after its last row, so rows that it read and the + // command did not print would be lost. + query.page.limit = u32::try_from(row_limit - rows.len()) + .map_or(MAX_PAGE_LIMIT, |missing| missing.min(MAX_PAGE_LIMIT)); + let page = read_page(query.clone()).await?; + let next = query.next(&page)?; + rows.extend(page.items); + match next { + Some(next) if rows.len() < row_limit => query = next, + next => return Ok((rows, next.and_then(|next| next.page.cursor))), + } + } + } + + /// Prints the rows that [`Self::read`] returned as JSON. With a row limit, + /// it prints the `Page` that the HTTP list routes answer, so the cursor + /// stays inside the document. Without one, no cursor can follow, so it + /// prints the bare array. + /// + /// # Errors + /// + /// The error of the JSON serialization or of the stdout write. + pub fn print_json<T: Serialize>( + &self, + items: Vec<T>, + next: Option<PageCursor>, + ) -> anyhow::Result<()> { + match self.row_limit { + Some(_) => print_json(&Page { items, next }), + None => print_json(&items), + } + } +} + +/// Prints the `next:` line after the rows, when more rows follow them. +pub fn print_next(next: Option<PageCursor>) { + if let Some(next) = next { + event!(target: PRINT_TARGET, Level::INFO, "next: {next}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use iggy_binary_protocol::primitives::page::WirePageCursor; + use std::cell::RefCell; + use std::future::ready; + + /// A list of `len` items read from a fake server, which answers each page + /// with at most `page_items` of the items it asks for. It records the + /// limit of each page read. + struct FakeList { + len: u64, + page_items: u64, + limits: RefCell<Vec<u32>>, + } + + impl FakeList { + fn new(len: u64, page_items: u64) -> Self { + Self { + len, + page_items, + limits: RefCell::new(Vec::new()), + } + } + + fn page(&self, query: &NamedPageQuery) -> Result<Page<u64>, IggyError> { + self.limits.borrow_mut().push(query.page.limit); + let start = query.page.cursor.map_or(0, |cursor| match cursor.into() { + WirePageCursor::Id(id) => id + 1, + other => panic!("an id walk got {other:?}"), + }); + let end = (start + u64::from(query.page.limit).min(self.page_items)).min(self.len); + let next = (end < self.len && end > 0).then(|| WirePageCursor::Id(end - 1).into()); + Ok(Page { + items: (start..end).collect(), + next, + }) + } + + async fn read(&self, row_limit: Option<usize>) -> (Vec<u64>, Option<PageCursor>) { + let rows = ListRows { + query: NamedPageQuery::default(), + row_limit, + }; + rows.read(|query| ready(self.page(&query))) + .await + .expect("every page reads") + } + } + + #[tokio::test] + async fn given_a_row_limit_above_one_page_when_reading_should_ask_only_for_the_missing_rows() { + let list = FakeList::new(3_000, 1_000); + let (rows, next) = list.read(Some(2_500)).await; + assert_eq!(rows, (0..2_500).collect::<Vec<_>>()); + assert_eq!(next, Some(WirePageCursor::Id(2_499).into())); + assert_eq!(*list.limits.borrow(), [1_000, 1_000, 500]); + } + + #[tokio::test] + async fn given_short_pages_when_reading_with_a_row_limit_should_go_on_until_it_holds_them() { + let list = FakeList::new(10, 2); + let (rows, next) = list.read(Some(5)).await; + assert_eq!(rows, [0, 1, 2, 3, 4]); + assert_eq!(next, Some(WirePageCursor::Id(4).into())); + assert_eq!(*list.limits.borrow(), [5, 3, 1]); + } + + #[tokio::test] + async fn given_an_empty_page_with_next_when_reading_should_go_on_after_it() { + let empty_then_rows = RefCell::new(0); + let rows = ListRows { + query: NamedPageQuery::default(), + row_limit: Some(2), + }; + let (rows, next) = rows + .read(|query| { + *empty_then_rows.borrow_mut() += 1; + let page = match query.page.cursor { + None => Page { + items: Vec::new(), + next: Some(WirePageCursor::Id(7).into()), + }, + Some(_) => Page { + items: vec![8_u64], + next: None, + }, + }; + ready(Ok(page)) + }) + .await + .expect("every page reads"); + assert_eq!((rows, next), (vec![8], None)); + assert_eq!(*empty_then_rows.borrow(), 2); + } + + #[tokio::test] + async fn given_an_empty_page_that_answers_its_own_cursor_when_reading_should_fail() { + const MAX_PAGES: u32 = 4; + let pages = RefCell::new(0); + let rows = ListRows { + query: NamedPageQuery::default(), + row_limit: Some(2), + }; + let result = rows + .read(|_| { + *pages.borrow_mut() += 1; + assert!( + *pages.borrow() <= MAX_PAGES, + "the read must stop at the repeated cursor" + ); + ready(Ok(Page::<u64> { + items: Vec::new(), + next: Some(WirePageCursor::Id(7).into()), + })) + }) + .await; + assert_eq!(result, Err(IggyError::InvalidFormat)); + assert_eq!(*pages.borrow(), 2); + } + + #[tokio::test] + async fn given_a_list_shorter_than_the_row_limit_when_reading_should_return_no_cursor() { + let list = FakeList::new(3, 1_000); + assert_eq!(list.read(Some(5)).await, (vec![0, 1, 2], None)); + } + + #[tokio::test] + async fn given_no_row_limit_when_reading_should_read_every_page_of_the_most_items() { + let list = FakeList::new(2_100, 1_000); + let (rows, next) = list.read(None).await; + assert_eq!((rows.len(), next), (2_100, None)); + assert_eq!(*list.limits.borrow(), [1_000, 1_000, 1_000]); + } + + #[tokio::test] + async fn given_a_failing_page_when_reading_should_return_its_error() { + let rows = ListRows { + query: NamedPageQuery::default(), + row_limit: Some(3), + }; + let result = rows + .read(|_| ready(Err::<Page<u64>, _>(IggyError::Unauthorized))) + .await; + assert_eq!(result, Err(IggyError::Unauthorized)); + } +}
diff --git a/core/cli/src/commands/utils/mod.rs b/core/cli/src/commands/utils/mod.rs index 0a91629..a0f1b23 100644 --- a/core/cli/src/commands/utils/mod.rs +++ b/core/cli/src/commands/utils/mod.rs
@@ -15,4 +15,5 @@ // specific language governing permissions and limitations // under the License. +pub mod list_rows; pub mod login_session_expiry;
diff --git a/core/cli/src/main.rs b/core/cli/src/main.rs index 6c1e85c..b390794 100644 --- a/core/cli/src/main.rs +++ b/core/cli/src/main.rs
@@ -69,6 +69,7 @@ binary_message::{poll_messages::PollMessagesCmd, send_messages::SendMessagesCmd}, binary_partitions::{ create_partitions::CreatePartitionsCmd, delete_partitions::DeletePartitionsCmd, + get_partitions::GetPartitionsCmd, }, binary_personal_access_tokens::{ create_personal_access_token::CreatePersonalAccessTokenCmd, @@ -132,9 +133,10 @@ args.stream_id.clone(), args.output.into(), )), - StreamAction::List(args) => { - Box::new(GetStreamsCmd::new(args.list_output.output().into())) - } + StreamAction::List(args) => Box::new(GetStreamsCmd::new( + args.list_output.output().into(), + args.page.into(), + )), }, Command::Topic(command) => match command { TopicAction::Create(args) => Box::new(CreateTopicCmd::new( @@ -165,6 +167,7 @@ TopicAction::List(args) => Box::new(GetTopicsCmd::new( args.stream_id.clone(), args.list_output.output().into(), + args.page.into(), )), }, Command::Partition(command) => match command { @@ -178,6 +181,12 @@ args.topic_id.clone(), args.partitions_count, )), + PartitionAction::List(args) => Box::new(GetPartitionsCmd::new( + args.stream_id, + args.topic_id, + args.list_mode.into(), + args.page.into(), + )), }, Command::Segment(command) => match command { SegmentAction::Delete(args) => Box::new(DeleteSegmentsCmd::new( @@ -238,7 +247,10 @@ Box::new(DeleteUserCmd::new(delete_args.user_id.clone())) } UserAction::Get(get_args) => Box::new(GetUserCmd::new(get_args.user_id.clone())), - UserAction::List(list_args) => Box::new(GetUsersCmd::new(list_args.list_mode.into())), + UserAction::List(list_args) => Box::new(GetUsersCmd::new( + list_args.list_mode.into(), + list_args.page.into(), + )), UserAction::Name(name_args) => Box::new(UpdateUserCmd::new( name_args.user_id.clone(), UpdateUserType::Name(name_args.username.clone()), @@ -292,6 +304,7 @@ list_args.stream_id.clone(), list_args.topic_id.clone(), list_args.list_mode.into(), + list_args.page.into(), )), }, Command::Message(command) => match command {
diff --git a/core/common/Cargo.toml b/core/common/Cargo.toml index 0534fc7..08a68aa 100644 --- a/core/common/Cargo.toml +++ b/core/common/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy_common" -version = "0.12.0" +version = "0.12.1-edge.1" description = "Iggy is the persistent message streaming platform written in Rust, supporting QUIC, TCP and HTTP transport protocols, capable of processing millions of messages per second." edition = "2024" rust-version.workspace = true
diff --git a/core/common/examples/list_pages_fixtures.rs b/core/common/examples/list_pages_fixtures.rs new file mode 100644 index 0000000..87d730d --- /dev/null +++ b/core/common/examples/list_pages_fixtures.rs
@@ -0,0 +1,37 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#[path = "list_pages_fixtures/schema.rs"] +mod schema; + +use schema::{CANONICAL_PATH, FixtureResult, LANGUAGE_COPIES, render}; +use std::fs; +use std::iter; +use std::path::Path; + +fn main() -> FixtureResult<()> { + let json = render()?; + let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); + for relative in iter::once(CANONICAL_PATH).chain(LANGUAGE_COPIES) { + let path = manifest.join(relative); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&path, &json)?; + } + Ok(()) +}
diff --git a/core/common/examples/list_pages_fixtures/schema.rs b/core/common/examples/list_pages_fixtures/schema.rs new file mode 100644 index 0000000..ae973da --- /dev/null +++ b/core/common/examples/list_pages_fixtures/schema.rs
@@ -0,0 +1,1035 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Shape and builder of the list page golden vectors. +//! +//! Shared by the generator example and the drift test, so the test rebuilds +//! the fixture in process and compares it byte for byte with the canonical +//! file and every SDK copy. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use iggy_binary_protocol::codes::{ + GET_CONSUMER_GROUPS_CODE, GET_PARTITIONS_CODE, GET_STREAMS_CODE, GET_TOPICS_CODE, + GET_USERS_CODE, +}; +use iggy_binary_protocol::primitives::page::{WirePageCursor, WirePageOrder, WirePageQuery}; +use iggy_binary_protocol::requests::consumer_groups::GetConsumerGroupsRequest; +use iggy_binary_protocol::requests::partitions::GetPartitionsRequest; +use iggy_binary_protocol::requests::streams::GetStreamsRequest; +use iggy_binary_protocol::requests::topics::GetTopicsRequest; +use iggy_binary_protocol::requests::users::GetUsersRequest; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::responses::consumer_groups::ConsumerGroupResponse; +use iggy_binary_protocol::responses::streams::{StreamResponse, TopicResponse}; +use iggy_binary_protocol::responses::topics::PartitionResponse; +use iggy_binary_protocol::responses::users::UserResponse; +use iggy_binary_protocol::{ + MAX_WIRE_NAME_LENGTH, PartitionContext, WireDecode, WireEncode, WireError, WireIdentifier, + WireName, WireOptions, +}; +use iggy_common::{ + DEFAULT_PAGE_LIMIT, IggyError, MAX_PAGE_LIMIT, NamedPageQuery, PAGE_CURSOR_PREFIX, PageCursor, + PageOrder, PageQuery, +}; +use serde::{Serialize, Serializer}; +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt::Display; + +pub const SCHEMA_VERSION: u32 = 1; +pub const GENERATOR: &str = "core/common/examples/list_pages_fixtures.rs"; +/// Relative to the `iggy_common` manifest directory. +pub const CANONICAL_PATH: &str = "fixtures/list_pages.json"; +/// Byte-identical copies each foreign SDK loads from its own test resources. +pub const LANGUAGE_COPIES: [&str; 8] = [ + "../../foreign/go/contracts/testdata/list_pages.json", + "../../foreign/java/java-sdk/src/test/resources/list_pages.json", + "../../foreign/node/src/wire/fixtures/list_pages.json", + "../../foreign/csharp/Iggy_SDK_Tests/Fixtures/list_pages.json", + "../../foreign/swift/Tests/IggyTests/Fixtures/list_pages.json", + "../../foreign/python/tests/fixtures/list_pages.json", + "../../foreign/cpp/tests/fixtures/list_pages.json", + "../../foreign/php/tests/fixtures/list_pages.json", +]; +/// The length of a cursor on the wire is one byte. +pub const MAX_CURSOR_BYTES: usize = u8::MAX as usize; + +const CREATED_AT: u64 = 1_710_000_000_000_000; +/// The cursor of the CLI help and docs examples. +const ID_SEVEN: WirePageCursor = WirePageCursor::Id(7); +const ID_DISTINCT_BYTES: WirePageCursor = WirePageCursor::Id(0x0807_0605_0403_0201); +/// Its text holds `_` and `-`, the two characters in which Base64url differs +/// from standard Base64. +const ID_URL_SAFE_CHARACTERS: WirePageCursor = WirePageCursor::Id(0x00f8_ff00); +const CREATED_DISTINCT_BYTES: WirePageCursor = WirePageCursor::Created { + created_at: 0x1817_1615_1413_1211, + id: 0x2827_2625_2423_2221, +}; +/// 17 bytes, 9 characters and 10 UTF-16 units, so a length in anything but +/// bytes shows. +const MULTI_BYTE_NAME: &str = "café-注文-📦"; + +pub type FixtureResult<T> = Result<T, Box<dyn Error>>; + +#[derive(Debug, Serialize)] +pub struct ListPagesFixture { + pub schema_version: u32, + pub generated_by: String, + pub conventions: BTreeMap<String, String>, + pub constants: Constants, + pub cursors: Vec<CursorVector>, + pub opaque_cursors: Vec<CursorVector>, + pub requests: Vec<RequestVector>, + pub responses: Vec<ResponseVector>, + pub opaque_responses: Vec<ResponseVector>, + pub refused: RefusedVectors, +} + +#[derive(Debug, Serialize)] +pub struct Constants { + pub codes: BTreeMap<String, u32>, + pub orders: BTreeMap<String, u8>, + pub cursor_prefix: String, + pub max_cursor_bytes: usize, + pub default_limit: u32, + pub max_limit: u32, + pub max_name_bytes: usize, + pub errors: BTreeMap<String, u32>, +} + +/// The five list commands. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ListCommand { + Users, + Streams, + Topics, + Partitions, + ConsumerGroups, +} + +/// A cursor text and the bytes it stands for. +#[derive(Debug, Serialize)] +pub struct CursorVector { + pub case: String, + pub text: String, + pub hex: String, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum Identifier { + Numeric(u32), + Named(String), +} + +/// The parent ids and the page query of one list request. +#[derive(Debug, Clone, Serialize)] +pub struct PageInput { + pub stream_id: Option<Identifier>, + pub topic_id: Option<Identifier>, + #[serde(serialize_with = "as_text")] + pub order: PageOrder, + pub descending: bool, + pub limit: u32, + pub cursor: Option<PageCursor>, + pub name: Option<String>, +} + +#[derive(Debug, Serialize)] +pub struct RequestVector { + pub case: String, + pub command: ListCommand, + pub input: PageInput, + pub request_hex: String, + pub http_query: BTreeMap<String, String>, +} + +#[derive(Debug, Serialize)] +pub struct ResponseVector { + pub case: String, + pub command: ListCommand, + pub response_hex: String, + pub next: Option<String>, + pub items: Vec<ItemFields>, +} + +/// What a reply vector pins of one item. The item codecs do not change, so +/// the id and the name show where each item starts and ends. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ItemFields { + pub id: u32, + pub name: Option<String>, +} + +#[derive(Debug, Serialize)] +pub struct RefusedVectors { + pub cursors: Vec<RefusedText>, + pub queries: Vec<RefusedQuery>, + pub responses: Vec<RefusedResponse>, +} + +#[derive(Debug, Serialize)] +pub struct RefusedText { + pub case: String, + pub text: String, +} + +#[derive(Debug, Serialize)] +pub struct RefusedQuery { + pub case: String, + pub input: PageInput, +} + +#[derive(Debug, Serialize)] +pub struct RefusedResponse { + pub case: String, + pub command: ListCommand, + pub response_hex: String, +} + +/// An item of a list page. +pub trait PageItem: WireEncode + WireDecode { + fn fields(&self) -> ItemFields; +} + +impl ListCommand { + pub const ALL: [Self; 5] = [ + Self::Users, + Self::Streams, + Self::Topics, + Self::Partitions, + Self::ConsumerGroups, + ]; + + pub const fn name(self) -> &'static str { + match self { + Self::Users => "get_users", + Self::Streams => "get_streams", + Self::Topics => "get_topics", + Self::Partitions => "get_partitions", + Self::ConsumerGroups => "get_consumer_groups", + } + } + + pub const fn code(self) -> u32 { + match self { + Self::Users => GET_USERS_CODE, + Self::Streams => GET_STREAMS_CODE, + Self::Topics => GET_TOPICS_CODE, + Self::Partitions => GET_PARTITIONS_CODE, + Self::ConsumerGroups => GET_CONSUMER_GROUPS_CODE, + } + } +} + +impl Serialize for ListCommand { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.serialize_str(self.name()) + } +} + +impl TryFrom<&Identifier> for WireIdentifier { + type Error = WireError; + + fn try_from(id: &Identifier) -> Result<Self, Self::Error> { + match id { + Identifier::Numeric(value) => Ok(Self::numeric(*value)), + Identifier::Named(value) => Self::named(value.as_str()), + } + } +} + +impl PageInput { + fn new(stream_id: Option<Identifier>, topic_id: Option<Identifier>) -> Self { + Self { + stream_id, + topic_id, + order: PageOrder::Id, + descending: false, + limit: DEFAULT_PAGE_LIMIT, + cursor: None, + name: None, + } + } + + pub fn query(&self) -> NamedPageQuery { + NamedPageQuery { + page: PageQuery { + order: self.order, + descending: self.descending, + limit: self.limit, + cursor: self.cursor, + }, + name: self.name.clone(), + } + } + + fn request_bytes(&self, command: ListCommand) -> FixtureResult<Vec<u8>> { + let page = WirePageQuery::try_from(&self.query())?; + let stream_id = || parent(self.stream_id.as_ref()); + let topic_id = || parent(self.topic_id.as_ref()); + let bytes = match command { + ListCommand::Users => GetUsersRequest { page }.to_bytes(), + ListCommand::Streams => GetStreamsRequest { page }.to_bytes(), + ListCommand::Topics => GetTopicsRequest { + stream_id: stream_id()?, + page, + } + .to_bytes(), + ListCommand::Partitions => GetPartitionsRequest { + stream_id: stream_id()?, + topic_id: topic_id()?, + page, + } + .to_bytes(), + ListCommand::ConsumerGroups => GetConsumerGroupsRequest { + stream_id: stream_id()?, + topic_id: topic_id()?, + page, + } + .to_bytes(), + }; + Ok(bytes.to_vec()) + } +} + +impl PageItem for StreamResponse { + fn fields(&self) -> ItemFields { + named_item(self.id, &self.name) + } +} + +impl PageItem for TopicResponse { + fn fields(&self) -> ItemFields { + named_item(self.id, &self.name) + } +} + +impl PageItem for PartitionResponse { + fn fields(&self) -> ItemFields { + ItemFields { + id: self.id, + name: None, + } + } +} + +impl PageItem for ConsumerGroupResponse { + fn fields(&self) -> ItemFields { + named_item(self.id, &self.name) + } +} + +impl PageItem for UserResponse { + fn fields(&self) -> ItemFields { + named_item(self.id, &self.username) + } +} + +pub fn render() -> FixtureResult<String> { + let mut json = serde_json::to_string_pretty(&build()?)?; + json.push('\n'); + Ok(json) +} + +/// The fixture, built from the live codecs, so a codec change shows up as a +/// stale file in the drift test. +pub fn build() -> FixtureResult<ListPagesFixture> { + Ok(ListPagesFixture { + schema_version: SCHEMA_VERSION, + generated_by: GENERATOR.to_owned(), + conventions: conventions(), + constants: constants(), + cursors: cursor_vectors(), + opaque_cursors: opaque_cursor_vectors(), + requests: request_vectors()?, + responses: response_vectors()?, + opaque_responses: opaque_response_vectors()?, + refused: RefusedVectors { + cursors: refused_cursors()?, + queries: refused_queries(), + responses: refused_responses()?, + }, + }) +} + +/// The text form of any byte string, also one that is not a valid cursor. +pub fn cursor_text(bytes: &[u8]) -> String { + format!("{PAGE_CURSOR_PREFIX}{}", URL_SAFE_NO_PAD.encode(bytes)) +} + +fn conventions() -> BTreeMap<String, String> { + [ + ( + "hex", + "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + ), + ( + "identifiers", + "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + ), + ( + "cursor_text", + "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + ), + ( + "opaque_cursors", + "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + ), + ( + "next", + "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + ), + ( + "walk", + "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array.", + ), + ( + "name", + "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + ), + ( + "http_query", + "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + ), + ( + "items", + "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + ), + ( + "refused", + "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + ), + ( + "errors", + "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + ), + ] + .into_iter() + .map(|(key, text)| (key.to_owned(), text.to_owned())) + .collect() +} + +fn constants() -> Constants { + Constants { + codes: ListCommand::ALL + .into_iter() + .map(|command| (command.name().to_owned(), command.code())) + .collect(), + orders: [PageOrder::Id, PageOrder::Created] + .into_iter() + .map(|order| (order.to_string(), WirePageOrder::from(order).as_u8())) + .collect(), + cursor_prefix: PAGE_CURSOR_PREFIX.to_owned(), + max_cursor_bytes: MAX_CURSOR_BYTES, + default_limit: DEFAULT_PAGE_LIMIT, + max_limit: MAX_PAGE_LIMIT, + max_name_bytes: MAX_WIRE_NAME_LENGTH, + errors: [IggyError::InvalidCommand, IggyError::ReplyTooLarge] + .into_iter() + .map(|error| (<&'static str>::from(&error).to_owned(), error.as_code())) + .collect(), + } +} + +fn cursor_vectors() -> Vec<CursorVector> { + [ + ("id_seven", ID_SEVEN), + ("id_distinct_bytes", ID_DISTINCT_BYTES), + ("id_url_safe_characters", ID_URL_SAFE_CHARACTERS), + ("created_distinct_bytes", CREATED_DISTINCT_BYTES), + ] + .into_iter() + .map(|(case, cursor)| CursorVector { + case: case.to_owned(), + text: PageCursor::from(cursor).to_string(), + hex: hex::encode(cursor.to_bytes()), + }) + .collect() +} + +fn opaque_cursor_vectors() -> Vec<CursorVector> { + let id_seven = ID_SEVEN.to_bytes(); + [ + ("kind_zero", with_kind(0, &id_seven)), + ("unknown_kind", unknown_kind_cursor()), + ("created_kind_with_the_id_length", with_kind(2, &id_seven)), + ( + "id_kind_with_the_created_length", + with_kind(1, &CREATED_DISTINCT_BYTES.to_bytes()), + ), + ("one_byte", vec![1]), + ("most_bytes", longest_cursor()), + ] + .into_iter() + .map(|(case, bytes)| CursorVector { + case: case.to_owned(), + text: cursor_text(&bytes), + hex: hex::encode(&bytes), + }) + .collect() +} + +fn request_vectors() -> FixtureResult<Vec<RequestVector>> { + let stream_id = || Some(Identifier::Numeric(7)); + let stream_name = || Some(Identifier::Named("orders".to_owned())); + let topic_id = || Some(Identifier::Numeric(3)); + let topic_name = || Some(Identifier::Named("events".to_owned())); + let no_parent = || PageInput::new(None, None); + let cases = [ + ("streams_first_page", ListCommand::Streams, no_parent()), + ( + "streams_whole_list_walk", + ListCommand::Streams, + PageInput { + limit: MAX_PAGE_LIMIT, + ..no_parent() + }, + ), + ( + "streams_created_descending_one_item", + ListCommand::Streams, + PageInput { + order: PageOrder::Created, + descending: true, + limit: 1, + ..no_parent() + }, + ), + ( + "streams_after_id_cursor", + ListCommand::Streams, + PageInput { + cursor: Some(ID_DISTINCT_BYTES.into()), + ..no_parent() + }, + ), + ( + "streams_created_after_cursor_with_name", + ListCommand::Streams, + PageInput { + order: PageOrder::Created, + descending: true, + limit: 20, + cursor: Some(CREATED_DISTINCT_BYTES.into()), + name: Some("ord".to_owned()), + ..no_parent() + }, + ), + ( + "streams_multi_byte_name", + ListCommand::Streams, + PageInput { + name: Some(MULTI_BYTE_NAME.to_owned()), + ..no_parent() + }, + ), + ( + "streams_longest_name", + ListCommand::Streams, + PageInput { + name: Some(longest_name()), + ..no_parent() + }, + ), + ("users_first_page", ListCommand::Users, no_parent()), + ( + "users_created_after_cursor_with_name", + ListCommand::Users, + PageInput { + order: PageOrder::Created, + cursor: Some( + WirePageCursor::Created { + created_at: CREATED_AT, + id: 1, + } + .into(), + ), + name: Some("adm".to_owned()), + ..no_parent() + }, + ), + ( + "topics_numeric_stream_first_page", + ListCommand::Topics, + PageInput::new(stream_id(), None), + ), + ( + "topics_named_stream_created_descending_with_name", + ListCommand::Topics, + PageInput { + order: PageOrder::Created, + descending: true, + limit: 50, + cursor: Some( + WirePageCursor::Created { + created_at: CREATED_AT + 9, + id: 3, + } + .into(), + ), + name: Some("sens".to_owned()), + ..PageInput::new(stream_name(), None) + }, + ), + ( + "partitions_numeric_ids_first_page", + ListCommand::Partitions, + PageInput::new(stream_id(), topic_id()), + ), + ( + "partitions_named_ids_descending_after_cursor", + ListCommand::Partitions, + PageInput { + descending: true, + limit: MAX_PAGE_LIMIT, + cursor: Some(WirePageCursor::Id(999).into()), + ..PageInput::new(stream_name(), topic_name()) + }, + ), + ( + "partitions_created_order_after_id_cursor", + ListCommand::Partitions, + PageInput { + order: PageOrder::Created, + cursor: Some(ID_SEVEN.into()), + ..PageInput::new(stream_id(), topic_id()) + }, + ), + ( + "consumer_groups_numeric_ids_first_page", + ListCommand::ConsumerGroups, + PageInput::new(stream_id(), topic_id()), + ), + ( + "consumer_groups_named_ids_descending_with_name", + ListCommand::ConsumerGroups, + PageInput { + descending: true, + cursor: Some(WirePageCursor::Id(3).into()), + name: Some("bill".to_owned()), + ..PageInput::new(stream_name(), topic_name()) + }, + ), + ]; + cases + .into_iter() + .map(|(case, command, input)| { + let request_hex = hex::encode(input.request_bytes(command)?); + let http_query = input + .query() + .http_query_pairs() + .into_iter() + .map(|(key, value)| (key.to_owned(), value)) + .collect(); + Ok(RequestVector { + case: case.to_owned(), + command, + input, + request_hex, + http_query, + }) + }) + .collect() +} + +fn response_vectors() -> FixtureResult<Vec<ResponseVector>> { + let orders = || stream(1, CREATED_AT + 5, "orders"); + let payments = || stream(4, CREATED_AT, "payments-eu"); + let events = || topic(1, CREATED_AT, "events"); + let full_partition = || partition(0, vec![0, 1, 2], vec![0, 1]); + let lagging_partition = || partition(1, vec![1], vec![]); + let iggy = || user(1, CREATED_AT, "iggy"); + let alice = || user(2, CREATED_AT + 1, "alice-ops"); + Ok(vec![ + response( + "streams_with_next", + ListCommand::Streams, + vec![orders()?, payments()?], + Some(WirePageCursor::Id(4)), + ), + response( + "streams_created_order_with_next", + ListCommand::Streams, + vec![payments()?, orders()?], + Some(WirePageCursor::Created { + created_at: CREATED_AT + 5, + id: 1, + }), + ), + response::<StreamResponse>( + "streams_empty_with_next", + ListCommand::Streams, + vec![], + Some(WirePageCursor::Id(1000)), + ), + response::<StreamResponse>( + "streams_empty_last_page", + ListCommand::Streams, + vec![], + None, + ), + response( + "topics_last_page", + ListCommand::Topics, + vec![events()?, topic(2, CREATED_AT, "sensor-readings")?], + None, + ), + response( + "topics_created_descending_with_next", + ListCommand::Topics, + vec![topic(3, CREATED_AT + 9, "audit")?, events()?], + Some(WirePageCursor::Created { + created_at: CREATED_AT, + id: 1, + }), + ), + response( + "partitions_with_next", + ListCommand::Partitions, + vec![full_partition(), lagging_partition()], + Some(WirePageCursor::Id(1)), + ), + response( + "partitions_descending_last_page", + ListCommand::Partitions, + vec![lagging_partition(), full_partition()], + None, + ), + response( + "consumer_groups_with_next", + ListCommand::ConsumerGroups, + vec![group(1, "billing")?, group(3, "analytics-eu")?], + Some(WirePageCursor::Id(3)), + ), + response( + "users_with_next", + ListCommand::Users, + vec![iggy()?, alice()?], + Some(WirePageCursor::Id(2)), + ), + response( + "users_created_descending_last_page", + ListCommand::Users, + vec![alice()?, iggy()?], + None, + ), + ]) +} + +/// Pages whose next only a server refuses, built around a valid page. +fn opaque_response_vectors() -> FixtureResult<Vec<ResponseVector>> { + [ + ("streams_with_unknown_cursor_kind", unknown_kind_cursor()), + ("streams_with_most_cursor_bytes", longest_cursor()), + ] + .into_iter() + .map(|(case, next)| { + let items = vec![ + stream(1, CREATED_AT + 5, "orders")?, + stream(4, CREATED_AT, "payments-eu")?, + ]; + let page = PageResponse { items, next: None }; + let last_page = page.to_bytes(); + let mut body = vec![u8::try_from(next.len())?]; + body.extend_from_slice(&next); + // The first byte of the last page is the length 0 of its absent next. + body.extend_from_slice(&last_page[1..]); + Ok(ResponseVector { + case: case.to_owned(), + command: ListCommand::Streams, + response_hex: hex::encode(body), + next: Some(cursor_text(&next)), + items: page.items.iter().map(PageItem::fields).collect(), + }) + }) + .collect() +} + +fn refused_cursors() -> FixtureResult<Vec<RefusedText>> { + let id_seven = PageCursor::from(ID_SEVEN).to_string(); + let id_seven_body = &id_seven[PAGE_CURSOR_PREFIX.len()..]; + let url_safe = PageCursor::from(ID_URL_SAFE_CHARACTERS).to_string(); + let standard_body = url_safe[PAGE_CURSOR_PREFIX.len()..] + .replace('_', "/") + .replace('-', "+"); + // 17 bytes end in a character with 4 data bits and 2 unused bits. Here + // all six are zero, so `B` in place of `A` sets an unused bit and keeps + // the bytes. + let unused_bits_zero = PageCursor::from(WirePageCursor::Created { + created_at: 9, + id: 3, + }) + .to_string(); + let unused_bit_set = format!( + "{}B", + unused_bits_zero + .strip_suffix('A') + .ok_or("the cursor text ends with A")? + ); + Ok([ + ("empty", String::new()), + ("missing_prefix", id_seven_body.to_owned()), + ("other_prefix", format!("mc1_{id_seven_body}")), + ("later_version_prefix", format!("pg2_{id_seven_body}")), + ("upper_case_prefix", format!("PG1_{id_seven_body}")), + ( + "padded", + format!("{}=", PageCursor::from(CREATED_DISTINCT_BYTES)), + ), + ( + "standard_alphabet", + format!("{PAGE_CURSOR_PREFIX}{standard_body}"), + ), + ( + "character_outside_the_alphabet", + format!("{}*", &id_seven[..id_seven.len() - 1]), + ), + ("trailing_newline", format!("{id_seven}\n")), + ("unused_bit_set", unused_bit_set), + ("no_bytes", PAGE_CURSOR_PREFIX.to_owned()), + ( + "more_than_max_cursor_bytes", + cursor_text(&[0x5a; MAX_CURSOR_BYTES + 1]), + ), + ] + .into_iter() + .map(|(case, text)| RefusedText { + case: case.to_owned(), + text, + }) + .collect()) +} + +fn refused_queries() -> Vec<RefusedQuery> { + let input = || PageInput::new(None, None); + [ + ( + "limit_zero", + PageInput { + limit: 0, + ..input() + }, + ), + ( + "limit_above_max_limit", + PageInput { + limit: MAX_PAGE_LIMIT + 1, + ..input() + }, + ), + ( + "empty_name", + PageInput { + name: Some(String::new()), + ..input() + }, + ), + ( + // 128 characters, so a length in characters passes it. + "name_above_max_name_bytes", + PageInput { + name: Some("é".repeat(MAX_WIRE_NAME_LENGTH / 2 + 1)), + ..input() + }, + ), + ] + .into_iter() + .map(|(case, input)| RefusedQuery { + case: case.to_owned(), + input, + }) + .collect() +} + +fn refused_responses() -> FixtureResult<Vec<RefusedResponse>> { + let one_group = PageResponse { + items: vec![group(1, "billing")?], + next: None, + } + .to_bytes(); + let with_count = |count: u32| { + let mut body = one_group.to_vec(); + body[1..5].copy_from_slice(&count.to_le_bytes()); + body + }; + let two_partitions = PageResponse { + items: vec![ + partition(0, vec![0, 1, 2], vec![0, 1]), + partition(1, vec![1], vec![]), + ], + next: Some(WirePageCursor::Id(1)), + } + .to_bytes(); + let created_next = PageResponse::<UserResponse> { + items: vec![], + next: Some(CREATED_DISTINCT_BYTES), + } + .to_bytes(); + Ok([ + ("empty_body", ListCommand::Streams, Vec::new()), + ("truncated_count", ListCommand::Topics, vec![0, 2, 0]), + ( + "truncated_next", + ListCommand::Users, + created_next[..6].to_vec(), + ), + ( + "count_above_items", + ListCommand::ConsumerGroups, + with_count(2), + ), + ( + "count_of_u32_max", + ListCommand::ConsumerGroups, + with_count(u32::MAX), + ), + ( + "truncated_item", + ListCommand::Partitions, + two_partitions[..two_partitions.len() - 1].to_vec(), + ), + ( + "trailing_bytes", + ListCommand::Partitions, + [&two_partitions[..], &[0]].concat(), + ), + ] + .into_iter() + .map(|(case, command, body)| RefusedResponse { + case: case.to_owned(), + command, + response_hex: hex::encode(body), + }) + .collect()) +} + +fn response<T: PageItem>( + case: &str, + command: ListCommand, + items: Vec<T>, + next: Option<WirePageCursor>, +) -> ResponseVector { + let page = PageResponse { items, next }; + ResponseVector { + case: case.to_owned(), + command, + response_hex: hex::encode(page.to_bytes()), + next: page.next.map(|cursor| PageCursor::from(cursor).to_string()), + items: page.items.iter().map(PageItem::fields).collect(), + } +} + +fn stream(id: u32, created_at: u64, name: &str) -> FixtureResult<StreamResponse> { + Ok(StreamResponse { + id, + created_at, + topics_count: 2, + size_bytes: 4096, + messages_count: 100, + name: WireName::new(name)?, + options: WireOptions::empty(), + derived_options: WireOptions::empty(), + }) +} + +fn topic(id: u32, created_at: u64, name: &str) -> FixtureResult<TopicResponse> { + Ok(TopicResponse { + id, + created_at, + partitions_count: 3, + size_bytes: 2048, + messages_count: 50, + name: WireName::new(name)?, + options: WireOptions::empty(), + derived_options: WireOptions::empty(), + }) +} + +fn partition(id: u32, members: Vec<u8>, in_sync_members: Vec<u8>) -> PartitionResponse { + PartitionResponse { + context: PartitionContext { + incarnation: 1, + owner_generation: 0, + metadata_op: 42, + }, + id, + created_at: CREATED_AT + u64::from(id), + segments_count: 1, + current_offset: 99, + size_bytes: 1024, + messages_count: 100, + members, + in_sync_members, + } +} + +fn group(id: u32, name: &str) -> FixtureResult<ConsumerGroupResponse> { + Ok(ConsumerGroupResponse { + id, + partitions_count: 3, + members_count: 1, + name: WireName::new(name)?, + }) +} + +fn user(id: u32, created_at: u64, username: &str) -> FixtureResult<UserResponse> { + Ok(UserResponse { + id, + created_at, + status: 1, + username: WireName::new(username)?, + options: WireOptions::empty(), + derived_options: WireOptions::empty(), + }) +} + +fn named_item(id: u32, name: &WireName) -> ItemFields { + ItemFields { + id, + name: Some(name.as_str().to_owned()), + } +} + +fn parent(id: Option<&Identifier>) -> FixtureResult<WireIdentifier> { + let id = id.ok_or("the command needs this parent id")?; + Ok(WireIdentifier::try_from(id)?) +} + +fn with_kind(kind: u8, cursor: &[u8]) -> Vec<u8> { + [&[kind][..], &cursor[1..]].concat() +} + +fn unknown_kind_cursor() -> Vec<u8> { + with_kind(3, &ID_SEVEN.to_bytes()) +} + +fn longest_cursor() -> Vec<u8> { + (1..=u8::MAX).collect() +} + +/// 255 bytes but 128 characters, so a length in characters shows. +fn longest_name() -> String { + let mut name = "é".repeat(MAX_WIRE_NAME_LENGTH / 2); + name.push('a'); + name +} + +fn as_text<T: Display, S: Serializer>(value: &T, serializer: S) -> Result<S::Ok, S::Error> { + serializer.collect_str(value) +}
diff --git a/core/common/examples/resource_options_fixtures.rs b/core/common/examples/resource_options_fixtures.rs index ddd7d55..a318f94 100644 --- a/core/common/examples/resource_options_fixtures.rs +++ b/core/common/examples/resource_options_fixtures.rs
@@ -21,7 +21,7 @@ use base64::Engine; use base64::engine::general_purpose::STANDARD; use iggy_binary_protocol::requests::system::DescribeOptionsRequest; -use iggy_binary_protocol::responses::streams::{GetStreamResponse, StreamResponse, TopicHeader}; +use iggy_binary_protocol::responses::streams::{GetStreamResponse, StreamResponse, TopicResponse}; use iggy_binary_protocol::responses::system::DescribeOptionsResponse; use iggy_binary_protocol::responses::topics::GetTopicResponse; use iggy_binary_protocol::responses::users::{UserDetailsResponse, UserResponse}; @@ -841,7 +841,7 @@ let (options, derived_options) = resource_options_to_wire_split(&public_options(OptionsScope::Topic, &stored)?)?; let bytes = GetTopicResponse { - topic: TopicHeader { + topic: TopicResponse { id: 4, created_at: CREATED_AT_MICROS, partitions_count: 0,
diff --git a/core/common/fixtures/list_pages.json b/core/common/fixtures/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/core/common/fixtures/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/core/common/fixtures/resource_options.json b/core/common/fixtures/resource_options.json index 8a2e7d1..ccda484 100644 --- a/core/common/fixtures/resource_options.json +++ b/core/common/fixtures/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/core/common/src/error/iggy_error.rs b/core/common/src/error/iggy_error.rs index fa2103e..9e4a9c9 100644 --- a/core/common/src/error/iggy_error.rs +++ b/core/common/src/error/iggy_error.rs
@@ -226,6 +226,13 @@ /// Clients must not send the request again. #[error("Tiered data cannot be read from the object store; a retry does not help")] TieredReadFailed = 96, + /// The reply frame of `GetClients` or of a metadata read is larger than + /// the reply cap of a client, so the server sent this error in its place. + /// The metadata reads are those of streams, topics, partitions, consumer + /// groups, users, options, stats and cluster metadata. The connection + /// stays open. A paged read returns the same data in smaller replies. + #[error("The reply is larger than the reply size limit")] + ReplyTooLarge = 97, #[error("Client with ID: {0} was not found.")] ClientNotFound(u32) = 100, #[error("Invalid client ID")]
diff --git a/core/common/src/lib.rs b/core/common/src/lib.rs index 8e2efd7..d2dd9f5 100644 --- a/core/common/src/lib.rs +++ b/core/common/src/lib.rs
@@ -154,6 +154,7 @@ pub use types::message::*; pub use types::metadata_changes::*; pub use types::options::*; +pub use types::page::*; pub use types::partition::*; pub use types::permissions::permissions_global::*; pub use types::permissions::personal_access_token::*;
diff --git a/core/common/src/traits/binary_impls/consumer_groups.rs b/core/common/src/traits/binary_impls/consumer_groups.rs index bf02feb..21d43f8 100644 --- a/core/common/src/traits/binary_impls/consumer_groups.rs +++ b/core/common/src/traits/binary_impls/consumer_groups.rs
@@ -17,10 +17,10 @@ use crate::traits::binary_auth::fail_if_not_authenticated; use crate::traits::binary_impls::messages::synced_group_assignment; -use crate::wire_conversions::{consumer_groups_from_wire, identifier_to_wire}; +use crate::wire_conversions::{identifier_to_wire, page_from_wire}; use crate::{ BinaryClient, ConsumerGroup, ConsumerGroupAssignment, ConsumerGroupClient, - ConsumerGroupDetails, Identifier, IggyError, + ConsumerGroupDetails, Identifier, IggyError, NamedPageQuery, Page, }; use iggy_binary_protocol::WireName; use iggy_binary_protocol::codec::WireEncode; @@ -28,12 +28,14 @@ CREATE_CONSUMER_GROUP_CODE, DELETE_CONSUMER_GROUP_CODE, GET_CONSUMER_GROUP_CODE, GET_CONSUMER_GROUPS_CODE, JOIN_CONSUMER_GROUP_CODE, LEAVE_CONSUMER_GROUP_CODE, }; +use iggy_binary_protocol::primitives::page::WirePageQuery; use iggy_binary_protocol::requests::consumer_groups::{ CreateConsumerGroupRequest, DeleteConsumerGroupRequest, GetConsumerGroupRequest, GetConsumerGroupsRequest, JoinConsumerGroupRequest, LeaveConsumerGroupRequest, }; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::responses::consumer_groups::ConsumerGroupResponse; use iggy_binary_protocol::responses::consumer_groups::get_consumer_group::ConsumerGroupDetailsResponse; -use iggy_binary_protocol::responses::consumer_groups::get_consumer_groups::GetConsumerGroupsResponse; #[async_trait::async_trait] impl<B: BinaryClient> ConsumerGroupClient for B { @@ -70,24 +72,30 @@ stream_id: &Identifier, topic_id: &Identifier, ) -> Result<Vec<ConsumerGroup>, IggyError> { + super::read_whole_list(self, |query| async move { + self.get_consumer_groups_page(stream_id, topic_id, &query) + .await + }) + .await + } + + async fn get_consumer_groups_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<ConsumerGroup>, IggyError> { fail_if_not_authenticated(self).await?; - let wire_stream_id = identifier_to_wire(stream_id)?; - let wire_topic_id = identifier_to_wire(topic_id)?; + let request = GetConsumerGroupsRequest { + stream_id: identifier_to_wire(stream_id)?, + topic_id: identifier_to_wire(topic_id)?, + page: WirePageQuery::try_from(query)?, + }; let response = self - .send_raw_with_response( - GET_CONSUMER_GROUPS_CODE, - GetConsumerGroupsRequest { - stream_id: wire_stream_id, - topic_id: wire_topic_id, - } - .to_bytes(), - ) + .send_raw_with_response(GET_CONSUMER_GROUPS_CODE, request.to_bytes()) .await?; - if response.is_empty() { - return Ok(Vec::new()); - } - let wire_resp = super::decode_response::<GetConsumerGroupsResponse>(&response)?; - Ok(consumer_groups_from_wire(wire_resp)) + let page = super::decode_response::<PageResponse<ConsumerGroupResponse>>(&response)?; + page_from_wire(page, |group| Ok(ConsumerGroup::from(group))) } async fn create_consumer_group(
diff --git a/core/common/src/traits/binary_impls/mod.rs b/core/common/src/traits/binary_impls/mod.rs index b9ef6db..69ca7b7 100644 --- a/core/common/src/traits/binary_impls/mod.rs +++ b/core/common/src/traits/binary_impls/mod.rs
@@ -38,7 +38,10 @@ use crate::http::users::defaults::{ MAX_PASSWORD_LENGTH, MAX_USERNAME_LENGTH, MIN_PASSWORD_LENGTH, MIN_USERNAME_LENGTH, }; -use crate::{BinaryClient, ClientState, Credentials, IdentityInfo}; +use crate::{ + BinaryClient, ClientState, Credentials, IdentityInfo, NamedPageQuery, Page, PageQuery, + binary_operation_deadline, with_binary_deadline, with_binary_lineage, +}; use bytes::Bytes; use iggy_binary_protocol::codec::WireEncode; use iggy_binary_protocol::codes::{ @@ -54,6 +57,25 @@ use secrecy::ExposeSecret; use tokio::time::timeout_at; +/// Reads a whole list as one call, as the one request before paging did. Every +/// page keeps the caller sign-in and the budget that the walk started with, so +/// a caller sign-in between two pages ends the walk. +async fn read_whole_list<B, T, F, Fut>(client: &B, read_page: F) -> Result<Vec<T>, IggyError> +where + B: BinaryClient + ?Sized, + F: FnMut(NamedPageQuery) -> Fut, + Fut: Future<Output = Result<Page<T>, IggyError>>, +{ + with_binary_lineage( + client.operation_lineage(), + with_binary_deadline( + binary_operation_deadline(), + NamedPageQuery::from(PageQuery::whole_list()).read_to_end(read_page), + ), + ) + .await +} + /// Send one `UpdateResource` patch for `target`. async fn update_resource<B: BinaryClient + ?Sized>( client: &B,
diff --git a/core/common/src/traits/binary_impls/partitions.rs b/core/common/src/traits/binary_impls/partitions.rs index dedf63b..d6c1926 100644 --- a/core/common/src/traits/binary_impls/partitions.rs +++ b/core/common/src/traits/binary_impls/partitions.rs
@@ -16,13 +16,18 @@ // under the License. use crate::traits::binary_auth::fail_if_not_authenticated; -use crate::wire_conversions::identifier_to_wire; -use crate::{BinaryClient, Identifier, IggyError, PartitionClient}; +use crate::wire_conversions::{identifier_to_wire, page_from_wire}; +use crate::{BinaryClient, Identifier, IggyError, Page, PageQuery, Partition, PartitionClient}; use iggy_binary_protocol::codec::WireEncode; -use iggy_binary_protocol::codes::{CREATE_PARTITIONS_CODE, DELETE_PARTITIONS_CODE}; -use iggy_binary_protocol::requests::partitions::{ - CreatePartitionsRequest, DeletePartitionsRequest, +use iggy_binary_protocol::codes::{ + CREATE_PARTITIONS_CODE, DELETE_PARTITIONS_CODE, GET_PARTITIONS_CODE, }; +use iggy_binary_protocol::primitives::page::WirePageQuery; +use iggy_binary_protocol::requests::partitions::{ + CreatePartitionsRequest, DeletePartitionsRequest, GetPartitionsRequest, +}; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::responses::topics::get_topic::PartitionResponse; #[async_trait::async_trait] impl<B: BinaryClient> PartitionClient for B { @@ -69,4 +74,23 @@ .await?; Ok(()) } + + async fn get_partitions_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &PageQuery, + ) -> Result<Page<Partition>, IggyError> { + fail_if_not_authenticated(self).await?; + let request = GetPartitionsRequest { + stream_id: identifier_to_wire(stream_id)?, + topic_id: identifier_to_wire(topic_id)?, + page: WirePageQuery::try_from(query)?, + }; + let response = self + .send_raw_with_response(GET_PARTITIONS_CODE, request.to_bytes()) + .await?; + let page = super::decode_response::<PageResponse<PartitionResponse>>(&response)?; + page_from_wire(page, |partition| Ok(Partition::from(partition))) + } }
diff --git a/core/common/src/traits/binary_impls/streams.rs b/core/common/src/traits/binary_impls/streams.rs index c070b03..e566e8d 100644 --- a/core/common/src/traits/binary_impls/streams.rs +++ b/core/common/src/traits/binary_impls/streams.rs
@@ -16,22 +16,24 @@ // under the License. use crate::traits::binary_auth::fail_if_not_authenticated; -use crate::wire_conversions::{identifier_to_wire, streams_from_wire}; +use crate::wire_conversions::{identifier_to_wire, page_from_wire}; use crate::{ - BinaryClient, Identifier, IggyError, Stream, StreamClient, StreamCreateOptions, StreamDetails, - StreamUpdateOptions, + BinaryClient, Identifier, IggyError, NamedPageQuery, Page, Stream, StreamClient, + StreamCreateOptions, StreamDetails, StreamUpdateOptions, }; use iggy_binary_protocol::WireName; use iggy_binary_protocol::codec::WireEncode; use iggy_binary_protocol::codes::{ CREATE_STREAM_CODE, DELETE_STREAM_CODE, GET_STREAM_CODE, GET_STREAMS_CODE, }; +use iggy_binary_protocol::primitives::page::WirePageQuery; use iggy_binary_protocol::requests::streams::{ CreateStreamRequest, DeleteStreamRequest, GetStreamRequest, GetStreamsRequest, }; use iggy_binary_protocol::requests::system::ResourceTarget; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::responses::streams::StreamResponse; use iggy_binary_protocol::responses::streams::get_stream::GetStreamResponse; -use iggy_binary_protocol::responses::streams::get_streams::GetStreamsResponse; #[async_trait::async_trait] impl<B: BinaryClient> StreamClient for B { @@ -52,15 +54,23 @@ } async fn get_streams(&self) -> Result<Vec<Stream>, IggyError> { + super::read_whole_list( + self, + |query| async move { self.get_streams_page(&query).await }, + ) + .await + } + + async fn get_streams_page(&self, query: &NamedPageQuery) -> Result<Page<Stream>, IggyError> { fail_if_not_authenticated(self).await?; + let request = GetStreamsRequest { + page: WirePageQuery::try_from(query)?, + }; let response = self - .send_raw_with_response(GET_STREAMS_CODE, GetStreamsRequest.to_bytes()) + .send_raw_with_response(GET_STREAMS_CODE, request.to_bytes()) .await?; - if response.is_empty() { - return Ok(Vec::new()); - } - let wire_resp = super::decode_response::<GetStreamsResponse>(&response)?; - Ok(streams_from_wire(wire_resp)?) + let page = super::decode_response::<PageResponse<StreamResponse>>(&response)?; + page_from_wire(page, Stream::try_from) } async fn create_stream(
diff --git a/core/common/src/traits/binary_impls/topics.rs b/core/common/src/traits/binary_impls/topics.rs index c0358b7..2c52226 100644 --- a/core/common/src/traits/binary_impls/topics.rs +++ b/core/common/src/traits/binary_impls/topics.rs
@@ -16,22 +16,24 @@ // under the License. use crate::traits::binary_auth::fail_if_not_authenticated; -use crate::wire_conversions::{identifier_to_wire, topics_from_wire}; +use crate::wire_conversions::{identifier_to_wire, page_from_wire}; use crate::{ - BinaryClient, DEFAULT_PARTITIONS_COUNT, Identifier, IggyError, Topic, TopicClient, - TopicCreateOptions, TopicDetails, TopicUpdateOptions, + BinaryClient, DEFAULT_PARTITIONS_COUNT, Identifier, IggyError, NamedPageQuery, Page, Topic, + TopicClient, TopicCreateOptions, TopicDetails, TopicUpdateOptions, }; use iggy_binary_protocol::WireName; use iggy_binary_protocol::codec::WireEncode; use iggy_binary_protocol::codes::{ CREATE_TOPIC_CODE, DELETE_TOPIC_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, }; +use iggy_binary_protocol::primitives::page::WirePageQuery; use iggy_binary_protocol::requests::system::ResourceTarget; use iggy_binary_protocol::requests::topics::{ CreateTopicRequest, DeleteTopicRequest, GetTopicRequest, GetTopicsRequest, }; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::responses::streams::TopicResponse; use iggy_binary_protocol::responses::topics::get_topic::GetTopicResponse; -use iggy_binary_protocol::responses::topics::get_topics::GetTopicsResponse; #[async_trait::async_trait] impl<B: BinaryClient> TopicClient for B { @@ -61,22 +63,27 @@ } async fn get_topics(&self, stream_id: &Identifier) -> Result<Vec<Topic>, IggyError> { + super::read_whole_list(self, |query| async move { + self.get_topics_page(stream_id, &query).await + }) + .await + } + + async fn get_topics_page( + &self, + stream_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<Topic>, IggyError> { fail_if_not_authenticated(self).await?; - let wire_stream_id = identifier_to_wire(stream_id)?; + let request = GetTopicsRequest { + stream_id: identifier_to_wire(stream_id)?, + page: WirePageQuery::try_from(query)?, + }; let response = self - .send_raw_with_response( - GET_TOPICS_CODE, - GetTopicsRequest { - stream_id: wire_stream_id, - } - .to_bytes(), - ) + .send_raw_with_response(GET_TOPICS_CODE, request.to_bytes()) .await?; - if response.is_empty() { - return Ok(Vec::new()); - } - let wire_resp = super::decode_response::<GetTopicsResponse>(&response)?; - Ok(topics_from_wire(wire_resp)?) + let page = super::decode_response::<PageResponse<TopicResponse>>(&response)?; + page_from_wire(page, Topic::try_from) } async fn create_topic(
diff --git a/core/common/src/traits/binary_impls/users.rs b/core/common/src/traits/binary_impls/users.rs index 7f9dd91..bdb40e4 100644 --- a/core/common/src/traits/binary_impls/users.rs +++ b/core/common/src/traits/binary_impls/users.rs
@@ -16,10 +16,11 @@ // under the License. use crate::traits::binary_auth::fail_if_not_authenticated; -use crate::wire_conversions::{identifier_to_wire, permissions_to_wire, users_from_wire}; +use crate::wire_conversions::{identifier_to_wire, page_from_wire, permissions_to_wire}; use crate::{ - BinaryClient, Credentials, Identifier, IdentityInfo, IggyError, Permissions, UserClient, - UserCreateOptions, UserInfo, UserInfoDetails, UserStatus, UserUpdateOptions, + BinaryClient, Credentials, Identifier, IdentityInfo, IggyError, NamedPageQuery, Page, + Permissions, UserClient, UserCreateOptions, UserInfo, UserInfoDetails, UserStatus, + UserUpdateOptions, }; use iggy_binary_protocol::WireName; use iggy_binary_protocol::codec::WireEncode; @@ -27,12 +28,14 @@ CHANGE_PASSWORD_CODE, CREATE_USER_CODE, DELETE_USER_CODE, GET_USER_CODE, GET_USERS_CODE, LOGOUT_USER_CODE, UPDATE_PERMISSIONS_CODE, }; +use iggy_binary_protocol::primitives::page::WirePageQuery; use iggy_binary_protocol::requests::system::ResourceTarget; use iggy_binary_protocol::requests::users::{ ChangePasswordRequest, CreateUserRequest, DeleteUserRequest, GetUserRequest, GetUsersRequest, LogoutUserRequest, UpdatePermissionsRequest, }; -use iggy_binary_protocol::responses::users::{GetUsersResponse, UserDetailsResponse}; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::responses::users::{UserDetailsResponse, UserResponse}; use secrecy::SecretString; #[async_trait::async_trait] @@ -54,15 +57,23 @@ } async fn get_users(&self) -> Result<Vec<UserInfo>, IggyError> { + super::read_whole_list( + self, + |query| async move { self.get_users_page(&query).await }, + ) + .await + } + + async fn get_users_page(&self, query: &NamedPageQuery) -> Result<Page<UserInfo>, IggyError> { fail_if_not_authenticated(self).await?; + let request = GetUsersRequest { + page: WirePageQuery::try_from(query)?, + }; let response = self - .send_raw_with_response(GET_USERS_CODE, GetUsersRequest.to_bytes()) + .send_raw_with_response(GET_USERS_CODE, request.to_bytes()) .await?; - if response.is_empty() { - return Ok(Vec::new()); - } - let wire_resp = super::decode_response::<GetUsersResponse>(&response)?; - users_from_wire(wire_resp) + let page = super::decode_response::<PageResponse<UserResponse>>(&response)?; + page_from_wire(page, UserInfo::try_from) } async fn create_user( @@ -194,16 +205,20 @@ mod tests { use super::*; use crate::{ - BinaryTransport, Client, ClientState, ConsumerGroupClientState, DiagnosticEvent, - NonZeroIggyDuration, OptionKey, PartitionContext, VsrSessionControl, VsrSessionSealed, + BinaryOperationLineage, BinaryTransport, Client, ClientState, ConsumerGroupClientState, + DiagnosticEvent, NonZeroIggyDuration, OptionKey, PartitionContext, VsrSessionControl, + VsrSessionSealed, binary_deadline_in_force, binary_operation_lineage, }; use async_broadcast::Receiver; use bytes::Bytes; + use iggy_binary_protocol::primitives::page::WirePageCursor; use iggy_binary_protocol::requests::messages::PollMessagesRequest; use iggy_binary_protocol::requests::system::SessionIdentity; use iggy_binary_protocol::requests::users::login_register::BindSecret; - use std::collections::BTreeSet; + use std::collections::{BTreeSet, VecDeque}; + use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; + use tokio::time::Instant; #[tokio::test] async fn given_short_username_and_status_reset_when_updating_user_should_report_admission_category() @@ -228,10 +243,44 @@ assert!(client.sent_codes().is_empty()); } - /// An authenticated binary client that records the codes it sends. + #[tokio::test] + async fn given_a_sign_in_after_the_first_page_when_reading_all_users_should_keep_the_scope_of_the_walk() + { + let client = RecordingClient::default(); + let page = |next| { + PageResponse::<UserResponse> { + items: Vec::new(), + next, + } + .to_bytes() + }; + client + .replies + .lock() + .expect("lock") + .extend([page(Some(WirePageCursor::Id(1))), page(None)]); + + assert!(client.get_users().await.expect("whole list").is_empty()); + + let scopes = client.scopes.lock().expect("lock").clone(); + let walk = Some(BinaryOperationLineage::new(OPERATION_OWNER, 0)); + assert_eq!(client.sent_codes(), [GET_USERS_CODE, GET_USERS_CODE]); + assert!(scopes.iter().all(|(lineage, _)| *lineage == walk)); + assert!(scopes[0].1.is_some()); + assert_eq!(scopes[0].1, scopes[1].1); + } + + const OPERATION_OWNER: u128 = 1; + + /// An authenticated binary client that records the codes it sends and the + /// sign-in and deadline that each request runs under. It answers each + /// request with the next of `replies`, and then the caller signs in again. #[derive(Debug, Default)] struct RecordingClient { sent: Mutex<Vec<u32>>, + replies: Mutex<VecDeque<Bytes>>, + sign_in_lineage: AtomicU64, + scopes: Mutex<Vec<(Option<BinaryOperationLineage>, Option<Instant>)>>, consumer_groups: Arc<ConsumerGroupClientState>, } @@ -242,12 +291,29 @@ fn record(&self, code: u32) -> Result<Bytes, IggyError> { self.sent.lock().expect("lock").push(code); - Ok(Bytes::new()) + self.scopes + .lock() + .expect("lock") + .push((binary_operation_lineage(), binary_deadline_in_force())); + self.sign_in_lineage.fetch_add(1, Ordering::SeqCst); + Ok(self + .replies + .lock() + .expect("lock") + .pop_front() + .unwrap_or_default()) } } #[async_trait::async_trait] impl BinaryTransport for RecordingClient { + fn operation_lineage(&self) -> Option<BinaryOperationLineage> { + Some(BinaryOperationLineage::capture( + OPERATION_OWNER, + self.sign_in_lineage.load(Ordering::SeqCst), + )) + } + async fn get_state(&self) -> ClientState { ClientState::Authenticated }
diff --git a/core/common/src/traits/consumer_group_client.rs b/core/common/src/traits/consumer_group_client.rs index f197c9e..7162e17 100644 --- a/core/common/src/traits/consumer_group_client.rs +++ b/core/common/src/traits/consumer_group_client.rs
@@ -15,7 +15,10 @@ // specific language governing permissions and limitations // under the License. -use crate::{ConsumerGroup, ConsumerGroupAssignment, ConsumerGroupDetails, Identifier, IggyError}; +use crate::{ + ConsumerGroup, ConsumerGroupAssignment, ConsumerGroupDetails, Identifier, IggyError, + NamedPageQuery, Page, +}; use async_trait::async_trait; /// This trait defines the methods to interact with the consumer group module. @@ -31,7 +34,13 @@ topic_id: &Identifier, group_id: &Identifier, ) -> Result<Option<ConsumerGroupDetails>, IggyError>; - /// Get the info about all the consumer groups for the given stream and topic by unique IDs or names. + /// Get the info about all the consumer groups for the given stream and topic by unique IDs or names, in id order. + /// + /// The list is read page by page, so it is not one consistent read. A group + /// that someone creates or deletes during the read can appear or not + /// appear. + /// A server that answers a page with the cursor it was sent fails the read + /// with `IggyError::InvalidFormat`. /// /// Authentication is required, and the permission to read the streams or topics. async fn get_consumer_groups( @@ -39,6 +48,17 @@ stream_id: &Identifier, topic_id: &Identifier, ) -> Result<Vec<ConsumerGroup>, IggyError>; + /// One page of the consumer groups of a topic, in id order. Read the next + /// page with [`NamedPageQuery::next`] until the page has no `next`. Group ids + /// follow creation, so `PageOrder::Created` walks in id order too. + /// + /// Authentication is required, and the permission to read the streams or topics. + async fn get_consumer_groups_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<ConsumerGroup>, IggyError>; /// Create a new consumer group for the given stream and topic by unique IDs or names. /// /// Authentication is required, and the permission to manage the streams or topics.
diff --git a/core/common/src/traits/partition_client.rs b/core/common/src/traits/partition_client.rs index 6382ea1..7203b96 100644 --- a/core/common/src/traits/partition_client.rs +++ b/core/common/src/traits/partition_client.rs
@@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -use crate::{Identifier, IggyError}; +use crate::{Identifier, IggyError, Page, PageQuery, Partition}; use async_trait::async_trait; /// This trait defines the methods to interact with the partition module. @@ -56,4 +56,15 @@ topic_id: &Identifier, partitions_count: u32, ) -> Result<(), IggyError>; + /// One page of the partitions of a topic, in id order. Read the next page + /// with [`PageQuery::next`] until the page has no `next`. Partition ids + /// follow creation, so `PageOrder::Created` walks in id order too. + /// + /// Authentication is required, and the permission to read the topic. + async fn get_partitions_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &PageQuery, + ) -> Result<Page<Partition>, IggyError>; }
diff --git a/core/common/src/traits/stream_client.rs b/core/common/src/traits/stream_client.rs index 366ac1f..2a5f3b9 100644 --- a/core/common/src/traits/stream_client.rs +++ b/core/common/src/traits/stream_client.rs
@@ -16,7 +16,8 @@ // under the License. use crate::{ - Identifier, IggyError, Stream, StreamCreateOptions, StreamDetails, StreamUpdateOptions, + Identifier, IggyError, NamedPageQuery, Page, Stream, StreamCreateOptions, StreamDetails, + StreamUpdateOptions, }; use async_trait::async_trait; @@ -28,10 +29,21 @@ /// /// Authentication is required, and the permission to read the streams. async fn get_stream(&self, stream_id: &Identifier) -> Result<Option<StreamDetails>, IggyError>; - /// Get the info about all the streams. + /// Get the info about all the streams, in id order. + /// + /// The list is read page by page, so it is not one consistent read. A stream + /// that someone creates or deletes during the read can appear or not + /// appear. + /// A server that answers a page with the cursor it was sent fails the read + /// with `IggyError::InvalidFormat`. /// /// Authentication is required, and the permission to read the streams. async fn get_streams(&self) -> Result<Vec<Stream>, IggyError>; + /// One page of the streams. Read the next page with + /// [`NamedPageQuery::next`] until the page has no `next`. + /// + /// Authentication is required, and the permission to read the streams. + async fn get_streams_page(&self, query: &NamedPageQuery) -> Result<Page<Stream>, IggyError>; /// Create a new stream. /// /// `options` may carry the stream's own encryption key. The server stores
diff --git a/core/common/src/traits/topic_client.rs b/core/common/src/traits/topic_client.rs index e482aa8..20ba5b8 100644 --- a/core/common/src/traits/topic_client.rs +++ b/core/common/src/traits/topic_client.rs
@@ -15,7 +15,10 @@ // specific language governing permissions and limitations // under the License. -use crate::{Identifier, IggyError, Topic, TopicCreateOptions, TopicDetails, TopicUpdateOptions}; +use crate::{ + Identifier, IggyError, NamedPageQuery, Page, Topic, TopicCreateOptions, TopicDetails, + TopicUpdateOptions, +}; use async_trait::async_trait; /// This trait defines the methods to interact with the topic module. @@ -31,10 +34,32 @@ stream_id: &Identifier, topic_id: &Identifier, ) -> Result<Option<TopicDetails>, IggyError>; - /// Get the info about all the topics. + /// Get the info about all the topics, in id order. + /// + /// The list is read page by page, so it is not one consistent read. A topic + /// that someone creates or deletes during the read can appear or not + /// appear. If the stream goes missing after the first page, the read + /// fails as [`Self::get_topics_page`] does. + /// A server that answers a page with the cursor it was sent fails the read + /// with `IggyError::InvalidFormat`. /// /// Authentication is required, and the permission to read the topics. async fn get_topics(&self, stream_id: &Identifier) -> Result<Vec<Topic>, IggyError>; + /// One page of the topics of a stream. Read the next page with + /// [`NamedPageQuery::next`] until the page has no `next`. + /// + /// For a missing stream, the first page is empty and has no `next`. A + /// page read with a cursor fails instead, because the stream was deleted + /// during the walk: a binary transport returns + /// `IggyError::StreamIdNotFound`, and `HttpClient` returns + /// `IggyError::ResourceNotFound`. + /// + /// Authentication is required, and the permission to read the topics. + async fn get_topics_page( + &self, + stream_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<Topic>, IggyError>; /// Create a new topic. /// /// Every knob rides `options`; an absent key resolves against the
diff --git a/core/common/src/traits/user_client.rs b/core/common/src/traits/user_client.rs index 9d2ad47..378960f 100644 --- a/core/common/src/traits/user_client.rs +++ b/core/common/src/traits/user_client.rs
@@ -16,8 +16,8 @@ // under the License. use crate::{ - Identifier, IdentityInfo, IggyError, Permissions, UserCreateOptions, UserInfo, UserInfoDetails, - UserStatus, UserUpdateOptions, + Identifier, IdentityInfo, IggyError, NamedPageQuery, Page, Permissions, UserCreateOptions, + UserInfo, UserInfoDetails, UserStatus, UserUpdateOptions, }; use async_trait::async_trait; @@ -29,10 +29,21 @@ /// /// Authentication is required, and the permission to read the users, unless the provided user ID is the same as the authenticated user. async fn get_user(&self, user_id: &Identifier) -> Result<Option<UserInfoDetails>, IggyError>; - /// Get the info about all the users. + /// Get the info about all the users, in id order. + /// + /// The list is read page by page, so it is not one consistent read. A user + /// that someone creates or deletes during the read can appear or not + /// appear. + /// A server that answers a page with the cursor it was sent fails the read + /// with `IggyError::InvalidFormat`. /// /// Authentication is required, and the permission to read the users. async fn get_users(&self) -> Result<Vec<UserInfo>, IggyError>; + /// One page of the users. Read the next page with + /// [`NamedPageQuery::next`] until the page has no `next`. + /// + /// Authentication is required, and the permission to read the users. + async fn get_users_page(&self, query: &NamedPageQuery) -> Result<Page<UserInfo>, IggyError>; /// Create a new user. /// /// Authentication is required, and the permission to manage the users.
diff --git a/core/common/src/types/metadata_changes/position.rs b/core/common/src/types/metadata_changes/position.rs index e03c4f5..fbaeaa2 100644 --- a/core/common/src/types/metadata_changes/position.rs +++ b/core/common/src/types/metadata_changes/position.rs
@@ -177,7 +177,7 @@ } /// Strip `prefix` and decode canonical unpadded Base64url. -fn decode_canonical(text: &str, prefix: &str) -> Result<Vec<u8>, IggyError> { +pub(crate) fn decode_canonical(text: &str, prefix: &str) -> Result<Vec<u8>, IggyError> { let encoded = text.strip_prefix(prefix).ok_or(IggyError::InvalidCommand)?; let bytes = URL_SAFE_NO_PAD .decode(encoded)
diff --git a/core/common/src/types/metadata_changes/query.rs b/core/common/src/types/metadata_changes/query.rs index f327327..c5d1c5b 100644 --- a/core/common/src/types/metadata_changes/query.rs +++ b/core/common/src/types/metadata_changes/query.rs
@@ -216,7 +216,7 @@ } /// A decimal integer without a sign, padding or leading zeros. -fn parse_canonical<T: FromStr>(value: &str) -> Result<T, IggyError> { +pub(crate) fn parse_canonical<T: FromStr>(value: &str) -> Result<T, IggyError> { let canonical = !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) && (value == "0" || !value.starts_with('0'));
diff --git a/core/common/src/types/mod.rs b/core/common/src/types/mod.rs index 9d4dfd3..5cd88f4 100644 --- a/core/common/src/types/mod.rs +++ b/core/common/src/types/mod.rs
@@ -29,6 +29,7 @@ pub(crate) mod message; pub(crate) mod metadata_changes; pub(crate) mod options; +pub(crate) mod page; pub(crate) mod partition; pub(crate) mod permissions; pub(crate) mod personal_access_tokens;
diff --git a/core/common/src/types/page.rs b/core/common/src/types/page.rs new file mode 100644 index 0000000..071f282 --- /dev/null +++ b/core/common/src/types/page.rs
@@ -0,0 +1,830 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Pages of the list commands: the query of one page and the page itself. +//! +//! A client reads a list page by page. Each page carries the cursor of the +//! next one until the list ends. A walk is not a snapshot: an entity that +//! someone creates or deletes during the walk can appear or not appear. + +use crate::IggyError; +use crate::types::metadata_changes::position::decode_canonical; +use crate::types::metadata_changes::query::parse_canonical; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use iggy_binary_protocol::primitives::page::{WirePageCursor, WirePageOrder, WirePageQuery}; +use iggy_binary_protocol::{MAX_WIRE_NAME_LENGTH, WireEncode, WireName}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::collections::BTreeSet; +use std::fmt::{Display, Formatter}; +use std::str::FromStr; +use strum::{Display as StrumDisplay, EnumString}; + +pub use iggy_binary_protocol::primitives::page::{DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT}; + +/// Text prefix of a page cursor. +pub const PAGE_CURSOR_PREFIX: &str = "pg1_"; + +const ORDER_KEY: &str = "order"; +const DESCENDING_KEY: &str = "descending"; +const LIMIT_KEY: &str = "limit"; +const CURSOR_KEY: &str = "cursor"; +const NAME_KEY: &str = "name"; + +/// The order of a list page. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, StrumDisplay, EnumString)] +#[strum(serialize_all = "snake_case")] +pub enum PageOrder { + /// The numeric id. + #[default] + Id, + /// The creation order. Entities with one creation time keep the order of + /// their ids. Partitions and consumer groups walk by id in this order too, + /// because their ids follow creation. + Created, +} + +/// The position after which the next page starts. +/// +/// Clients treat it as opaque and return it as they got it. Its text form is +/// `pg1_` followed by unpadded Base64url. It holds no direction, filter or +/// parent, so it is valid only with the query that returned it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct PageCursor(WirePageCursor); + +/// One page request of a list command. +/// +/// The lists of named entities take a [`NamedPageQuery`], which adds a name +/// filter. A partition has no name, so the partitions of a topic take this +/// type, which cannot carry one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PageQuery { + pub order: PageOrder, + pub descending: bool, + /// The most items of the page, 1 to [`MAX_PAGE_LIMIT`]. + pub limit: u32, + /// The `next` of the previous page, `None` for the first page. + pub cursor: Option<PageCursor>, +} + +/// One page request of a list of named entities: streams, topics, consumer +/// groups and users. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct NamedPageQuery { + pub page: PageQuery, + /// Only the entries whose name holds this text, case-sensitive. + pub name: Option<String>, +} + +/// One page of a list. A page can be short or empty and still have a `next`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Page<T> { + pub items: Vec<T>, + /// The cursor of the next page, `None` on the last page. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub next: Option<PageCursor>, +} + +impl Default for PageQuery { + fn default() -> Self { + Self { + order: PageOrder::Id, + descending: false, + limit: DEFAULT_PAGE_LIMIT, + cursor: None, + } + } +} + +impl From<PageQuery> for NamedPageQuery { + fn from(page: PageQuery) -> Self { + Self { page, name: None } + } +} + +impl PageQuery { + /// # Errors + /// `InvalidCommand` for a limit outside 1 to [`MAX_PAGE_LIMIT`]. + pub fn validate(&self) -> Result<(), IggyError> { + if !(1..=MAX_PAGE_LIMIT).contains(&self.limit) { + return Err(IggyError::InvalidCommand); + } + Ok(()) + } + + /// The query of the page after `page`, or `None` after the last page. + /// + /// # Errors + /// `InvalidFormat` for a page whose `next` is the cursor of this query. A + /// server that answers the cursor it was sent would keep a walk going + /// forever. + pub fn next<T>(&self, page: &Page<T>) -> Result<Option<Self>, IggyError> { + let Some(cursor) = page.next else { + return Ok(None); + }; + if self.cursor == Some(cursor) { + tracing::warn!("the server answered the page cursor {cursor} it was sent"); + return Err(IggyError::InvalidFormat); + } + Ok(Some(Self { + cursor: Some(cursor), + ..self.clone() + })) + } + + /// The first query of a walk over a whole list: ascending id order, in + /// pages of [`MAX_PAGE_LIMIT`]. + #[must_use] + pub fn whole_list() -> Self { + Self { + limit: MAX_PAGE_LIMIT, + ..Self::default() + } + } + + /// Every item from the page of this query to the end of the list, read + /// one page at a time with `read_page`. + /// + /// # Errors + /// The first error of `read_page` or of [`Self::next`]. + pub async fn read_to_end<T, F, Fut>(self, mut read_page: F) -> Result<Vec<T>, IggyError> + where + F: FnMut(Self) -> Fut, + Fut: Future<Output = Result<Page<T>, IggyError>>, + { + let mut query = self; + let mut items = Vec::new(); + loop { + let page = read_page(query.clone()).await?; + let next = query.next(&page)?; + items.extend(page.items); + match next { + Some(next) => query = next, + None => return Ok(items), + } + } + } + + /// The HTTP query parameters of this query, in a stable order. They always + /// hold the limit, so a server reads them as a page request. + #[must_use] + pub fn http_query_pairs(&self) -> Vec<(&'static str, String)> { + let mut pairs = vec![ + (ORDER_KEY, self.order.to_string()), + (DESCENDING_KEY, self.descending.to_string()), + (LIMIT_KEY, self.limit.to_string()), + ]; + if let Some(cursor) = self.cursor { + pairs.push((CURSOR_KEY, cursor.to_string())); + } + pairs + } + + /// [`NamedPageQuery::from_http_query`] for a list without names. A `name` + /// key is refused. + /// + /// # Errors + /// `InvalidCommand` for any refused parameter. + pub fn from_http_query<'a>( + pairs: impl IntoIterator<Item = (&'a str, &'a str)>, + ) -> Result<Self, IggyError> { + let query = NamedPageQuery::from_http_query(pairs)?; + if query.name.is_some() { + return Err(IggyError::InvalidCommand); + } + Ok(query.page) + } +} + +impl NamedPageQuery { + /// # Errors + /// `InvalidCommand` as for [`PageQuery::validate`], and for a name that is + /// empty or longer than 255 bytes. + pub fn validate(&self) -> Result<(), IggyError> { + self.page.validate()?; + if self + .name + .as_ref() + .is_some_and(|name| name.is_empty() || name.len() > MAX_WIRE_NAME_LENGTH) + { + return Err(IggyError::InvalidCommand); + } + Ok(()) + } + + /// The query of the page after `page`, or `None` after the last page. + /// + /// # Errors + /// As for [`PageQuery::next`]. + pub fn next<T>(&self, page: &Page<T>) -> Result<Option<Self>, IggyError> { + Ok(self.page.next(page)?.map(|next| Self { + page: next, + name: self.name.clone(), + })) + } + + /// [`PageQuery::read_to_end`] with the name filter of this query. + /// + /// # Errors + /// As for [`PageQuery::read_to_end`]. + pub async fn read_to_end<T, F, Fut>(self, mut read_page: F) -> Result<Vec<T>, IggyError> + where + F: FnMut(Self) -> Fut, + Fut: Future<Output = Result<Page<T>, IggyError>>, + { + let name = self.name; + self.page + .read_to_end(|page| { + read_page(Self { + page, + name: name.clone(), + }) + }) + .await + } + + /// [`PageQuery::http_query_pairs`] and the name filter. + #[must_use] + pub fn http_query_pairs(&self) -> Vec<(&'static str, String)> { + let mut pairs = self.page.http_query_pairs(); + if let Some(name) = &self.name { + pairs.push((NAME_KEY, name.clone())); + } + pairs + } + + /// Whether the HTTP query parameters of a list request ask for one page: + /// they hold a `limit` or a `cursor`. Without both, a list route answers + /// the whole list, in the order and with the filter of the other keys. + #[must_use] + pub fn selects_page(pairs: &[(&str, &str)]) -> bool { + pairs + .iter() + .any(|(key, _)| matches!(*key, LIMIT_KEY | CURSOR_KEY)) + } + + /// Parse the page parameters of an HTTP list request. A missing parameter + /// keeps its default. + /// + /// Unknown or repeated keys and malformed values are refused. The result + /// is not yet validated, see [`Self::validate`]. + /// + /// # Errors + /// `InvalidCommand` for any refused parameter. + pub fn from_http_query<'a>( + pairs: impl IntoIterator<Item = (&'a str, &'a str)>, + ) -> Result<Self, IggyError> { + let mut seen = BTreeSet::new(); + let mut query = Self::default(); + for (key, value) in pairs { + if !seen.insert(key) { + return Err(IggyError::InvalidCommand); + } + match key { + ORDER_KEY => { + query.page.order = + PageOrder::from_str(value).map_err(|_| IggyError::InvalidCommand)?; + } + DESCENDING_KEY => { + query.page.descending = + bool::from_str(value).map_err(|_| IggyError::InvalidCommand)?; + } + LIMIT_KEY => query.page.limit = parse_canonical(value)?, + CURSOR_KEY => query.page.cursor = Some(PageCursor::from_str(value)?), + NAME_KEY => query.name = Some(value.to_owned()), + _ => return Err(IggyError::InvalidCommand), + } + } + Ok(query) + } +} + +impl From<PageOrder> for WirePageOrder { + fn from(order: PageOrder) -> Self { + match order { + PageOrder::Id => Self::Id, + PageOrder::Created => Self::Created, + } + } +} + +impl From<WirePageOrder> for PageOrder { + fn from(order: WirePageOrder) -> Self { + match order { + WirePageOrder::Id => Self::Id, + WirePageOrder::Created => Self::Created, + } + } +} + +impl From<WirePageCursor> for PageCursor { + fn from(cursor: WirePageCursor) -> Self { + Self(cursor) + } +} + +impl From<PageCursor> for WirePageCursor { + fn from(cursor: PageCursor) -> Self { + cursor.0 + } +} + +impl TryFrom<&PageQuery> for WirePageQuery { + type Error = IggyError; + + fn try_from(query: &PageQuery) -> Result<Self, Self::Error> { + query.validate()?; + Ok(Self { + order: query.order.into(), + descending: query.descending, + limit: query.limit, + cursor: query.cursor.map(Into::into), + name: None, + }) + } +} + +impl TryFrom<&NamedPageQuery> for WirePageQuery { + type Error = IggyError; + + fn try_from(query: &NamedPageQuery) -> Result<Self, Self::Error> { + query.validate()?; + let name = query + .name + .as_deref() + .map(WireName::new) + .transpose() + .map_err(|_| IggyError::InvalidCommand)?; + Ok(Self { + name, + ..Self::try_from(&query.page)? + }) + } +} + +/// The page block of a list without names, such as the partitions of a +/// topic. A block with a name filter is refused. +impl TryFrom<WirePageQuery> for PageQuery { + type Error = IggyError; + + fn try_from(page: WirePageQuery) -> Result<Self, Self::Error> { + if page.name.is_some() { + return Err(IggyError::InvalidCommand); + } + let query = Self { + order: page.order.into(), + descending: page.descending, + limit: page.limit, + cursor: page.cursor.map(PageCursor::from), + }; + query.validate()?; + Ok(query) + } +} + +impl TryFrom<WirePageQuery> for NamedPageQuery { + type Error = IggyError; + + /// A [`WireName`] already holds 1 to 255 bytes, so only the page needs a + /// check. + fn try_from(mut page: WirePageQuery) -> Result<Self, Self::Error> { + let name = page.name.take().map(|name| name.as_str().to_owned()); + Ok(Self { + page: PageQuery::try_from(page)?, + name, + }) + } +} + +impl Display for PageCursor { + fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result { + write!( + formatter, + "{PAGE_CURSOR_PREFIX}{}", + URL_SAFE_NO_PAD.encode(self.0.to_bytes()) + ) + } +} + +impl FromStr for PageCursor { + type Err = IggyError; + + fn from_str(text: &str) -> Result<Self, Self::Err> { + let bytes = decode_canonical(text, PAGE_CURSOR_PREFIX)?; + WirePageCursor::decode_exact(&bytes) + .map(Self) + .map_err(|_| IggyError::InvalidCommand) + } +} + +impl Serialize for PageCursor { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for PageCursor { + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + let text = String::deserialize(deserializer)?; + Self::from_str(&text).map_err(D::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::future::ready; + use std::pin::pin; + use std::task::{Context, Poll, Waker}; + + const ID_SEVEN: &str = "pg1_AQcAAAAAAAAA"; + + fn created(created_at: u64, id: u64) -> PageCursor { + PageCursor(WirePageCursor::Created { created_at, id }) + } + + #[test] + fn given_cursors_when_printing_should_round_trip_through_the_pg1_text() { + assert_eq!(PageCursor(WirePageCursor::Id(7)).to_string(), ID_SEVEN); + for cursor in [ + PageCursor(WirePageCursor::Id(0)), + PageCursor(WirePageCursor::Id(u64::MAX)), + created(1_700_000_000_000_000, 42), + created(u64::MAX, u64::MAX), + ] { + assert_eq!(PageCursor::from_str(&cursor.to_string()).unwrap(), cursor); + } + } + + #[test] + fn given_malformed_cursor_text_when_parsing_should_refuse() { + let refused = [ + "", + "AQcAAAAAAAAA", + "mc1_AQcAAAAAAAAA", + "pg2_AQcAAAAAAAAA", + "pg1_AQcAAAAAAAAA=", + "pg1_AQcAAAAAAAA+", + "pg1_AAcAAAAAAAAA", + "pg1_AwcAAAAAAAAA", + "pg1_AQcAAAAAAAAAAA", + "pg1_AgcAAAAAAAAA", + ]; + for text in refused { + assert_eq!( + PageCursor::from_str(text), + Err(IggyError::InvalidCommand), + "{text}" + ); + } + // 17 bytes leave two spare bits in the last character, which a + // canonical text keeps at zero. + let text = created(9, 3).to_string(); + let spare_bit_set = format!("{}B", text.strip_suffix('A').unwrap()); + assert_eq!( + PageCursor::from_str(&spare_bit_set), + Err(IggyError::InvalidCommand) + ); + } + + fn text_pairs<'a>(pairs: &'a [(&'static str, String)]) -> Vec<(&'static str, &'a str)> { + pairs + .iter() + .map(|(key, value)| (*key, value.as_str())) + .collect() + } + + #[test] + fn given_a_query_when_round_tripping_http_pairs_should_keep_it() { + let query = NamedPageQuery { + page: PageQuery { + order: PageOrder::Created, + descending: true, + limit: 20, + cursor: Some(created(9, 3)), + }, + name: Some("ord ers".to_owned()), + }; + let pairs = query.http_query_pairs(); + assert_eq!( + &pairs[..3], + &[ + ("order", "created".to_owned()), + ("descending", "true".to_owned()), + ("limit", "20".to_owned()), + ] + ); + assert_eq!( + NamedPageQuery::from_http_query(text_pairs(&pairs)).unwrap(), + query + ); + let unnamed = query.page.http_query_pairs(); + assert_eq!( + PageQuery::from_http_query(text_pairs(&unnamed)).unwrap(), + query.page + ); + assert_eq!( + NamedPageQuery::from_http_query(Vec::<(&str, &str)>::new()).unwrap(), + NamedPageQuery::default() + ); + } + + #[test] + fn given_refused_http_parameters_when_parsing_should_refuse_each() { + let refused: &[&[(&str, &str)]] = &[ + &[("offset", "10")], + &[("consistency", "linearizable")], + &[("limit", "10"), ("limit", "10")], + &[("limit", "010")], + &[("limit", "+10")], + &[("limit", "-1")], + &[("limit", "")], + &[("order", "name")], + &[("order", "ID")], + &[("descending", "1")], + &[("descending", "yes")], + &[("cursor", "pg1_")], + ]; + for pairs in refused { + assert_eq!( + NamedPageQuery::from_http_query(pairs.iter().copied()), + Err(IggyError::InvalidCommand), + "{pairs:?}" + ); + assert_eq!( + PageQuery::from_http_query(pairs.iter().copied()), + Err(IggyError::InvalidCommand), + "{pairs:?}" + ); + } + assert_eq!( + PageQuery::from_http_query([("name", "orders")]), + Err(IggyError::InvalidCommand), + "a list without names refuses a name key" + ); + } + + #[test] + fn given_http_parameters_when_asking_for_one_page_should_need_a_limit_or_a_cursor() { + let whole_list: &[&[(&str, &str)]] = &[ + &[], + &[ + ("name", "ord"), + ("order", "created"), + ("descending", "true"), + ], + ]; + for pairs in whole_list { + assert!(!NamedPageQuery::selects_page(pairs), "{pairs:?}"); + } + let one_page: &[&[(&str, &str)]] = + &[&[("limit", "10")], &[("name", "ord"), ("cursor", ID_SEVEN)]]; + for pairs in one_page { + assert!(NamedPageQuery::selects_page(pairs), "{pairs:?}"); + } + } + + #[test] + fn given_limits_and_names_when_validating_should_keep_the_ranges() { + let with = |limit, name: Option<&str>| NamedPageQuery { + page: PageQuery { + limit, + ..PageQuery::default() + }, + name: name.map(str::to_owned), + }; + assert!(with(1, None).validate().is_ok()); + assert!( + with(MAX_PAGE_LIMIT, Some("n".repeat(255).as_str())) + .validate() + .is_ok() + ); + for refused in [ + with(0, None), + with(MAX_PAGE_LIMIT + 1, None), + with(10, Some("")), + with(10, Some("n".repeat(256).as_str())), + ] { + assert_eq!(refused.validate(), Err(IggyError::InvalidCommand)); + assert_eq!( + WirePageQuery::try_from(&refused), + Err(IggyError::InvalidCommand) + ); + } + for limit in [0, MAX_PAGE_LIMIT + 1] { + let page = PageQuery { + limit, + ..PageQuery::default() + }; + assert_eq!(page.validate(), Err(IggyError::InvalidCommand)); + assert_eq!( + WirePageQuery::try_from(&page), + Err(IggyError::InvalidCommand) + ); + } + } + + #[test] + fn given_a_wire_block_with_a_name_when_reading_a_list_without_names_should_refuse_it() { + let named = NamedPageQuery { + name: Some("n".to_owned()), + ..NamedPageQuery::default() + }; + let wire = WirePageQuery::try_from(&named).unwrap(); + assert_eq!( + PageQuery::try_from(wire.clone()), + Err(IggyError::InvalidCommand) + ); + assert_eq!(NamedPageQuery::try_from(wire).unwrap(), named); + let unnamed = WirePageQuery::try_from(&PageQuery::default()).unwrap(); + assert_eq!(unnamed.name, None); + assert_eq!(PageQuery::try_from(unnamed).unwrap(), PageQuery::default()); + } + + #[test] + fn given_a_query_when_round_tripping_the_wire_block_should_keep_it() { + let query = NamedPageQuery { + page: PageQuery { + order: PageOrder::Created, + descending: true, + limit: 1000, + cursor: Some(created(5, 6)), + }, + name: Some("orders".to_owned()), + }; + let wire = WirePageQuery::try_from(&query).unwrap(); + assert_eq!(NamedPageQuery::try_from(wire.clone()).unwrap(), query); + let over_limit = WirePageQuery { + limit: 1001, + ..wire + }; + assert_eq!( + NamedPageQuery::try_from(over_limit), + Err(IggyError::InvalidCommand) + ); + } + + #[test] + fn given_a_page_when_asking_for_the_next_query_should_carry_its_cursor() { + let query = NamedPageQuery { + page: PageQuery { + limit: 2, + ..PageQuery::default() + }, + name: Some("ord".to_owned()), + }; + let more = Page { + items: vec![1, 2], + next: Some(PageCursor(WirePageCursor::Id(2))), + }; + let next = query.next(&more).unwrap().unwrap(); + assert_eq!(next.page.cursor, more.next); + assert_eq!(next.name, query.name); + let last = Page::<u32> { + items: vec![3], + next: None, + }; + assert_eq!(next.next(&last), Ok(None)); + assert_eq!( + next.next(&more), + Err(IggyError::InvalidFormat), + "a page that answers the cursor it was read with" + ); + } + + /// Drives a future whose every await is ready. + fn run_ready<T>(future: impl Future<Output = T>) -> T { + let mut future = pin!(future); + match future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + { + Poll::Ready(output) => output, + Poll::Pending => panic!("a ready reader never suspends"), + } + } + + #[test] + fn given_a_list_of_several_pages_when_reading_to_the_end_should_follow_each_cursor() { + const ITEMS: u64 = 7; + let first = NamedPageQuery { + page: PageQuery { + limit: 3, + ..PageQuery::default() + }, + name: Some("ord".to_owned()), + }; + let mut queries = Vec::new(); + let read = run_ready(first.clone().read_to_end(|query| { + let start = match query.page.cursor.map(WirePageCursor::from) { + None => 0, + Some(WirePageCursor::Id(id)) => id + 1, + Some(cursor) => panic!("an id walk got {cursor:?}"), + }; + let end = (start + u64::from(query.page.limit)).min(ITEMS); + let next = (end < ITEMS).then(|| PageCursor(WirePageCursor::Id(end - 1))); + queries.push(query); + ready(Ok(Page { + items: (start..end).collect(), + next, + })) + })); + assert_eq!(read, Ok((0..ITEMS).collect::<Vec<_>>())); + let cursors: Vec<_> = queries.iter().map(|query| query.page.cursor).collect(); + assert_eq!( + cursors, + [ + None, + Some(PageCursor(WirePageCursor::Id(2))), + Some(PageCursor(WirePageCursor::Id(5))) + ] + ); + assert!( + queries.iter().all(|query| NamedPageQuery { + page: PageQuery { + cursor: None, + ..query.page.clone() + }, + name: query.name.clone(), + } == first), + "every page keeps the order, the limit and the filter" + ); + } + + #[test] + fn given_a_failing_page_when_reading_to_the_end_should_return_its_error() { + let mut pages = 0; + let read = run_ready(PageQuery::whole_list().read_to_end(|query| { + pages += 1; + ready(if query.cursor.is_none() { + Ok(Page { + items: vec![1_u32], + next: Some(PageCursor(WirePageCursor::Id(1))), + }) + } else { + Err(IggyError::Unauthorized) + }) + })); + assert_eq!(read, Err(IggyError::Unauthorized)); + assert_eq!(pages, 2); + } + + #[test] + fn given_a_page_that_answers_its_own_cursor_when_reading_to_the_end_should_fail() { + const MAX_PAGES: u32 = 4; + let repeated = PageCursor(WirePageCursor::Id(1)); + let mut pages = 0; + let read = run_ready(PageQuery::whole_list().read_to_end(|_| { + pages += 1; + assert!( + pages <= MAX_PAGES, + "the walk must stop at the repeated cursor" + ); + ready(Ok(Page { + items: vec![pages], + next: Some(repeated), + })) + })); + assert_eq!(read, Err(IggyError::InvalidFormat)); + assert_eq!( + pages, 2, + "the second page answered the cursor it was read with" + ); + } + + #[test] + fn given_a_page_when_serializing_json_should_leave_out_next_on_the_last_page() { + let more = Page { + items: vec![1u32], + next: Some(PageCursor(WirePageCursor::Id(7))), + }; + let json = serde_json::to_string(&more).unwrap(); + assert_eq!(json, format!(r#"{{"items":[1],"next":"{ID_SEVEN}"}}"#)); + assert_eq!(serde_json::from_str::<Page<u32>>(&json).unwrap(), more); + let last = Page::<u32> { + items: Vec::new(), + next: None, + }; + assert_eq!(serde_json::to_string(&last).unwrap(), r#"{"items":[]}"#); + assert_eq!( + serde_json::from_str::<Page<u32>>(r#"{"items":[]}"#).unwrap(), + last + ); + assert!(serde_json::from_str::<Page<u32>>(r#"{"items":[],"next":"pg1_"}"#).is_err()); + } +}
diff --git a/core/common/src/wire_conversions.rs b/core/common/src/wire_conversions.rs index e87723b..0970236 100644 --- a/core/common/src/wire_conversions.rs +++ b/core/common/src/wire_conversions.rs
@@ -28,9 +28,9 @@ HeaderKind, HeaderValue, IdKind, Identifier, IdentityInfo, IggyByteSize, IggyError, OPTION_FLAG_CRITICAL, OPTION_FLAG_READ_ONLY, OPTION_FLAG_RESETTABLE, OPTION_FLAG_SECRET, OPTION_FLAG_UPDATABLE, OptionKey, OptionSpec, OptionValue, OptionsProvenance, OptionsScope, - Partition, Permissions, PersonalAccessTokenInfo, RawPersonalAccessToken, ResourceOptions, - Stats, Stream, StreamDetails, StreamPermissions, Topic, TopicDetails, TopicPermissions, - TransportEndpoints, UserInfo, UserInfoDetails, UserStatus, descriptors_for, + Page, PageCursor, Partition, Permissions, PersonalAccessTokenInfo, RawPersonalAccessToken, + ResourceOptions, Stats, Stream, StreamDetails, StreamPermissions, Topic, TopicDetails, + TopicPermissions, TransportEndpoints, UserInfo, UserInfoDetails, UserStatus, descriptors_for, }; use bytes::{BufMut, BytesMut}; use iggy_binary_protocol::primitives::options::{MAX_OPTIONS, MAX_OPTIONS_BYTES, WireOptions}; @@ -46,24 +46,22 @@ use iggy_binary_protocol::responses::consumer_groups::get_consumer_group::{ ConsumerGroupDetailsResponse, ConsumerGroupMemberResponse, }; -use iggy_binary_protocol::responses::consumer_groups::get_consumer_groups::GetConsumerGroupsResponse; use iggy_binary_protocol::responses::consumer_offsets::get_consumer_offset::ConsumerOffsetResponse; +use iggy_binary_protocol::responses::page::PageResponse; use iggy_binary_protocol::responses::personal_access_tokens::create_personal_access_token::RawPersonalAccessTokenResponse; use iggy_binary_protocol::responses::personal_access_tokens::get_personal_access_tokens::{ GetPersonalAccessTokensResponse, PersonalAccessTokenResponse, }; use iggy_binary_protocol::responses::streams::StreamResponse; -use iggy_binary_protocol::responses::streams::get_stream::{GetStreamResponse, TopicHeader}; -use iggy_binary_protocol::responses::streams::get_streams::GetStreamsResponse; +use iggy_binary_protocol::responses::streams::get_stream::{GetStreamResponse, TopicResponse}; use iggy_binary_protocol::responses::system::get_cluster_metadata::{ ClusterMetadataResponse, ClusterNodeResponse, }; use iggy_binary_protocol::responses::system::get_stats::{CacheMetricEntry, StatsResponse}; use iggy_binary_protocol::responses::topics::get_topic::{GetTopicResponse, PartitionResponse}; -use iggy_binary_protocol::responses::topics::get_topics::GetTopicsResponse; +use iggy_binary_protocol::responses::users::UserDetailsResponse; use iggy_binary_protocol::responses::users::login_user::IdentityResponse; use iggy_binary_protocol::responses::users::user_response::UserResponse; -use iggy_binary_protocol::responses::users::{GetUsersResponse, UserDetailsResponse}; use iggy_binary_protocol::{WireConsumer, WireIdentifier, WireUserHeaderIterator}; use std::collections::{BTreeMap, HashMap}; @@ -116,24 +114,34 @@ } } -pub fn streams_from_wire(w: GetStreamsResponse) -> Result<Vec<Stream>, IggyError> { - let mut streams: Vec<Stream> = w - .streams - .into_iter() - .map(Stream::try_from) - .collect::<Result<_, _>>()?; - streams.sort_by_key(|s| s.id); - Ok(streams) +// --------------------------------------------------------------------------- +// Pages +// --------------------------------------------------------------------------- + +/// A wire page with each item converted by `convert`. The items keep the +/// order of the server. +pub fn page_from_wire<W, T>( + page: PageResponse<W>, + convert: impl FnMut(W) -> Result<T, IggyError>, +) -> Result<Page<T>, IggyError> { + Ok(Page { + items: page + .items + .into_iter() + .map(convert) + .collect::<Result<_, _>>()?, + next: page.next.map(PageCursor::from), + }) } // --------------------------------------------------------------------------- // Topics // --------------------------------------------------------------------------- -impl TryFrom<TopicHeader> for Topic { +impl TryFrom<TopicResponse> for Topic { type Error = IggyError; - fn try_from(w: TopicHeader) -> Result<Self, Self::Error> { + fn try_from(w: TopicResponse) -> Result<Self, Self::Error> { let options = resource_options_from_wire_split(&w.options, &w.derived_options)?; Ok(Self { id: w.id, @@ -184,16 +192,6 @@ } } -pub fn topics_from_wire(w: GetTopicsResponse) -> Result<Vec<Topic>, IggyError> { - let mut topics: Vec<Topic> = w - .topics - .into_iter() - .map(Topic::try_from) - .collect::<Result<_, _>>()?; - topics.sort_by_key(|t| t.id); - Ok(topics) -} - // --------------------------------------------------------------------------- // Users // --------------------------------------------------------------------------- @@ -229,16 +227,6 @@ } } -pub fn users_from_wire(w: GetUsersResponse) -> Result<Vec<UserInfo>, IggyError> { - let mut users: Vec<UserInfo> = w - .users - .into_iter() - .map(UserInfo::try_from) - .collect::<Result<_, _>>()?; - users.sort_by_key(|u| u.id); - Ok(users) -} - impl From<IdentityResponse> for IdentityInfo { fn from(w: IdentityResponse) -> Self { Self { @@ -356,12 +344,6 @@ } } -pub fn consumer_groups_from_wire(w: GetConsumerGroupsResponse) -> Vec<ConsumerGroup> { - let mut groups: Vec<ConsumerGroup> = w.groups.into_iter().map(ConsumerGroup::from).collect(); - groups.sort_by_key(|g| g.id); - groups -} - // --------------------------------------------------------------------------- // Consumer Offsets // ---------------------------------------------------------------------------
diff --git a/core/common/tests/list_pages_fixtures.rs b/core/common/tests/list_pages_fixtures.rs new file mode 100644 index 0000000..eff5da9 --- /dev/null +++ b/core/common/tests/list_pages_fixtures.rs
@@ -0,0 +1,349 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#[path = "../examples/list_pages_fixtures/schema.rs"] +mod schema; + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use iggy_binary_protocol::primitives::page::{WirePageCursor, WirePageOrder, WirePageQuery}; +use iggy_binary_protocol::requests::consumer_groups::GetConsumerGroupsRequest; +use iggy_binary_protocol::requests::partitions::GetPartitionsRequest; +use iggy_binary_protocol::requests::streams::GetStreamsRequest; +use iggy_binary_protocol::requests::topics::GetTopicsRequest; +use iggy_binary_protocol::requests::users::GetUsersRequest; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::responses::consumer_groups::ConsumerGroupResponse; +use iggy_binary_protocol::responses::streams::{StreamResponse, TopicResponse}; +use iggy_binary_protocol::responses::topics::PartitionResponse; +use iggy_binary_protocol::responses::users::UserResponse; +use iggy_binary_protocol::{WireDecode, WireEncode, WireError, WireIdentifier}; +use iggy_common::{ + DEFAULT_PAGE_LIMIT, NamedPageQuery, PAGE_CURSOR_PREFIX, PageCursor, PageOrder, PageQuery, +}; +use schema::{ + CANONICAL_PATH, ItemFields, LANGUAGE_COPIES, ListCommand, MAX_CURSOR_BYTES, PageItem, build, + render, +}; +use std::fs; +use std::path::Path; +use std::str::FromStr; + +#[test] +fn given_live_codecs_when_rendering_fixture_should_match_the_canonical_file() { + let rendered = render().expect("fixture builds"); + assert!( + read_manifest_file(CANONICAL_PATH) == rendered.as_bytes(), + "{CANONICAL_PATH} is stale, rerun: cargo run -p iggy_common --example list_pages_fixtures" + ); +} + +#[test] +fn given_language_copies_when_comparing_should_match_canonical_bytes() { + let canonical = read_manifest_file(CANONICAL_PATH); + for copy in LANGUAGE_COPIES { + assert!( + read_manifest_file(copy) == canonical, + "{copy} differs from {CANONICAL_PATH}, rerun the list_pages_fixtures example" + ); + } +} + +#[test] +fn given_cursor_vectors_when_parsing_and_printing_should_round_trip() { + let fixture = build().expect("fixture builds"); + for vector in &fixture.cursors { + let bytes = hex::decode(&vector.hex).expect("hex"); + let cursor = PageCursor::from_str(&vector.text).expect(&vector.case); + assert_eq!( + WirePageCursor::from(cursor).to_bytes()[..], + bytes[..], + "{}", + vector.case + ); + assert_eq!(cursor.to_string(), vector.text, "{}", vector.case); + assert_eq!(text_rule(&vector.text), Some(bytes), "{}", vector.case); + } + let texts: String = fixture + .cursors + .iter() + .map(|vector| &vector.text[PAGE_CURSOR_PREFIX.len()..]) + .collect(); + assert!( + texts.contains('-') && texts.contains('_'), + "the cursor texts hold both characters that only Base64url has" + ); +} + +#[test] +fn given_opaque_cursors_when_parsing_or_decoding_a_request_should_pass_only_the_text_rule() { + let fixture = build().expect("fixture builds"); + for vector in &fixture.cursors { + let request = first_page_block_with_cursor(&hex::decode(&vector.hex).expect("hex")); + assert!( + GetStreamsRequest::decode_from(&request).is_ok(), + "{}: the same block with a valid cursor decodes", + vector.case + ); + } + for vector in &fixture.opaque_cursors { + let bytes = hex::decode(&vector.hex).expect("hex"); + assert!( + PageCursor::from_str(&vector.text).is_err(), + "{}", + vector.case + ); + let request = first_page_block_with_cursor(&bytes); + assert!( + GetStreamsRequest::decode_from(&request).is_err(), + "{}: the server decodes the request", + vector.case + ); + assert_eq!(text_rule(&vector.text), Some(bytes), "{}", vector.case); + } +} + +#[test] +fn given_request_vectors_when_decoding_should_reach_a_query_that_a_server_serves() { + let fixture = build().expect("fixture builds"); + for vector in &fixture.requests { + let bytes = hex::decode(&vector.request_hex).expect("hex"); + let (stream_id, topic_id, page) = decode_request(vector.command, &bytes) + .unwrap_or_else(|error| panic!("{}: {error}", vector.case)); + let parent = |id: Option<&schema::Identifier>| { + id.map(|id| WireIdentifier::try_from(id).expect("identifier")) + }; + assert_eq!( + (stream_id, topic_id), + ( + parent(vector.input.stream_id.as_ref()), + parent(vector.input.topic_id.as_ref()) + ), + "{}", + vector.case + ); + let query = vector.input.query(); + assert_eq!( + page, + WirePageQuery::try_from(&query).expect("valid query"), + "{}", + vector.case + ); + assert_served(vector.command, &query, &vector.case); + let pairs = vector + .http_query + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())); + let parsed = match vector.command { + ListCommand::Partitions => PageQuery::from_http_query(pairs).map(NamedPageQuery::from), + _ => NamedPageQuery::from_http_query(pairs), + }; + assert_eq!(parsed.expect(&vector.case), query, "{}", vector.case); + } +} + +#[test] +fn given_response_vectors_when_decoding_should_reach_their_next_and_items() { + let fixture = build().expect("fixture builds"); + for vector in &fixture.responses { + let bytes = hex::decode(&vector.response_hex).expect("hex"); + let reply = decode_reply(vector.command, &bytes) + .unwrap_or_else(|error| panic!("{}: {error}", vector.case)); + assert_eq!( + (reply.next, reply.items, reply.consumed), + (vector.next.clone(), vector.items.clone(), bytes.len()), + "{}", + vector.case + ); + } + for command in ListCommand::ALL { + assert!( + fixture + .responses + .iter() + .any(|vector| vector.command == command && vector.items.len() > 1), + "{} has a page of more than one item", + command.name() + ); + } + assert!( + fixture + .responses + .iter() + .any(|vector| vector.items.is_empty() && vector.next.is_some()), + "an empty page with a next" + ); +} + +#[test] +fn given_opaque_responses_when_decoding_should_hold_a_valid_page_after_a_next_rust_refuses() { + let fixture = build().expect("fixture builds"); + for vector in &fixture.opaque_responses { + let bytes = hex::decode(&vector.response_hex).expect("hex"); + assert!( + decode_reply(vector.command, &bytes).is_err(), + "{}", + vector.case + ); + let next_end = 1 + usize::from(bytes[0]); + let next = vector.next.as_deref().expect("an opaque next"); + assert_eq!( + text_rule(next).as_deref(), + Some(&bytes[1..next_end]), + "{}", + vector.case + ); + let without_next = [&[0][..], &bytes[next_end..]].concat(); + let reply = decode_reply(vector.command, &without_next) + .unwrap_or_else(|error| panic!("{}: {error}", vector.case)); + assert_eq!( + (reply.next, reply.items, reply.consumed), + (None, vector.items.clone(), without_next.len()), + "{}", + vector.case + ); + } +} + +#[test] +fn given_refused_vectors_when_parsing_validating_or_decoding_should_refuse_each() { + let fixture = build().expect("fixture builds"); + for vector in &fixture.refused.cursors { + assert_eq!(text_rule(&vector.text), None, "{}", vector.case); + assert!( + PageCursor::from_str(&vector.text).is_err(), + "{}", + vector.case + ); + } + for vector in &fixture.refused.queries { + assert!(vector.input.query().validate().is_err(), "{}", vector.case); + } + for vector in &fixture.refused.responses { + let bytes = hex::decode(&vector.response_hex).expect("hex"); + assert!( + decode_reply(vector.command, &bytes).is_err(), + "{}", + vector.case + ); + } +} + +/// The cursor check of a foreign SDK: the prefix, then canonical unpadded +/// Base64url of 1 to 255 bytes. It does not read the bytes. +fn text_rule(text: &str) -> Option<Vec<u8>> { + let encoded = text.strip_prefix(PAGE_CURSOR_PREFIX)?; + let bytes = URL_SAFE_NO_PAD.decode(encoded).ok()?; + (URL_SAFE_NO_PAD.encode(&bytes) == encoded && (1..=MAX_CURSOR_BYTES).contains(&bytes.len())) + .then_some(bytes) +} + +/// The page block that a client which does not read the cursor bytes sends. +fn first_page_block_with_cursor(cursor: &[u8]) -> Vec<u8> { + let cursor_len = u8::try_from(cursor.len()).expect("a cursor length fits one byte"); + let no_name = 0; + [ + &[WirePageOrder::Id.as_u8(), u8::from(false)][..], + &DEFAULT_PAGE_LIMIT.to_le_bytes(), + &[cursor_len], + cursor, + &[no_name], + ] + .concat() +} + +/// The server refuses a cursor of the other walk and a name filter on +/// partitions, so every request vector must be one that a server serves. +fn assert_served(command: ListCommand, query: &NamedPageQuery, case: &str) { + let id_walk = matches!( + command, + ListCommand::Partitions | ListCommand::ConsumerGroups + ) || query.page.order == PageOrder::Id; + let cursor_fits = match query.page.cursor.map(WirePageCursor::from) { + None => true, + Some(WirePageCursor::Id(_)) => id_walk, + Some(WirePageCursor::Created { .. }) => !id_walk, + }; + assert!(cursor_fits, "{case}: the cursor kind does not fit the walk"); + assert!( + command != ListCommand::Partitions || query.name.is_none(), + "{case}: partitions have no name filter" + ); +} + +type DecodedRequest = ( + Option<WireIdentifier>, + Option<WireIdentifier>, + WirePageQuery, +); + +fn decode_request(command: ListCommand, bytes: &[u8]) -> Result<DecodedRequest, WireError> { + Ok(match command { + ListCommand::Users => (None, None, GetUsersRequest::decode_from(bytes)?.page), + ListCommand::Streams => (None, None, GetStreamsRequest::decode_from(bytes)?.page), + ListCommand::Topics => { + let request = GetTopicsRequest::decode_from(bytes)?; + (Some(request.stream_id), None, request.page) + } + ListCommand::Partitions => { + let request = GetPartitionsRequest::decode_from(bytes)?; + ( + Some(request.stream_id), + Some(request.topic_id), + request.page, + ) + } + ListCommand::ConsumerGroups => { + let request = GetConsumerGroupsRequest::decode_from(bytes)?; + ( + Some(request.stream_id), + Some(request.topic_id), + request.page, + ) + } + }) +} + +struct DecodedReply { + next: Option<String>, + items: Vec<ItemFields>, + consumed: usize, +} + +fn decode_reply(command: ListCommand, bytes: &[u8]) -> Result<DecodedReply, WireError> { + match command { + ListCommand::Users => decode_page::<UserResponse>(bytes), + ListCommand::Streams => decode_page::<StreamResponse>(bytes), + ListCommand::Topics => decode_page::<TopicResponse>(bytes), + ListCommand::Partitions => decode_page::<PartitionResponse>(bytes), + ListCommand::ConsumerGroups => decode_page::<ConsumerGroupResponse>(bytes), + } +} + +fn decode_page<T: PageItem>(bytes: &[u8]) -> Result<DecodedReply, WireError> { + let (page, consumed) = PageResponse::<T>::decode(bytes)?; + Ok(DecodedReply { + next: page.next.map(|cursor| PageCursor::from(cursor).to_string()), + items: page.items.iter().map(PageItem::fields).collect(), + consumed, + }) +} + +fn read_manifest_file(relative: &str) -> Vec<u8> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(relative); + fs::read(&path).unwrap_or_else(|error| panic!("read {}: {error}", path.display())) +}
diff --git a/core/common/tests/resource_options_fixtures.rs b/core/common/tests/resource_options_fixtures.rs index 2089f4b..cd2abc8 100644 --- a/core/common/tests/resource_options_fixtures.rs +++ b/core/common/tests/resource_options_fixtures.rs
@@ -24,7 +24,7 @@ use iggy_binary_protocol::requests::system::{DescribeOptionsRequest, UpdateResourceRequest}; use iggy_binary_protocol::requests::topics::CreateTopicRequest; use iggy_binary_protocol::requests::users::CreateUserRequest; -use iggy_binary_protocol::responses::streams::{GetStreamResponse, StreamResponse, TopicHeader}; +use iggy_binary_protocol::responses::streams::{GetStreamResponse, StreamResponse, TopicResponse}; use iggy_binary_protocol::responses::system::DescribeOptionsResponse; use iggy_binary_protocol::responses::topics::GetTopicResponse; use iggy_binary_protocol::responses::users::{UserDetailsResponse, UserResponse}; @@ -65,9 +65,9 @@ ); assert_eq!( constants.protocol_version.packed, - pack_protocol_version(0, 12, 2) + pack_protocol_version(0, 12, 3) ); - assert_eq!(constants.protocol_version.text, "0.12.2"); + assert_eq!(constants.protocol_version.text, "0.12.3"); assert_eq!( constants.command_codes["update_resource"], CommandCode { @@ -660,7 +660,7 @@ vector.case ); let rebuilt = GetTopicResponse { - topic: TopicHeader { + topic: TopicResponse { id: vector.expected.id, created_at: vector.expected.created_at, partitions_count: vector.expected.partitions_count,
diff --git a/core/integration/tests/cli/common/list_runs.rs b/core/integration/tests/cli/common/list_runs.rs new file mode 100644 index 0000000..a04ed90 --- /dev/null +++ b/core/integration/tests/cli/common/list_runs.rs
@@ -0,0 +1,178 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Runs of a list command in list mode or JSON mode, with the page flags. A +//! run can pass the cursor of the run before it to `--after`, as a user does. + +use crate::cli::common::{IggyCmdCommand, IggyCmdTest, IggyCmdTestCase}; +use assert_cmd::assert::Assert; +use async_trait::async_trait; +use futures::future::BoxFuture; +use iggy::prelude::Client; +use serde_json::Value; +use std::sync::{Arc, Mutex}; + +/// In the arguments of a run, the cursor that the run before it printed. +pub(crate) const NEXT: &str = "{next}"; + +const NEXT_PREFIX: &str = "next: "; + +/// A run with these arguments prints JSON, not list mode rows. +const JSON_OUTPUT: &str = "-o json"; + +/// A JSON run with this flag prints a page object, without it a bare array. +const LIMIT_FLAG: &str = "--limit"; + +/// The key of the entity name in a JSON row. +const NAME_KEY: &str = "name"; + +/// Creates the entities that the runs list. +pub(crate) type Seed = for<'a> fn(&'a dyn Client) -> BoxFuture<'a, ()>; + +/// One run of a list command. +pub(crate) struct ListRun { + /// The words after `iggy`, split at spaces. + pub(crate) args: String, + /// The field of each row that the run must print, in order. In JSON + /// mode, the name of each row. + pub(crate) rows: Vec<String>, + /// Whether the run must print a cursor: the last line `next:`, or the + /// `next` field in JSON mode. + pub(crate) next: bool, +} + +impl ListRun { + pub(crate) fn new(args: &str, rows: &[&str], next: bool) -> Self { + Self { + args: args.to_owned(), + rows: rows.iter().map(|&row| row.to_owned()).collect(), + next, + } + } +} + +/// Seeds a new server, then executes the runs in order. `column` is the field +/// of a list mode row that a run compares. +pub(crate) async fn execute_list_runs(seed: Seed, column: usize, runs: Vec<ListRun>) { + let mut iggy_cmd_test = IggyCmdTest::default(); + iggy_cmd_test.setup().await; + let next = Arc::new(Mutex::new(None)); + let mut seed = Some(seed); + for run in runs { + iggy_cmd_test + .execute_test(TestListRunCmd { + seed: seed.take(), + run, + column, + next: Arc::clone(&next), + }) + .await; + } +} + +struct TestListRunCmd { + seed: Option<Seed>, + run: ListRun, + column: usize, + /// The cursor that the last run printed. + next: Arc<Mutex<Option<String>>>, +} + +#[async_trait] +impl IggyCmdTestCase for TestListRunCmd { + async fn prepare_server_state(&mut self, client: &dyn Client) { + if let Some(seed) = self.seed { + seed(client).await; + } + } + + fn get_command(&self) -> IggyCmdCommand { + let next = self.next.lock().expect("an unpoisoned lock").clone(); + let args: Vec<String> = self + .run + .args + .split(' ') + .map(|arg| match arg { + NEXT => next.clone().expect("the run before printed a cursor"), + arg => arg.to_owned(), + }) + .collect(); + IggyCmdCommand::new().args(args).with_env_credentials() + } + + fn verify_command(&self, command_state: Assert) { + let stdout = String::from_utf8(command_state.success().get_output().stdout.clone()) + .expect("UTF-8 output"); + let (rows, next) = if self.run.args.contains(JSON_OUTPUT) { + self.json_rows(&stdout) + } else { + self.list_mode_rows(&stdout) + }; + assert_eq!(rows, self.run.rows, "{}", self.run.args); + assert_eq!(next.is_some(), self.run.next, "{}: {stdout}", self.run.args); + *self.next.lock().expect("an unpoisoned lock") = next; + } + + async fn verify_server_state(&self, _client: &dyn Client) {} +} + +impl TestListRunCmd { + /// The fields and the cursor of a list mode run. + fn list_mode_rows(&self, stdout: &str) -> (Vec<String>, Option<String>) { + let lines: Vec<&str> = stdout.lines().collect(); + let Some((executing, rest)) = lines.split_first() else { + panic!("{}: no output", self.run.args); + }; + assert!(executing.starts_with("Executing "), "{stdout}"); + let (rows, next) = match rest.split_last() { + Some((last, rows)) if last.starts_with(NEXT_PREFIX) => { + (rows, last.strip_prefix(NEXT_PREFIX)) + } + _ => (rest, None), + }; + let fields = rows + .iter() + .map(|row| { + row.split('|') + .nth(self.column) + .expect("a list mode row") + .to_owned() + }) + .collect(); + (fields, next.map(str::to_owned)) + } + + /// The names and the cursor of a JSON run. The whole stdout must be one + /// JSON document: a page object with `--limit`, otherwise a bare array. + fn json_rows(&self, stdout: &str) -> (Vec<String>, Option<String>) { + let output: Value = serde_json::from_str(stdout) + .unwrap_or_else(|error| panic!("{}: {error}: {stdout}", self.run.args)); + let (items, next) = if self.run.args.contains(LIMIT_FLAG) { + (&output["items"], output.get("next")) + } else { + (&output, None) + }; + let names = items + .as_array() + .unwrap_or_else(|| panic!("{}: no row array: {stdout}", self.run.args)) + .iter() + .map(|item| item[NAME_KEY].as_str().expect("a row name").to_owned()) + .collect(); + let next = next.map(|next| next.as_str().expect("a cursor string").to_owned()); + (names, next) + } +}
diff --git a/core/integration/tests/cli/common/mod.rs b/core/integration/tests/cli/common/mod.rs index 992c408..5ff9c0d 100644 --- a/core/integration/tests/cli/common/mod.rs +++ b/core/integration/tests/cli/common/mod.rs
@@ -19,6 +19,7 @@ pub(crate) mod help; pub(crate) mod json_output; pub(crate) mod keyring; +pub(crate) mod list_runs; pub(crate) use crate::cli::common::command::IggyCmdCommand; pub(crate) use crate::cli::common::help::{CLAP_INDENT, TestHelpCmd, USAGE_PREFIX}; pub(crate) use crate::cli::common::keyring::clear_session_entry;
diff --git a/core/integration/tests/cli/consumer_group/test_consumer_group_list_command.rs b/core/integration/tests/cli/consumer_group/test_consumer_group_list_command.rs index 9bd1110..c8c4408 100644 --- a/core/integration/tests/cli/consumer_group/test_consumer_group_list_command.rs +++ b/core/integration/tests/cli/consumer_group/test_consumer_group_list_command.rs
@@ -15,19 +15,27 @@ // specific language governing permissions and limitations // under the License. +use crate::cli::common::list_runs::{ListRun, execute_list_runs}; use crate::cli::common::{ CLAP_INDENT, IggyCmdCommand, IggyCmdTest, IggyCmdTestCase, OutputFormat, TestHelpCmd, USAGE_PREFIX, }; use assert_cmd::assert::Assert; use async_trait::async_trait; +use futures::future::BoxFuture; use iggy::prelude::Client; +use iggy::prelude::Identifier; use iggy::prelude::IggyExpiry; use iggy::prelude::StreamCreateOptions; use iggy::prelude::TopicCreateOptions; use predicates::str::{contains, starts_with}; use serial_test::parallel; +const PAGES_STREAM: &str = "pages"; +const PAGES_TOPIC: &str = "events"; +/// The field of the group name in a list mode row. +const NAME_COLUMN: usize = 1; + struct TestConsumerGroupListCmd { stream_name: String, topic_name: String, @@ -205,6 +213,67 @@ #[tokio::test] #[parallel] +pub async fn should_print_pages() { + execute_list_runs( + seed_consumer_groups, + NAME_COLUMN, + vec![ + ListRun::new( + "consumer-group list pages events -l list", + &["pages-g1", "pages-g2", "pages-g3"], + false, + ), + ListRun::new( + "consumer-group list pages events -l list --desc --limit 2", + &["pages-g3", "pages-g2"], + true, + ), + ListRun::new( + "consumer-group list pages events -l list --desc --limit 2 --after {next}", + &["pages-g1"], + false, + ), + ListRun::new( + "consumer-group list pages events -l list --name g2", + &["pages-g2"], + false, + ), + ], + ) + .await; +} + +fn seed_consumer_groups(client: &dyn Client) -> BoxFuture<'_, ()> { + Box::pin(async move { + let stream_id = Identifier::named(PAGES_STREAM).expect("a stream name"); + let topic_id = Identifier::named(PAGES_TOPIC).expect("a topic name"); + client + .create_stream(PAGES_STREAM, &StreamCreateOptions::default()) + .await + .expect("create stream"); + client + .create_topic( + &stream_id, + PAGES_TOPIC, + &TopicCreateOptions { + partitions_count: Some(1), + message_expiry: Some(IggyExpiry::NeverExpire), + ..TopicCreateOptions::default() + }, + ) + .await + .expect("create topic"); + for name in ["pages-g1", "pages-g2", "pages-g3"] { + client + .create_consumer_group(&stream_id, &topic_id, name) + .await + .expect("create consumer group"); + } + }) +} + +#[tokio::test] +#[parallel] pub async fn should_help_match() { let mut iggy_cmd_test = IggyCmdTest::help_message(); @@ -222,6 +291,7 @@ iggy consumer-group list stream 2 --list-mode table iggy consumer-group list 3 topic -l table iggy consumer-group list production sensor -l table + iggy consumer-group list production sensor --desc --limit 20 {USAGE_PREFIX} consumer-group list [OPTIONS] <STREAM_ID> <TOPIC_ID> @@ -243,6 +313,28 @@ [default: table] [possible values: table, list] + --sort <SORT> + Order of the rows, by ID or by creation time +{CLAP_INDENT} + [default: id] + [possible values: id, created] + + --desc + Print the rows in descending order + + --limit <N> + Print at most N rows +{CLAP_INDENT} + If more rows follow them, the last line is `next: <CURSOR>`. Pass that cursor to --after to print the rows that follow. + + --after <CURSOR> + Print the rows after this cursor +{CLAP_INDENT} + The cursor comes from the `next:` line of a list with --limit. Use the same other flags as that list. + + --name <TEXT> + Print only the rows whose name holds this text (case-sensitive) + -h, --help Print help (see a summary with '-h') "#, @@ -270,6 +362,11 @@ Options: -l, --list-mode <LIST_MODE> List mode (table or list) [default: table] [possible values: table, list] + --sort <SORT> Order of the rows, by ID or by creation time [default: id] [possible values: id, created] + --desc Print the rows in descending order + --limit <N> Print at most N rows + --after <CURSOR> Print the rows after this cursor + --name <TEXT> Print only the rows whose name holds this text (case-sensitive) -h, --help Print help (see more with '--help') "#, ),
diff --git a/core/integration/tests/cli/partition/mod.rs b/core/integration/tests/cli/partition/mod.rs index 539a448..75c10e1 100644 --- a/core/integration/tests/cli/partition/mod.rs +++ b/core/integration/tests/cli/partition/mod.rs
@@ -18,3 +18,4 @@ mod test_partition_create_command; mod test_partition_delete_command; mod test_partition_help_command; +mod test_partition_list_command;
diff --git a/core/integration/tests/cli/partition/test_partition_help_command.rs b/core/integration/tests/cli/partition/test_partition_help_command.rs index 8e9446e..3217ae0 100644 --- a/core/integration/tests/cli/partition/test_partition_help_command.rs +++ b/core/integration/tests/cli/partition/test_partition_help_command.rs
@@ -36,6 +36,8 @@ and stream ID based on the given count. [alias: c] delete Delete partitions for the specified topic ID and stream ID based on the given count. [alias: d] + list List partitions for the specified topic ID + and stream ID. [alias: l] help Print this message or the help of the given subcommand(s) Options:
diff --git a/core/integration/tests/cli/partition/test_partition_list_command.rs b/core/integration/tests/cli/partition/test_partition_list_command.rs new file mode 100644 index 0000000..333791b --- /dev/null +++ b/core/integration/tests/cli/partition/test_partition_list_command.rs
@@ -0,0 +1,293 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::cli::common::list_runs::{ListRun, execute_list_runs}; +use crate::cli::common::{ + CLAP_INDENT, IggyCmdCommand, IggyCmdTest, IggyCmdTestCase, TestHelpCmd, USAGE_PREFIX, +}; +use assert_cmd::assert::Assert; +use async_trait::async_trait; +use futures::future::BoxFuture; +use iggy::prelude::{ + Client, Identifier, IggyExpiry, MAX_PAGE_LIMIT, StreamCreateOptions, TopicCreateOptions, +}; +use iggy_common::MAX_PARTITIONS_COUNT; +use serial_test::parallel; +use std::ops::RangeInclusive; + +const PAGES_STREAM: &str = "pages"; +const PAGES_TOPIC: &str = "events"; +const PARTITIONS: u32 = 5; +/// The field of the partition ID in a list mode row. +const ID_COLUMN: usize = 0; +/// The columns of the partition table of `topic get`. +const TABLE_HEADER: [&str; 8] = [ + "Partition id", + "Created", + "Segments count", + "Current offset", + "Size", + "Messages count", + "Members", + "In sync", +]; + +struct TestPartitionListCmd; + +#[async_trait] +impl IggyCmdTestCase for TestPartitionListCmd { + async fn prepare_server_state(&mut self, client: &dyn Client) { + create_topic(client, PARTITIONS).await; + } + + fn get_command(&self) -> IggyCmdCommand { + IggyCmdCommand::new() + .args(vec!["partition", "list", PAGES_STREAM, PAGES_TOPIC]) + .with_env_credentials() + } + + fn verify_command(&self, command_state: Assert) { + let stdout = String::from_utf8(command_state.success().get_output().stdout.clone()) + .expect("UTF-8 output"); + let mut lines = stdout.lines(); + assert_eq!( + lines.next(), + Some( + format!( + "Executing list partitions for stream with ID: {PAGES_STREAM} and topic with ID: {PAGES_TOPIC} in table mode" + ) + .as_str() + ) + ); + let cells = |line: &str| -> Vec<String> { + line.split('|') + .map(|cell| cell.trim().to_owned()) + .filter(|cell| !cell.is_empty()) + .collect() + }; + // The lines between rows start with `|-` or `|=`. + let mut rows = lines.filter(|line| line.starts_with("| ")).map(cells); + assert_eq!(rows.next(), Some(TABLE_HEADER.map(str::to_owned).to_vec())); + let first_cells: Vec<String> = rows.map(|row| row[0].clone()).collect(); + assert_eq!(first_cells, ids(0..=PARTITIONS - 1), "{stdout}"); + } + + async fn verify_server_state(&self, _client: &dyn Client) {} +} + +#[tokio::test] +#[parallel] +pub async fn should_be_successful() { + let mut iggy_cmd_test = IggyCmdTest::default(); + + iggy_cmd_test.setup().await; + iggy_cmd_test.execute_test(TestPartitionListCmd).await; +} + +#[tokio::test] +#[parallel] +pub async fn should_print_pages() { + execute_list_runs( + seed_partitions, + ID_COLUMN, + vec![ + ListRun::new( + "partition list pages events -l list", + &["0", "1", "2", "3", "4"], + false, + ), + ListRun::new( + "partition list pages events -l list --desc --limit 2", + &["4", "3"], + true, + ), + ListRun::new( + "partition list pages events -l list --desc --after {next}", + &["2", "1", "0"], + false, + ), + ], + ) + .await; +} + +#[tokio::test] +#[parallel] +pub async fn should_print_more_rows_than_one_page() { + let last = MAX_PAGE_LIMIT; + execute_list_runs( + seed_more_partitions_than_one_page, + ID_COLUMN, + vec![ + ListRun { + args: "partition list pages events -l list".to_owned(), + rows: ids(0..=last), + next: false, + }, + ListRun { + args: format!("partition list pages events -l list --limit {}", last + 1), + rows: ids(0..=last), + next: false, + }, + ListRun { + args: format!("partition list pages events -l list --limit {last}"), + rows: ids(0..=last - 1), + next: true, + }, + ListRun { + args: "partition list pages events -l list --after {next}".to_owned(), + rows: ids(last..=last), + next: false, + }, + ], + ) + .await; +} + +#[tokio::test] +#[parallel] +pub async fn should_help_match() { + let mut iggy_cmd_test = IggyCmdTest::help_message(); + + iggy_cmd_test + .execute_test_for_help_command(TestHelpCmd::new( + vec!["partition", "list", "--help"], + format!( + r#"List partitions for the specified topic ID +and stream ID. + +Stream ID can be specified as a stream name or ID +Topic ID can be specified as a topic name or ID + +Examples + iggy partition list 1 1 + iggy partition list prod sensor -l list + iggy partition list prod sensor --desc --limit 100 + +{USAGE_PREFIX} partition list [OPTIONS] <STREAM_ID> <TOPIC_ID> + +Arguments: + <STREAM_ID> + Stream ID to list partitions +{CLAP_INDENT} + Stream ID can be specified as a stream name or ID + + <TOPIC_ID> + Topic ID to list partitions +{CLAP_INDENT} + Topic ID can be specified as a topic name or ID + +Options: + -l, --list-mode <LIST_MODE> + List mode (table or list) +{CLAP_INDENT} + [default: table] + [possible values: table, list] + + --desc + Print the rows in descending order + + --limit <N> + Print at most N rows +{CLAP_INDENT} + If more rows follow them, the last line is `next: <CURSOR>`. Pass that cursor to --after to print the rows that follow. + + --after <CURSOR> + Print the rows after this cursor +{CLAP_INDENT} + The cursor comes from the `next:` line of a list with --limit. Use the same other flags as that list. + + -h, --help + Print help (see a summary with '-h') +"#, + ), + )) + .await; +} + +#[tokio::test] +#[parallel] +pub async fn should_short_help_match() { + let mut iggy_cmd_test = IggyCmdTest::help_message(); + + iggy_cmd_test + .execute_test_for_help_command(TestHelpCmd::new( + vec!["partition", "list", "-h"], + format!( + r#"List partitions for the specified topic ID +and stream ID. + +{USAGE_PREFIX} partition list [OPTIONS] <STREAM_ID> <TOPIC_ID> + +Arguments: + <STREAM_ID> Stream ID to list partitions + <TOPIC_ID> Topic ID to list partitions + +Options: + -l, --list-mode <LIST_MODE> List mode (table or list) [default: table] [possible values: table, list] + --desc Print the rows in descending order + --limit <N> Print at most N rows + --after <CURSOR> Print the rows after this cursor + -h, --help Print help (see more with '--help') +"#, + ), + )) + .await; +} + +fn ids(range: RangeInclusive<u32>) -> Vec<String> { + range.map(|id| id.to_string()).collect() +} + +fn seed_partitions(client: &dyn Client) -> BoxFuture<'_, ()> { + Box::pin(create_topic(client, PARTITIONS)) +} + +/// One request creates at most [`MAX_PARTITIONS_COUNT`] partitions, so the +/// last one comes in a second request. +fn seed_more_partitions_than_one_page(client: &dyn Client) -> BoxFuture<'_, ()> { + Box::pin(async move { + create_topic(client, MAX_PARTITIONS_COUNT).await; + client + .create_partitions( + &Identifier::named(PAGES_STREAM).expect("a stream name"), + &Identifier::named(PAGES_TOPIC).expect("a topic name"), + MAX_PAGE_LIMIT + 1 - MAX_PARTITIONS_COUNT, + ) + .await + .expect("create partitions"); + }) +} + +async fn create_topic(client: &dyn Client, partitions_count: u32) { + client + .create_stream(PAGES_STREAM, &StreamCreateOptions::default()) + .await + .expect("create stream"); + client + .create_topic( + &Identifier::named(PAGES_STREAM).expect("a stream name"), + PAGES_TOPIC, + &TopicCreateOptions { + partitions_count: Some(partitions_count), + message_expiry: Some(IggyExpiry::NeverExpire), + ..TopicCreateOptions::default() + }, + ) + .await + .expect("create topic"); +}
diff --git a/core/integration/tests/cli/stream/test_stream_list_command.rs b/core/integration/tests/cli/stream/test_stream_list_command.rs index 84ddabf..3efb545 100644 --- a/core/integration/tests/cli/stream/test_stream_list_command.rs +++ b/core/integration/tests/cli/stream/test_stream_list_command.rs
@@ -15,17 +15,22 @@ // specific language governing permissions and limitations // under the License. +use crate::cli::common::list_runs::{ListRun, execute_list_runs}; use crate::cli::common::{ CLAP_INDENT, IggyCmdCommand, IggyCmdTest, IggyCmdTestCase, OutputFormat, TestHelpCmd, USAGE_PREFIX, }; use assert_cmd::assert::Assert; use async_trait::async_trait; +use futures::future::BoxFuture; use iggy::prelude::Client; -use iggy::prelude::StreamCreateOptions; +use iggy::prelude::{Identifier, StreamCreateOptions}; use predicates::str::{contains, starts_with}; use serial_test::parallel; +/// The field of the stream name in a list mode row. +const NAME_COLUMN: usize = 2; + struct TestStreamListCmd { name: String, output: OutputFormat, @@ -103,6 +108,80 @@ #[tokio::test] #[parallel] +pub async fn should_print_pages() { + execute_list_runs( + seed_streams, + NAME_COLUMN, + vec![ + ListRun::new( + "stream list -l list", + &["pages-s1", "pages-s4", "pages-s3"], + false, + ), + ListRun::new( + "stream list -l list --sort created", + &["pages-s1", "pages-s3", "pages-s4"], + false, + ), + ListRun::new( + "stream list -l list --sort created --desc --limit 2", + &["pages-s4", "pages-s3"], + true, + ), + ListRun::new( + "stream list -l list --sort created --desc --limit 2 --after {next}", + &["pages-s1"], + false, + ), + ListRun::new( + "stream list -l list --limit 3", + &["pages-s1", "pages-s4", "pages-s3"], + false, + ), + ListRun::new("stream list -l list --name s3", &["pages-s3"], false), + ListRun::new( + "stream list -o json --sort created --desc --limit 2", + &["pages-s4", "pages-s3"], + true, + ), + ListRun::new( + "stream list -o json --sort created --desc --limit 2 --after {next}", + &["pages-s1"], + false, + ), + ListRun::new( + "stream list -o json --sort created", + &["pages-s1", "pages-s3", "pages-s4"], + false, + ), + ], + ) + .await; +} + +/// Stream `pages-s4` takes the ID of the deleted `pages-s2`, so the ID order +/// is s1 s4 s3 and the creation order is s1 s3 s4. +fn seed_streams(client: &dyn Client) -> BoxFuture<'_, ()> { + Box::pin(async move { + for name in ["pages-s1", "pages-s2", "pages-s3"] { + client + .create_stream(name, &StreamCreateOptions::default()) + .await + .expect("create stream"); + } + client + .delete_stream(&Identifier::named("pages-s2").expect("a stream name")) + .await + .expect("delete stream"); + client + .create_stream("pages-s4", &StreamCreateOptions::default()) + .await + .expect("create stream"); + }) +} + +#[tokio::test] +#[parallel] pub async fn should_help_match() { let mut iggy_cmd_test = IggyCmdTest::help_message(); @@ -116,6 +195,8 @@ iggy stream list iggy stream list --list-mode table iggy stream list -l table + iggy stream list --sort created --desc --limit 20 + iggy stream list --name prod --limit 50 --after pg1_AQcAAAAAAAAA {USAGE_PREFIX} stream list [OPTIONS] @@ -131,6 +212,28 @@ {CLAP_INDENT} [possible values: table, list, json] + --sort <SORT> + Order of the rows, by ID or by creation time +{CLAP_INDENT} + [default: id] + [possible values: id, created] + + --desc + Print the rows in descending order + + --limit <N> + Print at most N rows +{CLAP_INDENT} + If more rows follow them, the last line is `next: <CURSOR>`. Pass that cursor to --after to print the rows that follow. + + --after <CURSOR> + Print the rows after this cursor +{CLAP_INDENT} + The cursor comes from the `next:` line of a list with --limit. Use the same other flags as that list. + + --name <TEXT> + Print only the rows whose name holds this text (case-sensitive) + -h, --help Print help (see a summary with '-h') "#, @@ -155,6 +258,11 @@ Options: -l, --list-mode <LIST_MODE> List mode (table or list) [default: table] [possible values: table, list] -o, --output <OUTPUT> Output format (table, list or json), cannot be combined with --list-mode [possible values: table, list, json] + --sort <SORT> Order of the rows, by ID or by creation time [default: id] [possible values: id, created] + --desc Print the rows in descending order + --limit <N> Print at most N rows + --after <CURSOR> Print the rows after this cursor + --name <TEXT> Print only the rows whose name holds this text (case-sensitive) -h, --help Print help (see more with '--help') "#, ),
diff --git a/core/integration/tests/cli/topic/test_topic_list_command.rs b/core/integration/tests/cli/topic/test_topic_list_command.rs index f6e44b4..e6f2cc2 100644 --- a/core/integration/tests/cli/topic/test_topic_list_command.rs +++ b/core/integration/tests/cli/topic/test_topic_list_command.rs
@@ -15,19 +15,26 @@ // specific language governing permissions and limitations // under the License. +use crate::cli::common::list_runs::{ListRun, execute_list_runs}; use crate::cli::common::{ CLAP_INDENT, IggyCmdCommand, IggyCmdTest, IggyCmdTestCase, OutputFormat, TestHelpCmd, TestStreamId, USAGE_PREFIX, }; use assert_cmd::assert::Assert; use async_trait::async_trait; +use futures::future::BoxFuture; use iggy::prelude::Client; +use iggy::prelude::Identifier; use iggy::prelude::IggyExpiry; use iggy::prelude::StreamCreateOptions; use iggy::prelude::TopicCreateOptions; use predicates::str::{contains, starts_with}; use serial_test::parallel; +const PAGES_STREAM: &str = "pages"; +/// The field of the topic name in a list mode row. +const NAME_COLUMN: usize = 2; + struct TestTopicListCmd { stream_id: u32, stream_name: String, @@ -163,6 +170,81 @@ #[tokio::test] #[parallel] +pub async fn should_print_pages() { + execute_list_runs( + seed_topics, + NAME_COLUMN, + vec![ + ListRun::new( + "topic list pages -l list", + &["pages-t1", "pages-t4", "pages-t3"], + false, + ), + ListRun::new( + "topic list pages -l list --sort created --desc --limit 1", + &["pages-t4"], + true, + ), + ListRun::new( + "topic list pages -l list --sort created --desc --after {next}", + &["pages-t3", "pages-t1"], + false, + ), + ListRun::new("topic list pages -l list --name t1", &["pages-t1"], false), + ListRun::new( + "topic list pages -o json --sort created --desc --limit 1", + &["pages-t4"], + true, + ), + ListRun::new( + "topic list pages -o json --sort created --desc --after {next}", + &["pages-t3", "pages-t1"], + false, + ), + ], + ) + .await; +} + +/// Topic `pages-t4` takes the ID of the deleted `pages-t2`, so the ID order +/// is t1 t4 t3 and the creation order is t1 t3 t4. +fn seed_topics(client: &dyn Client) -> BoxFuture<'_, ()> { + Box::pin(async move { + let stream_id = &Identifier::named(PAGES_STREAM).expect("a stream name"); + client + .create_stream(PAGES_STREAM, &StreamCreateOptions::default()) + .await + .expect("create stream"); + let create_topic = |name| async move { + client + .create_topic( + stream_id, + name, + &TopicCreateOptions { + partitions_count: Some(1), + message_expiry: Some(IggyExpiry::NeverExpire), + ..TopicCreateOptions::default() + }, + ) + .await + .expect("create topic"); + }; + for name in ["pages-t1", "pages-t2", "pages-t3"] { + create_topic(name).await; + } + client + .delete_topic( + stream_id, + &Identifier::named("pages-t2").expect("a topic name"), + ) + .await + .expect("delete topic"); + create_topic("pages-t4").await; + }) +} + +#[tokio::test] +#[parallel] pub async fn should_help_match() { let mut iggy_cmd_test = IggyCmdTest::help_message(); @@ -177,6 +259,8 @@ Examples iggy topic list 1 iggy topic list prod + iggy topic list prod --sort created --desc --limit 20 + iggy topic list prod --name sensor --limit 50 {USAGE_PREFIX} topic list [OPTIONS] <STREAM_ID> @@ -198,6 +282,28 @@ {CLAP_INDENT} [possible values: table, list, json] + --sort <SORT> + Order of the rows, by ID or by creation time +{CLAP_INDENT} + [default: id] + [possible values: id, created] + + --desc + Print the rows in descending order + + --limit <N> + Print at most N rows +{CLAP_INDENT} + If more rows follow them, the last line is `next: <CURSOR>`. Pass that cursor to --after to print the rows that follow. + + --after <CURSOR> + Print the rows after this cursor +{CLAP_INDENT} + The cursor comes from the `next:` line of a list with --limit. Use the same other flags as that list. + + --name <TEXT> + Print only the rows whose name holds this text (case-sensitive) + -h, --help Print help (see a summary with '-h') "#, @@ -225,6 +331,11 @@ Options: -l, --list-mode <LIST_MODE> List mode (table or list) [default: table] [possible values: table, list] -o, --output <OUTPUT> Output format (table, list or json), cannot be combined with --list-mode [possible values: table, list, json] + --sort <SORT> Order of the rows, by ID or by creation time [default: id] [possible values: id, created] + --desc Print the rows in descending order + --limit <N> Print at most N rows + --after <CURSOR> Print the rows after this cursor + --name <TEXT> Print only the rows whose name holds this text (case-sensitive) -h, --help Print help (see more with '--help') "#, ),
diff --git a/core/integration/tests/cli/user/test_user_list_command.rs b/core/integration/tests/cli/user/test_user_list_command.rs index fbf8360..2fa14ed 100644 --- a/core/integration/tests/cli/user/test_user_list_command.rs +++ b/core/integration/tests/cli/user/test_user_list_command.rs
@@ -15,18 +15,24 @@ // specific language governing permissions and limitations // under the License. +use crate::cli::common::list_runs::{ListRun, execute_list_runs}; use crate::cli::common::{ CLAP_INDENT, IggyCmdCommand, IggyCmdTest, IggyCmdTestCase, OutputFormat, TestHelpCmd, USAGE_PREFIX, }; use assert_cmd::assert::Assert; use async_trait::async_trait; +use futures::future::BoxFuture; use iggy::prelude::Client; use iggy::prelude::UserCreateOptions; use iggy::prelude::UserStatus; +use iggy::prelude::{DEFAULT_ROOT_USERNAME, Identifier}; use predicates::str::{contains, starts_with}; use serial_test::parallel; +/// The field of the username in a list mode row. +const NAME_COLUMN: usize = 3; + struct TestUserListCmd { username: String, status: UserStatus, @@ -115,6 +121,65 @@ #[tokio::test] #[parallel] +pub async fn should_print_pages() { + execute_list_runs( + seed_users, + NAME_COLUMN, + vec![ + ListRun::new( + "user list -l list", + &[DEFAULT_ROOT_USERNAME, "pages-u1", "pages-u4", "pages-u3"], + false, + ), + ListRun::new( + "user list -l list --sort created --limit 2", + &[DEFAULT_ROOT_USERNAME, "pages-u1"], + true, + ), + ListRun::new( + "user list -l list --sort created --after {next}", + &["pages-u3", "pages-u4"], + false, + ), + ListRun::new( + "user list -l list --name pages-u --desc", + &["pages-u3", "pages-u4", "pages-u1"], + false, + ), + ], + ) + .await; +} + +/// User `pages-u4` takes the ID of the deleted `pages-u2`, so the ID order is +/// u1 u4 u3 and the creation order is u1 u3 u4, both after the root user. +fn seed_users(client: &dyn Client) -> BoxFuture<'_, ()> { + Box::pin(async move { + let create_user = |name| async move { + client + .create_user( + name, + "secret", + UserStatus::Active, + None, + &UserCreateOptions::default(), + ) + .await + .expect("create user"); + }; + for name in ["pages-u1", "pages-u2", "pages-u3"] { + create_user(name).await; + } + client + .delete_user(&Identifier::named("pages-u2").expect("a username")) + .await + .expect("delete user"); + create_user("pages-u4").await; + }) +} + +#[tokio::test] +#[parallel] pub async fn should_help_match() { let mut iggy_cmd_test = IggyCmdTest::help_message(); @@ -128,6 +193,7 @@ iggy user list iggy user list --list-mode table iggy user list -l table + iggy user list --sort created --desc --limit 20 {USAGE_PREFIX} user list [OPTIONS] @@ -138,6 +204,28 @@ [default: table] [possible values: table, list] + --sort <SORT> + Order of the rows, by ID or by creation time +{CLAP_INDENT} + [default: id] + [possible values: id, created] + + --desc + Print the rows in descending order + + --limit <N> + Print at most N rows +{CLAP_INDENT} + If more rows follow them, the last line is `next: <CURSOR>`. Pass that cursor to --after to print the rows that follow. + + --after <CURSOR> + Print the rows after this cursor +{CLAP_INDENT} + The cursor comes from the `next:` line of a list with --limit. Use the same other flags as that list. + + --name <TEXT> + Print only the rows whose name holds this text (case-sensitive) + -h, --help Print help (see a summary with '-h') "#, @@ -161,6 +249,11 @@ Options: -l, --list-mode <LIST_MODE> List mode (table or list) [default: table] [possible values: table, list] + --sort <SORT> Order of the rows, by ID or by creation time [default: id] [possible values: id, created] + --desc Print the rows in descending order + --limit <N> Print at most N rows + --after <CURSOR> Print the rows after this cursor + --name <TEXT> Print only the rows whose name holds this text (case-sensitive) -h, --help Print help (see more with '--help') "#, ),
diff --git a/core/integration/tests/cluster/replica_raw_request.rs b/core/integration/tests/cluster/replica_raw_request.rs index 5ba9614..1621b82 100644 --- a/core/integration/tests/cluster/replica_raw_request.rs +++ b/core/integration/tests/cluster/replica_raw_request.rs
@@ -17,9 +17,11 @@ use bytes::Bytes; use iggy::prelude::*; -use iggy_binary_protocol::WireDecode; use iggy_binary_protocol::codes::{CREATE_STREAM_CODE, GET_STATS_CODE, GET_STREAMS_CODE}; +use iggy_binary_protocol::primitives::page::WirePageQuery; +use iggy_binary_protocol::requests::streams::GetStreamsRequest; use iggy_binary_protocol::responses::system::get_stats::StatsResponse; +use iggy_binary_protocol::{WireDecode, WireEncode}; use integration::iggy_harness; use std::collections::BTreeSet; @@ -83,9 +85,13 @@ .map(|node| node.replica_id) .collect(); + let first_page = GetStreamsRequest { + page: WirePageQuery::default(), + } + .to_bytes(); for replica in replicas { let reply = client - .send_binary_request_to_replica(GET_STREAMS_CODE, Bytes::new(), replica) + .send_binary_request_to_replica(GET_STREAMS_CODE, first_page.clone(), replica) .await .unwrap_or_else(|error| panic!("streams of replica {replica}: {error}")); assert!( @@ -119,4 +125,11 @@ .await, Err(IggyError::InvalidCommand) ); + assert_eq!( + client + .send_binary_request_to_replica(GET_STREAMS_CODE, Bytes::new(), 1) + .await, + Err(IggyError::InvalidCommand), + "a list read without its page block" + ); }
diff --git a/core/integration/tests/mcp/mod.rs b/core/integration/tests/mcp/mod.rs index c1b459f..09e13d2 100644 --- a/core/integration/tests/mcp/mod.rs +++ b/core/integration/tests/mcp/mod.rs
@@ -22,7 +22,7 @@ use iggy_common::{ ClientInfo, ClientInfoDetails, ClusterMetadata, ConsumerGroup, ConsumerGroupDetails, - ConsumerOffsetInfo, IggyMessage, MessageClient, Partitioning, Permissions, + ConsumerOffsetInfo, IggyMessage, MessageClient, Page, Partition, Partitioning, Permissions, PersonalAccessTokenClient, PersonalAccessTokenExpiry, PersonalAccessTokenInfo, PolledMessages, RawPersonalAccessToken, Snapshot, Stats, Stream, StreamDetails, Topic, TopicDetails, UserClient, UserCreateOptions, UserInfo, UserInfoDetails, UserStatus, @@ -180,7 +180,7 @@ .expect("Failed to list tools"); assert!(!tools.tools.is_empty()); - assert_eq!(tools.tools.len(), 41); + assert_eq!(tools.tools.len(), 42); } #[iggy_harness(server(mcp))] @@ -229,6 +229,144 @@ assert_eq!(streams[0].topics_count, 1); } +#[iggy_harness(server(mcp))] +async fn should_return_pages_of_streams(harness: &TestHarness) { + let mcp_client = harness.mcp_client().await.expect("MCP client required"); + for name in ["pages-1", "pages-2", "pages-3"] { + let _: StreamDetails = + invoke(&mcp_client, "create_stream", Some(json!({"name": name}))).await; + } + invoke_empty( + &mcp_client, + "delete_stream", + Some(json!({"stream_id": "pages-2"})), + ) + .await; + // The new stream takes the freed id, so the id order and the creation + // order differ. + let _: StreamDetails = invoke( + &mcp_client, + "create_stream", + Some(json!({"name": "pages-4"})), + ) + .await; + let names = |streams: &[Stream]| -> Vec<String> { + streams.iter().map(|stream| stream.name.clone()).collect() + }; + + let first: Page<Stream> = invoke(&mcp_client, "get_streams", Some(json!({"limit": 2}))).await; + assert_eq!(names(&first.items), ["pages-1", "pages-4"]); + let next = first.next.expect("a next cursor").to_string(); + let last: Page<Stream> = invoke( + &mcp_client, + "get_streams", + Some(json!({"limit": 2, "cursor": next})), + ) + .await; + assert_eq!( + (names(&last.items), last.next), + (vec!["pages-3".to_owned()], None) + ); + + let newest: Page<Stream> = invoke( + &mcp_client, + "get_streams", + Some(json!({"order": "created", "descending": true, "limit": 1})), + ) + .await; + assert_eq!(names(&newest.items), ["pages-4"]); + + let whole: Vec<Stream> = invoke(&mcp_client, "get_streams", None).await; + assert_eq!( + names(&whole), + ["pages-1", "pages-4", "pages-3"], + "without limit and cursor, the whole list in id order" + ); + let newest_first: Vec<Stream> = invoke( + &mcp_client, + "get_streams", + Some(json!({"order": "created", "descending": true})), + ) + .await; + assert_eq!( + names(&newest_first), + ["pages-4", "pages-3", "pages-1"], + "without limit and cursor, the whole list in the asked order" + ); + let named: Vec<Stream> = + invoke(&mcp_client, "get_streams", Some(json!({"name": "pages-3"}))).await; + assert_eq!( + names(&named), + ["pages-3"], + "without limit and cursor, the whole list with the asked filter" + ); + + for (arguments, error) in [ + (json!({"cursor": "pg1_"}), "Failed to parse cursor"), + (json!({"order": "name"}), "Failed to parse order"), + (json!({"limit": 0}), "Invalid command"), + ] { + let params = CallToolRequestParams::new("get_streams".to_owned()) + .with_arguments(arguments.as_object().expect("Tool arguments").clone()); + let result = mcp_client.call_tool(params).await; + assert!( + matches!(&result, Err(ServiceError::McpError(refusal)) if refusal.message.contains(error)), + "{arguments}: {result:?}" + ); + } +} + +#[iggy_harness(server(mcp))] +async fn should_return_pages_of_partitions(harness: &TestHarness) { + let mcp_client = harness.mcp_client().await.expect("MCP client required"); + let _: StreamDetails = + invoke(&mcp_client, "create_stream", Some(json!({"name": "pages"}))).await; + let _: TopicDetails = invoke( + &mcp_client, + "create_topic", + Some(json!({"stream_id": "pages", "name": "events", "partitions_count": 3})), + ) + .await; + let topic = json!({"stream_id": "pages", "topic_id": "events"}); + let read = |extra: serde_json::Value| { + let mut arguments = topic.clone(); + arguments + .as_object_mut() + .expect("Tool arguments") + .extend(extra.as_object().expect("Page arguments").clone()); + arguments + }; + let ids = |page: &Page<Partition>| -> Vec<u32> { + page.items.iter().map(|partition| partition.id).collect() + }; + + let first: Page<Partition> = invoke( + &mcp_client, + "get_partitions", + Some(read(json!({"limit": 2}))), + ) + .await; + assert_eq!(ids(&first), [0, 1]); + let next = first.next.expect("a next cursor").to_string(); + let last: Page<Partition> = invoke( + &mcp_client, + "get_partitions", + Some(read(json!({"limit": 2, "cursor": next}))), + ) + .await; + assert_eq!((ids(&last), last.next), (vec![2], None)); + + let default: Page<Partition> = invoke(&mcp_client, "get_partitions", Some(topic.clone())).await; + assert_eq!((ids(&default), default.next), (vec![0, 1, 2], None)); + let descending: Page<Partition> = invoke( + &mcp_client, + "get_partitions", + Some(read(json!({"descending": true}))), + ) + .await; + assert_eq!(ids(&descending), [2, 1, 0]); +} + #[iggy_harness(server(mcp), seed = seeds::mcp_standard)] async fn should_return_stream_details(harness: &TestHarness) { let mcp_client = harness.mcp_client().await.expect("MCP client required"); @@ -292,6 +430,51 @@ assert_eq!(topics[0].name, seeds::names::TOPIC); assert_eq!(topics[0].partitions_count, 1); assert_eq!(topics[0].messages_count, 1); + + for name in ["topic-1", "topic-2"] { + let _: TopicDetails = invoke( + &mcp_client, + "create_topic", + Some(json!({"stream_id": seeds::names::STREAM, "name": name, "partitions_count": 1})), + ) + .await; + } + invoke_empty( + &mcp_client, + "delete_topic", + Some(json!({"stream_id": seeds::names::STREAM, "topic_id": "topic-1"})), + ) + .await; + // The new topic takes the freed id, so the id order and the creation + // order differ. + let _: TopicDetails = invoke( + &mcp_client, + "create_topic", + Some(json!({"stream_id": seeds::names::STREAM, "name": "topic-3", "partitions_count": 1})), + ) + .await; + let names = |topics: &[Topic]| -> Vec<String> { + topics.iter().map(|topic| topic.name.clone()).collect() + }; + let by_created: Vec<Topic> = invoke( + &mcp_client, + "get_topics", + Some(json!({"stream_id": seeds::names::STREAM, "order": "created"})), + ) + .await; + assert_eq!( + names(&by_created), + [seeds::names::TOPIC, "topic-2", "topic-3"], + "without limit and cursor, the whole list in the asked order" + ); + let page: Page<Topic> = invoke( + &mcp_client, + "get_topics", + Some(json!({"stream_id": seeds::names::STREAM, "order": "created", "limit": 2})), + ) + .await; + assert_eq!(names(&page.items), [seeds::names::TOPIC, "topic-2"]); + assert!(page.next.is_some(), "one more topic follows the page"); } #[iggy_harness(server(mcp), seed = seeds::mcp_standard)] @@ -547,6 +730,21 @@ .await; assert!(!groups.is_empty()); + + let page: Page<ConsumerGroup> = invoke( + &mcp_client, + "get_consumer_groups", + Some(json!({ + "stream_id": seeds::names::STREAM, + "topic_id": seeds::names::TOPIC, + "name": seeds::names::CONSUMER_GROUP, + "limit": 10, + })), + ) + .await; + let names: Vec<&str> = page.items.iter().map(|group| group.name.as_str()).collect(); + assert_eq!(names, [seeds::names::CONSUMER_GROUP]); + assert_eq!(page.next, None); } #[iggy_harness(server(mcp), seed = seeds::mcp_standard)] @@ -731,6 +929,18 @@ let users: Vec<UserInfo> = invoke(&mcp_client, "get_users", None).await; assert_eq!(users.len(), 2); + + let ids = |users: &[UserInfo]| -> Vec<u32> { users.iter().map(|user| user.id).collect() }; + let first: Page<UserInfo> = invoke(&mcp_client, "get_users", Some(json!({"limit": 1}))).await; + assert_eq!(ids(&first.items), ids(&users[..1])); + let next = first.next.expect("a next cursor").to_string(); + let last: Page<UserInfo> = invoke( + &mcp_client, + "get_users", + Some(json!({"limit": 1, "cursor": next})), + ) + .await; + assert_eq!((ids(&last.items), last.next), (ids(&users[1..]), None)); } #[tokio::test] @@ -1045,6 +1255,7 @@ json!({"name": seeds::names::PERSONAL_ACCESS_TOKEN}), ), ("get_users", json!({})), + ("get_users", json!({"limit": 1})), ("get_user", json!({"user_id": seeds::names::USER})), ( "create_user",
diff --git a/core/integration/tests/server/general.rs b/core/integration/tests/server/general.rs index 344e8d9..a5ed2b9 100644 --- a/core/integration/tests/server/general.rs +++ b/core/integration/tests/server/general.rs
@@ -17,8 +17,9 @@ use crate::server::scenarios::{ authentication_scenario, consumer_timestamp_polling_scenario, delete_stats_rollback_scenario, - invalid_consumer_offset_scenario, message_headers_scenario, permissions_scenario, - snapshot_scenario, stream_size_validation_scenario, system_scenario, user_scenario, + invalid_consumer_offset_scenario, list_pages_scenario, message_headers_scenario, + permissions_scenario, snapshot_scenario, stream_size_validation_scenario, system_scenario, + user_scenario, }; use integration::iggy_harness; @@ -59,6 +60,17 @@ user_scenario::run(harness).await; } +#[iggy_harness( + test_client_transport = [Tcp, Http, Quic, WebSocket], + server( + quic.max_idle_timeout = "500s", + quic.keep_alive_interval = "15s" + ) +)] +async fn list_pages(harness: &TestHarness) { + list_pages_scenario::run(harness).await; +} + // Same HTTP relay requirement as `system`. #[iggy_harness( test_client_transport = [Tcp, Http, Quic, WebSocket],
diff --git a/core/integration/tests/server/http_list_pages.rs b/core/integration/tests/server/http_list_pages.rs new file mode 100644 index 0000000..36eed5a --- /dev/null +++ b/core/integration/tests/server/http_list_pages.rs
@@ -0,0 +1,224 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The query of the HTTP list routes: page keys, the JSON page and the strict +//! parser. The SDK only sends well-formed keys, so these requests are raw. + +use crate::server::http_client::HttpClient; +use futures::future::{join_all, try_join_all}; +use iggy::prelude::*; +use integration::harness::TestHarness; +use integration::iggy_harness; +use reqwest::{Response, StatusCode}; +use serde_json::Value; + +const STREAM: &str = "http-pages"; +const TOPIC: &str = "events"; +const PARTITIONS: u32 = 4; +const PARTITIONS_PATH: &str = "/streams/http-pages/topics/events/partitions"; +/// The routes that answer the bare array of the legacy server without `limit` +/// and `cursor`. +const LIST_PATHS: [&str; 4] = [ + "/streams", + "/streams/http-pages/topics", + "/streams/http-pages/topics/events/consumer-groups", + "/users", +]; +/// Clients that create the streams of the long list at the same time. One +/// client alone waits about 100 ms for each create. +const CREATORS: usize = 8; + +#[iggy_harness] +async fn given_the_partitions_route_when_reading_should_serve_pages_and_refuse_bad_keys( + harness: &TestHarness, +) { + seed(harness).await; + let http = HttpClient::login_root(harness).await; + + let page = json_of(http.get(PARTITIONS_PATH).await).await; + assert_eq!(ids(&page), [0, 1, 2, 3], "no page key reads the first page"); + assert_eq!(page.get("next"), None); + + let first = json_of( + http.get(&format!( + "{PARTITIONS_PATH}?limit=3&consistency=serializable" + )) + .await, + ) + .await; + assert_eq!(ids(&first), [0, 1, 2]); + let next = first["next"].as_str().expect("a next cursor"); + assert!(next.starts_with(PAGE_CURSOR_PREFIX), "{next}"); + let last = json_of( + http.get(&format!("{PARTITIONS_PATH}?limit=3&cursor={next}")) + .await, + ) + .await; + assert_eq!(ids(&last), [3]); + assert_eq!(last.get("next"), None); + + let newest = json_of( + http.get(&format!( + "{PARTITIONS_PATH}?descending=true&limit=2&consistency=linearizable" + )) + .await, + ) + .await; + assert_eq!(ids(&newest), [3, 2]); + + for query in [ + "offset=3", + "limit=3&limit=3", + "limit=0", + "limit=1001", + "limit=03", + "order=name", + "descending=1", + "cursor=pg1_", + "cursor=mc1_AQcAAAAAAAAA", + "name=p", + "consistency=strong", + "consistency=serializable&consistency=serializable", + ] { + let response = http.get(&format!("{PARTITIONS_PATH}?{query}")).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "?{query}"); + } +} + +#[iggy_harness] +async fn given_the_list_routes_when_reading_should_answer_the_bare_array_or_one_page( + harness: &TestHarness, +) { + seed(harness).await; + let http = HttpClient::login_root(harness).await; + for path in LIST_PATHS { + let page = json_of(http.get(&format!("{path}?limit={MAX_PAGE_LIMIT}")).await).await; + assert_eq!(page.get("next"), None, "{path}: one page holds the list"); + let items = page["items"].as_array().expect("an items array"); + assert_ne!(items.len(), 0, "{path}: the seed fills each list"); + for query in ["", "?consistency=serializable"] { + let bare = json_of(http.get(&format!("{path}{query}")).await).await; + assert_eq!( + bare.as_array(), + Some(items), + "{path}{query}: without limit and cursor, the bare array of the page items" + ); + } + let newest_first: Vec<Value> = items.iter().rev().cloned().collect(); + let descending = json_of(http.get(&format!("{path}?descending=true")).await).await; + assert_eq!( + descending.as_array(), + Some(&newest_first), + "{path}: without limit and cursor, the whole list in the asked order" + ); + let filtered = json_of(http.get(&format!("{path}?name=no-such-name")).await).await; + assert_eq!( + filtered.as_array(), + Some(&Vec::new()), + "{path}: without limit and cursor, the whole list with the asked filter" + ); + for query in ["offset=3", "limit=0", "consistency=strong", "name="] { + let response = http.get(&format!("{path}?{query}")).await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{path}?{query}"); + } + } +} + +#[iggy_harness] +async fn given_more_streams_than_one_page_when_listing_should_return_every_stream( + harness: &TestHarness, +) { + let names: Vec<String> = (0..=MAX_PAGE_LIMIT) + .map(|index| format!("many-{index:04}")) + .collect(); + let creators = try_join_all((0..CREATORS).map(|_| harness.tcp_root_client())) + .await + .expect("tcp root clients"); + let chunks = names.chunks(names.len().div_ceil(CREATORS)); + join_all( + creators + .iter() + .zip(chunks) + .map(|(client, chunk)| async move { + for name in chunk { + client + .create_stream(name, &StreamCreateOptions::default()) + .await + .expect("create stream"); + } + }), + ) + .await; + + let listed = creators[0].get_streams().await.expect("get streams"); + let mut listed: Vec<&str> = listed.iter().map(|stream| stream.name.as_str()).collect(); + listed.sort_unstable(); + assert_eq!(listed, names, "the list reads past its first page"); + + let http = HttpClient::login_root(harness).await; + let reply = json_of(http.get("/streams").await).await; + let mut bare: Vec<&str> = reply + .as_array() + .expect("the bare array") + .iter() + .map(|stream| stream["name"].as_str().expect("a stream name")) + .collect(); + bare.sort_unstable(); + assert_eq!(bare, names, "the bare array holds every page"); +} + +/// Stream `http-pages` with topic `events` of [`PARTITIONS`] partitions and +/// one consumer group, created over TCP. +async fn seed(harness: &TestHarness) { + let client = harness.tcp_root_client().await.expect("tcp root client"); + let stream_id = Identifier::named(STREAM).unwrap(); + let topic_id = Identifier::named(TOPIC).unwrap(); + client + .create_stream(STREAM, &StreamCreateOptions::default()) + .await + .expect("create stream"); + client + .create_topic( + &stream_id, + TOPIC, + &TopicCreateOptions { + partitions_count: Some(PARTITIONS), + message_expiry: Some(IggyExpiry::NeverExpire), + ..TopicCreateOptions::default() + }, + ) + .await + .expect("create topic"); + client + .create_consumer_group(&stream_id, &topic_id, "workers") + .await + .expect("create consumer group"); +} + +async fn json_of(response: Response) -> Value { + assert_eq!(response.status(), StatusCode::OK); + response.json().await.expect("a JSON reply") +} + +fn ids(page: &Value) -> Vec<u64> { + page["items"] + .as_array() + .expect("an items array") + .iter() + .map(|item| item["id"].as_u64().expect("an item id")) + .collect() +}
diff --git a/core/integration/tests/server/mod.rs b/core/integration/tests/server/mod.rs index cc49e0d..147b38a 100644 --- a/core/integration/tests/server/mod.rs +++ b/core/integration/tests/server/mod.rs
@@ -50,6 +50,8 @@ pub(crate) mod http_client; // Raw-HTTP data-plane contract against the server's shard-0 listener. mod http_vsr; +// Raw-HTTP page keys of the list routes. +mod http_list_pages; // Raw-HTTP wire-contract residue against the server (status codes + typed error // bodies); the RBAC matrix lives in permissions_scenario. mod http_rbac;
diff --git a/core/integration/tests/server/scenarios/authentication_scenario.rs b/core/integration/tests/server/scenarios/authentication_scenario.rs index 1e3747a..f1fdefb 100644 --- a/core/integration/tests/server/scenarios/authentication_scenario.rs +++ b/core/integration/tests/server/scenarios/authentication_scenario.rs
@@ -290,6 +290,10 @@ .delete_partitions(&ctx.stream_id, &ctx.topic_id, 1) .await } + GET_PARTITIONS_CODE => client + .get_partitions_page(&ctx.stream_id, &ctx.topic_id, &PageQuery::default()) + .await + .map(|_| ()), // Messages GET_PARTITION_ROUTE_CODE => client
diff --git a/core/integration/tests/server/scenarios/list_pages_scenario.rs b/core/integration/tests/server/scenarios/list_pages_scenario.rs new file mode 100644 index 0000000..1c6e445 --- /dev/null +++ b/core/integration/tests/server/scenarios/list_pages_scenario.rs
@@ -0,0 +1,546 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Pages of the list commands, read through the SDK on every transport. + +use crate::server::scenarios::create_client; +use crate::server::scenarios::permissions_scenario::assert_error_code; +use iggy::prelude::*; +use integration::harness::{TestHarness, login_root}; +use std::cell::Cell; + +const STREAM: &str = "pages-stream"; +const TOPIC: &str = "pages-topic"; +const PARTITIONS: u32 = 10; +const PAGE_LIMIT: u32 = 3; +const READER: &str = "pages-reader"; +const PASSWORD: &str = "password123"; + +pub async fn run(harness: &TestHarness) { + let root = create_client(harness).await; + login_root(&root).await.expect("login root"); + let stream_id = Identifier::named(STREAM).unwrap(); + let topic_id = Identifier::named(TOPIC).unwrap(); + root.create_stream(STREAM, &StreamCreateOptions::default()) + .await + .expect("create stream"); + create_topic(&root, &stream_id, TOPIC, PARTITIONS).await; + + assert_partition_pages(&root, &stream_id, &topic_id).await; + assert_stream_pages(&root).await; + assert_topic_pages(&root, &stream_id).await; + assert_consumer_group_pages(&root, &stream_id, &topic_id).await; + assert_user_pages(&root).await; + assert_walks_across_deletes(&root).await; + assert_page_refusals(harness, &root, &stream_id, &topic_id).await; + + root.delete_stream(&stream_id).await.expect("delete stream"); +} + +async fn assert_partition_pages( + client: &IggyClient, + stream_id: &Identifier, + topic_id: &Identifier, +) { + let all: Vec<u32> = (0..PARTITIONS).collect(); + let ascending = PageQuery { + limit: PAGE_LIMIT, + ..PageQuery::default() + }; + assert_eq!( + walk_partitions(client, stream_id, topic_id, ascending.clone()).await, + (all.clone(), 4), + "pages of 3, 3, 3 and 1, and only the last one without next" + ); + let descending = PageQuery { + descending: true, + ..ascending.clone() + }; + assert_eq!( + walk_partitions(client, stream_id, topic_id, descending).await, + (all.iter().rev().copied().collect(), 4) + ); + let created = PageQuery { + order: PageOrder::Created, + ..ascending + }; + assert_eq!( + walk_partitions(client, stream_id, topic_id, created) + .await + .0, + all, + "partition ids follow creation" + ); + + let details = client + .get_topic(stream_id, topic_id) + .await + .expect("get topic") + .expect("the topic exists"); + let whole = PageQuery { + limit: PARTITIONS, + ..PageQuery::default() + }; + let page = client + .get_partitions_page(stream_id, topic_id, &whole) + .await + .expect("one page of every partition"); + assert_eq!(page.next, None); + let shape = |partitions: &[Partition]| { + partitions + .iter() + .map(|partition| { + ( + partition.id, + partition.created_at, + partition.members.clone(), + ) + }) + .collect::<Vec<_>>() + }; + assert_eq!( + shape(&page.items), + shape(&details.partitions), + "a page item is the partition of the topic details" + ); +} + +/// Stream `pages-s5` takes the id of the deleted `pages-s2`, so the id order +/// and the creation order differ. +async fn assert_stream_pages(client: &IggyClient) { + for name in ["pages-s1", "pages-s2", "pages-s3", "pages-s4"] { + client + .create_stream(name, &StreamCreateOptions::default()) + .await + .expect("create stream"); + } + client + .delete_stream(&Identifier::named("pages-s2").unwrap()) + .await + .expect("delete stream"); + client + .create_stream("pages-s5", &StreamCreateOptions::default()) + .await + .expect("create a stream in the freed id"); + let by_id = [STREAM, "pages-s1", "pages-s5", "pages-s3", "pages-s4"]; + let by_created = [STREAM, "pages-s1", "pages-s3", "pages-s4", "pages-s5"]; + assert_walks( + &by_id, + &by_created, + |stream: &Stream| stream.name.as_str(), + |query| async move { client.get_streams_page(&query.into()).await }, + ) + .await; + let listed = client.get_streams().await.expect("get streams"); + let names: Vec<&str> = listed.iter().map(|stream| stream.name.as_str()).collect(); + assert_eq!(names, by_id, "the list is in id order"); + + let filtered = NamedPageQuery { + name: Some("s3".to_owned()), + ..NamedPageQuery::default() + }; + let page = client + .get_streams_page(&filtered) + .await + .expect("a page of the streams with s3 in the name"); + let names: Vec<&str> = page + .items + .iter() + .map(|stream| stream.name.as_str()) + .collect(); + assert_eq!(names, ["pages-s3"]); +} + +async fn assert_topic_pages(client: &IggyClient, stream_id: &Identifier) { + for name in ["pages-t1", "pages-t2", "pages-t3"] { + create_topic(client, stream_id, name, 1).await; + } + let by_id = [TOPIC, "pages-t1", "pages-t2", "pages-t3"]; + assert_walks( + &by_id, + &by_id, + |topic: &Topic| topic.name.as_str(), + |query| async move { client.get_topics_page(stream_id, &query.into()).await }, + ) + .await; + let listed = client.get_topics(stream_id).await.expect("get topics"); + let names: Vec<&str> = listed.iter().map(|topic| topic.name.as_str()).collect(); + assert_eq!(names, by_id, "the list is in id order"); + + let missing_stream = Identifier::named("pages-missing-stream").unwrap(); + let page = client + .get_topics_page(&missing_stream, &NamedPageQuery::default()) + .await + .expect("a page of the topics of a missing stream"); + assert_eq!( + (page.items.len(), page.next), + (0, None), + "a missing stream lists as an empty last page" + ); +} + +async fn assert_consumer_group_pages( + client: &IggyClient, + stream_id: &Identifier, + topic_id: &Identifier, +) { + let groups = ["pages-g1", "pages-g2", "pages-g3", "pages-g4"]; + for name in groups { + client + .create_consumer_group(stream_id, topic_id, name) + .await + .expect("create consumer group"); + } + assert_walks( + &groups, + &groups, + |group: &ConsumerGroup| group.name.as_str(), + |query| async move { + client + .get_consumer_groups_page(stream_id, topic_id, &query.into()) + .await + }, + ) + .await; + let listed = client + .get_consumer_groups(stream_id, topic_id) + .await + .expect("get consumer groups"); + let names: Vec<&str> = listed.iter().map(|group| group.name.as_str()).collect(); + assert_eq!(names, groups, "the list is in id order"); +} + +/// User `pages-u5` takes the id of the deleted `pages-u2`. The root user is +/// the first one created. +async fn assert_user_pages(client: &IggyClient) { + for username in ["pages-u1", "pages-u2", "pages-u3", "pages-u4"] { + create_user(client, username).await; + } + client + .delete_user(&Identifier::named("pages-u2").unwrap()) + .await + .expect("delete user"); + create_user(client, "pages-u5").await; + let by_id = [ + DEFAULT_ROOT_USERNAME, + "pages-u1", + "pages-u5", + "pages-u3", + "pages-u4", + ]; + let by_created = [ + DEFAULT_ROOT_USERNAME, + "pages-u1", + "pages-u3", + "pages-u4", + "pages-u5", + ]; + assert_walks( + &by_id, + &by_created, + |user: &UserInfo| user.username.as_str(), + |query| async move { client.get_users_page(&query.into()).await }, + ) + .await; + let listed = client.get_users().await.expect("get users"); + let names: Vec<&str> = listed.iter().map(|user| user.username.as_str()).collect(); + assert_eq!(names, by_id, "the list is in id order"); +} + +/// Deletes the stream that a cursor names between two pages of a walk, then +/// the stream of a topics walk. No entity is created between the delete and +/// the next page, so no new stream can take the freed id. +async fn assert_walks_across_deletes(client: &IggyClient) { + for order in [PageOrder::Id, PageOrder::Created] { + let prefix = format!("pages-{order}-"); + let names: Vec<String> = (1..=4).map(|index| format!("{prefix}{index}")).collect(); + for name in &names { + client + .create_stream(name, &StreamCreateOptions::default()) + .await + .expect("create stream"); + } + let first = NamedPageQuery { + page: PageQuery { + order, + limit: 2, + ..PageQuery::default() + }, + name: Some(prefix), + }; + let page = client + .get_streams_page(&first) + .await + .expect("the first page"); + let mut read: Vec<String> = page + .items + .iter() + .map(|stream| stream.name.clone()) + .collect(); + assert_eq!(read, names[..2], "{order} order: the first page"); + client + .delete_stream(&Identifier::named(&names[1]).unwrap()) + .await + .expect("delete the stream that the cursor names"); + let rest = first + .next(&page) + .expect("a new cursor") + .expect("more pages") + .read_to_end(|query| async move { client.get_streams_page(&query).await }) + .await + .expect("the pages after the deleted stream"); + read.extend(rest.into_iter().map(|stream| stream.name)); + assert_eq!( + read, names, + "{order} order: no stream twice and none left out" + ); + for name in [&names[0], &names[2], &names[3]] { + client + .delete_stream(&Identifier::named(name).unwrap()) + .await + .expect("delete stream"); + } + } + + let parent = Identifier::named("pages-parent").unwrap(); + client + .create_stream("pages-parent", &StreamCreateOptions::default()) + .await + .expect("create stream"); + for name in ["pages-parent-t1", "pages-parent-t2", "pages-parent-t3"] { + create_topic(client, &parent, name, 1).await; + } + let first = NamedPageQuery::from(PageQuery { + limit: 2, + ..PageQuery::default() + }); + let page = client + .get_topics_page(&parent, &first) + .await + .expect("the first page of topics"); + let next = first + .next(&page) + .expect("a new cursor") + .expect("more topics"); + client + .delete_stream(&parent) + .await + .expect("delete the stream during the walk"); + assert_error_code( + client.get_topics_page(&parent, &next).await, + IggyError::StreamIdNotFound(Identifier::default()), + "a topics page after its stream was deleted", + ); +} + +async fn assert_page_refusals( + harness: &TestHarness, + root: &IggyClient, + stream_id: &Identifier, + topic_id: &Identifier, +) { + let empty = PageQuery { + limit: 0, + ..PageQuery::default() + }; + assert_error_code( + root.get_partitions_page(stream_id, topic_id, &empty).await, + IggyError::InvalidCommand, + "a limit of 0", + ); + assert_error_code( + root.get_streams_page(&empty.into()).await, + IggyError::InvalidCommand, + "a limit of 0", + ); + let first = NamedPageQuery::from(PageQuery { + limit: 1, + ..PageQuery::default() + }); + let id_page = root + .get_streams_page(&first) + .await + .expect("a first page in id order"); + let other_order = NamedPageQuery::from(PageQuery { + order: PageOrder::Created, + cursor: Some(id_page.next.expect("more than one stream")), + ..PageQuery::default() + }); + assert_error_code( + root.get_streams_page(&other_order).await, + IggyError::InvalidCommand, + "an id cursor in a creation walk", + ); + let missing_topic = Identifier::named("pages-missing-topic").unwrap(); + let missing_topic_error = + IggyError::TopicIdNotFound(Identifier::default(), Identifier::default()); + assert_error_code( + root.get_partitions_page(stream_id, &missing_topic, &PageQuery::default()) + .await, + missing_topic_error.clone(), + "the partitions of a missing topic", + ); + assert_error_code( + root.get_consumer_groups_page(stream_id, &missing_topic, &NamedPageQuery::default()) + .await, + missing_topic_error, + "the consumer groups of a missing topic", + ); + + create_user(root, READER).await; + let reader = create_client(harness).await; + reader + .login_user(READER, PASSWORD) + .await + .expect("login the user without permissions"); + let query = PageQuery::default(); + let named = NamedPageQuery::default(); + assert_error_code( + reader.get_streams_page(&named).await, + IggyError::Unauthorized, + "a streams page without the permission to read streams", + ); + assert_error_code( + reader.get_topics_page(stream_id, &named).await, + IggyError::Unauthorized, + "a topics page without the permission to read the stream", + ); + assert_error_code( + reader + .get_partitions_page(stream_id, topic_id, &query) + .await, + IggyError::Unauthorized, + "a partitions page without the permission to read the topic", + ); + assert_error_code( + reader + .get_consumer_groups_page(stream_id, topic_id, &named) + .await, + IggyError::Unauthorized, + "a consumer groups page without the permission to read the topic", + ); + assert_error_code( + reader.get_users_page(&named).await, + IggyError::Unauthorized, + "a users page without the permission to read users", + ); + root.delete_user(&Identifier::named(READER).unwrap()) + .await + .expect("delete the user without permissions"); +} + +async fn create_topic(client: &IggyClient, stream_id: &Identifier, name: &str, partitions: u32) { + client + .create_topic( + stream_id, + name, + &TopicCreateOptions { + partitions_count: Some(partitions), + message_expiry: Some(IggyExpiry::NeverExpire), + ..TopicCreateOptions::default() + }, + ) + .await + .expect("create topic"); +} + +async fn create_user(client: &IggyClient, username: &str) { + client + .create_user( + username, + PASSWORD, + UserStatus::Active, + None, + &UserCreateOptions::default(), + ) + .await + .expect("create user"); +} + +/// Walks each order both ways in pages of [`PAGE_LIMIT`] and compares the +/// names with `by_id` and `by_created`, both in ascending order. +async fn assert_walks<T, Fut>( + by_id: &[&str], + by_created: &[&str], + name: impl Fn(&T) -> &str, + mut read_page: impl FnMut(PageQuery) -> Fut, +) where + Fut: Future<Output = Result<Page<T>, IggyError>>, +{ + for (order, ascending) in [(PageOrder::Id, by_id), (PageOrder::Created, by_created)] { + for descending in [false, true] { + let first = PageQuery { + order, + descending, + limit: PAGE_LIMIT, + ..PageQuery::default() + }; + let (items, pages) = walk(first, &mut read_page).await; + let mut expected = ascending.to_vec(); + if descending { + expected.reverse(); + } + let names: Vec<&str> = items.iter().map(&name).collect(); + let case = format!("{order} order, descending {descending}"); + assert_eq!(names, expected, "{case}"); + assert_eq!( + pages, + expected.len().div_ceil(PAGE_LIMIT as usize), + "{case}: only the last page has no next" + ); + } + } +} + +/// Every page of partitions from `first` on, as the partition ids and the +/// pages read. +async fn walk_partitions( + client: &IggyClient, + stream_id: &Identifier, + topic_id: &Identifier, + first: PageQuery, +) -> (Vec<u32>, usize) { + let (partitions, pages) = walk(first, |query| async move { + client + .get_partitions_page(stream_id, topic_id, &query) + .await + }) + .await; + ( + partitions.iter().map(|partition| partition.id).collect(), + pages, + ) +} + +/// Every page from `first` on, as the items and the pages read. +async fn walk<T, Fut>( + first: PageQuery, + mut read_page: impl FnMut(PageQuery) -> Fut, +) -> (Vec<T>, usize) +where + Fut: Future<Output = Result<Page<T>, IggyError>>, +{ + let pages = Cell::new(0); + let items = first + .read_to_end(|query| { + pages.set(pages.get() + 1); + read_page(query) + }) + .await + .expect("every page reads"); + (items, pages.get()) +}
diff --git a/core/integration/tests/server/scenarios/mod.rs b/core/integration/tests/server/scenarios/mod.rs index 0fea848..558056c 100644 --- a/core/integration/tests/server/scenarios/mod.rs +++ b/core/integration/tests/server/scenarios/mod.rs
@@ -36,6 +36,7 @@ pub mod encryption_scenario; pub mod external_group_offsets_scenario; pub mod invalid_consumer_offset_scenario; +pub mod list_pages_scenario; pub mod log_rotation_scenario; pub mod message_cleanup_scenario; pub mod message_headers_scenario;
diff --git a/core/integration/tests/server/scenarios/permissions_scenario.rs b/core/integration/tests/server/scenarios/permissions_scenario.rs index f00c586..030813b 100644 --- a/core/integration/tests/server/scenarios/permissions_scenario.rs +++ b/core/integration/tests/server/scenarios/permissions_scenario.rs
@@ -3133,7 +3133,7 @@ /// `CannotDeleteUser`, and `CannotChangePermissions`) into a generic /// `HttpResponseError` wrapping the typed JSON body. Read the exact code back /// from that body's `id` so the assertion stays exact over HTTP as well. -fn assert_error_code<T: std::fmt::Debug>( +pub(crate) fn assert_error_code<T: std::fmt::Debug>( result: Result<T, IggyError>, expected: IggyError, context: &str,
diff --git a/core/metadata/src/change_log/current.rs b/core/metadata/src/change_log/current.rs index c987cc6..9ddda10 100644 --- a/core/metadata/src/change_log/current.rs +++ b/core/metadata/src/change_log/current.rs
@@ -249,25 +249,17 @@ let topic_from = after_topic.filter(|_| same_stream).unwrap_or(0); for (topic_id, topic) in stream.topics.iter_from(topic_from) { let same_topic = same_stream && after_topic == Some(topic_id); - // Group ids are monotone and bounded per topic. - let mut group_ids: Vec<u64> = topic - .consumer_groups - .keys() - .copied() - .filter(|group_id| { - after_group.filter(|_| same_topic).is_none_or(|after| { - let after = after as u64; - *group_id > after - || (group == MetadataChangeGroup::ConsumerGroupMembers - && *group_id == after) - }) - }) - .collect(); - group_ids.sort_unstable(); - for group_id in group_ids { - let Some(consumer_group) = topic.consumer_groups.get(&group_id) else { - continue; - }; + // Members continue inside the group of the cursor, groups after it. + let group_from = match after_group.filter(|_| same_topic) { + None => Bound::Unbounded, + Some(after) if group == MetadataChangeGroup::ConsumerGroupMembers => { + Bound::Included(after as u64) + } + Some(after) => Bound::Excluded(after as u64), + }; + for (&group_id, consumer_group) in + topic.consumer_groups.range((group_from, Bound::Unbounded)) + { let wire_group_id = group_id as u32; if group == MetadataChangeGroup::ConsumerGroups { let Ok(name) = WireName::new(consumer_group.name.as_ref()) else {
diff --git a/core/metadata/src/change_log/mod.rs b/core/metadata/src/change_log/mod.rs index 3a5a248..9505d11 100644 --- a/core/metadata/src/change_log/mod.rs +++ b/core/metadata/src/change_log/mod.rs
@@ -21,7 +21,7 @@ mod store; pub use current::{CurrentState, current_page}; -pub use query::{MAX_SCANNED_ENTRIES, change_page}; +pub use query::{MAX_PAGE_BYTES, MAX_SCANNED_ENTRIES, change_page}; pub use snapshot::{ChangeEntrySnapshot, ChangeLogSnapshot, RingSnapshot}; pub use store::{
diff --git a/core/metadata/src/change_log/tests.rs b/core/metadata/src/change_log/tests.rs index c6481a1..e36f7f7 100644 --- a/core/metadata/src/change_log/tests.rs +++ b/core/metadata/src/change_log/tests.rs
@@ -1482,6 +1482,9 @@ ); let session = harness.register(CLIENT_A, ALICE); harness.join(CLIENT_A, session); + // A second member makes the walk continue inside the group of its cursor. + let second = harness.register(CLIENT_B, ALICE); + harness.join(CLIENT_B, second); harness.commit( ROOT_CALLER, Operation::CreatePersonalAccessToken, @@ -1506,10 +1509,10 @@ assert_eq!(count(WireMetadataChangeGroup::Topics), 1); assert_eq!(count(WireMetadataChangeGroup::Partitions), 1); assert_eq!(count(WireMetadataChangeGroup::ConsumerGroups), 2); - assert_eq!(count(WireMetadataChangeGroup::ConsumerGroupMembers), 1); + assert_eq!(count(WireMetadataChangeGroup::ConsumerGroupMembers), 2); assert_eq!(count(WireMetadataChangeGroup::Users), 2); assert_eq!(count(WireMetadataChangeGroup::PersonalAccessTokens), 1); - assert_eq!(count(WireMetadataChangeGroup::Sessions), 2); + assert_eq!(count(WireMetadataChangeGroup::Sessions), 3); } #[test]
diff --git a/core/metadata/src/stm/consumer_group.rs b/core/metadata/src/stm/consumer_group.rs index 7c38fa6..7f268b6 100644 --- a/core/metadata/src/stm/consumer_group.rs +++ b/core/metadata/src/stm/consumer_group.rs
@@ -561,7 +561,7 @@ topic.consumer_group_catalog_op = state.apply_context.metadata_op; topic .consumer_groups - .insert(id, ConsumerGroup::new(id, name.clone())); + .insert(id, Box::new(ConsumerGroup::new(id, name.clone()))); topic.consumer_group_index.insert(name, id); let partitions_count = topic.partitions.len() as u32; let consumer_groups_count = topic.consumer_groups.len() as u32; @@ -2167,6 +2167,51 @@ } #[test] + fn given_a_deleted_group_when_snapshotted_and_listed_should_hold_ascending_ids() { + let mut state = streams_with_topic(); + for name in ["a", "b", "c", "d", "e"] { + assert_eq!(create_group(&mut state, name).code, 0); + } + let delete = DeleteConsumerGroupRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(0), + group_id: WireIdentifier::numeric(2), + }; + let deleted = crate::stm::lifecycle::apply_with_lifecycle_completion( + &delete, + &mut state, + IggyTimestamp::now(), + ); + assert_eq!(deleted.code, 0); + assert_eq!(create_group(&mut state, "f").code, 0); + let expected = [0, 1, 3, 4, 5]; + + let snapshot = Streams::from(state).to_snapshot(); + let snapshotted: Vec<u64> = snapshot.items[0].1.topics[0] + .1 + .consumer_groups + .iter() + .map(|(id, _)| *id) + .collect(); + assert_eq!(snapshotted, expected); + + let restored = Streams::from_snapshot(snapshot).unwrap(); + let listed: Vec<u64> = restored.read(|inner| { + inner + .items + .get(0) + .unwrap() + .topics + .get(0) + .unwrap() + .consumer_groups_after(None, false) + .map(|group| group.id) + .collect() + }); + assert_eq!(listed, expected); + } + + #[test] fn given_group_with_rows_and_no_members_when_partitions_grow_should_cover_every_partition() { const CLIENT: u128 = 7; let mut state = streams_with_topic();
diff --git a/core/metadata/src/stm/id_slab.rs b/core/metadata/src/stm/id_slab.rs index d47a331..fd1cd36 100644 --- a/core/metadata/src/stm/id_slab.rs +++ b/core/metadata/src/stm/id_slab.rs
@@ -30,6 +30,7 @@ //! occupied set, which is exactly what a snapshot carries. Restored and live //! arenas agree by construction. +use crate::stm::walk::Directed; use std::collections::BTreeSet; use std::ops::{Index, IndexMut}; @@ -136,6 +137,27 @@ Iter { inner } } + /// Occupied keys below `key`, ascending; `.rev()` walks them descending. + #[must_use] + pub fn iter_before(&self, key: usize) -> Iter<'_, T> { + Iter { + inner: self.entries[..key.min(self.entries.len())] + .iter() + .enumerate(), + } + } + + /// Occupied entries after `after` in one direction. An id page walks this. + #[must_use] + pub fn walk(&self, after: Option<usize>, descending: bool) -> Directed<Iter<'_, T>> { + let iter = match after { + None => self.iter(), + Some(key) if descending => self.iter_before(key), + Some(key) => self.iter_from(key.saturating_add(1)), + }; + Directed::new(iter, descending) + } + /// Ascending by key. pub fn iter_mut(&mut self) -> IterMut<'_, T> { IterMut { @@ -163,6 +185,17 @@ } } +impl<T> DoubleEndedIterator for Iter<'_, T> { + fn next_back(&mut self) -> Option<Self::Item> { + loop { + let (key, slot) = self.inner.next_back()?; + if let Some(value) = slot { + return Some((key, value)); + } + } + } +} + pub struct IterMut<'a, T> { inner: std::iter::Enumerate<std::slice::IterMut<'a, Option<T>>>, } @@ -292,6 +325,38 @@ assert_eq!(keys(usize::MAX), [] as [usize; 0]); } + #[test] + fn given_gaps_when_walking_after_a_key_should_yield_occupied_keys_past_it_in_both_directions() { + let mut slab: IdSlab<char> = IdSlab::new(); + for value in ['a', 'b', 'c', 'd', 'e', 'f'] { + slab.insert(value); + } + slab.remove(0); + slab.remove(3); + + let walk = |after, descending| { + slab.walk(after, descending) + .map(|(key, _)| key) + .collect::<Vec<_>>() + }; + + assert_eq!(walk(None, false), [1, 2, 4, 5]); + assert_eq!(walk(None, true), [5, 4, 2, 1]); + assert_eq!(walk(Some(3), false), [4, 5], "a vacant key still splits"); + assert_eq!(walk(Some(3), true), [2, 1]); + assert_eq!(walk(Some(1), true), [] as [usize; 0]); + assert_eq!(walk(Some(5), false), [] as [usize; 0]); + assert_eq!(walk(Some(usize::MAX), false), [] as [usize; 0]); + assert_eq!(walk(Some(usize::MAX), true), [5, 4, 2, 1]); + for after in 0..8 { + let mut ascending = walk(Some(after), false); + ascending.extend(walk(Some(after), true)); + ascending.extend(slab.get(after).map(|_| after)); + ascending.sort_unstable(); + assert_eq!(ascending, walk(None, false), "after {after}"); + } + } + /// The property the type exists for. `Slab` fails it: LIFO reuse makes the /// head depend on delete order while a rebuild scans ascending, so /// descending deletes diverge.
diff --git a/core/metadata/src/stm/mod.rs b/core/metadata/src/stm/mod.rs index 8216cf3..ad93d4d 100644 --- a/core/metadata/src/stm/mod.rs +++ b/core/metadata/src/stm/mod.rs
@@ -25,6 +25,7 @@ pub mod snapshot; pub mod stream; pub mod user; +pub mod walk; use iggy_binary_protocol::PrepareHeader; use iggy_common::Either; use left_right::{Absorb, ReadHandle, ReadHandleFactory, WriteHandle};
diff --git a/core/metadata/src/stm/stream.rs b/core/metadata/src/stm/stream.rs index 015e4ab..f7fae3b 100644 --- a/core/metadata/src/stm/stream.rs +++ b/core/metadata/src/stm/stream.rs
@@ -33,6 +33,7 @@ TruncatePartitionResult, UpdateStreamResult, UpdateTopicResult, }; use crate::stm::snapshot::{SnapshotError, Snapshotable}; +use crate::stm::walk::{Directed, range_after, slice_after}; use crate::stm::{ApplyContext, StateHandler}; use crate::{collect_handlers, define_state, impl_fill_restore}; use ahash::{AHashMap, AHashSet}; @@ -71,7 +72,7 @@ ConsumerGroupDetailsResponse, ConsumerGroupMemberResponse, }; use iggy_binary_protocol::responses::streams::StreamResponse; -use iggy_binary_protocol::responses::streams::get_stream::{GetStreamResponse, TopicHeader}; +use iggy_binary_protocol::responses::streams::get_stream::{GetStreamResponse, TopicResponse}; use iggy_binary_protocol::responses::topics::get_topic::PartitionResponse; use iggy_binary_protocol::{WireIdentifier, WireName, WireOptions}; use iggy_common::wire_conversions::{ @@ -400,7 +401,10 @@ /// Consumer groups belonging to this topic, keyed by monotonic group id. /// Co-located so a stream/topic delete drops them automatically. - pub consumer_groups: AHashMap<u64, ConsumerGroup>, + /// + /// Boxed, because a B-tree leaf reserves room for 11 values: a topic with + /// one group holds about 330 B this way and about 1.3 KB with plain values. + pub consumer_groups: BTreeMap<u64, Box<ConsumerGroup>>, /// Group name -> id, for per-topic name uniqueness + name resolution. pub consumer_group_index: AHashMap<Arc<str>, u64>, /// Monotonic group-id counter; never reused so the partition-plane offset @@ -432,7 +436,7 @@ stats: Arc::new(TopicStats::default()), partitions: Vec::new(), round_robin_counter: Arc::new(AtomicUsize::new(0)), - consumer_groups: AHashMap::default(), + consumer_groups: BTreeMap::new(), consumer_group_index: AHashMap::default(), next_consumer_group_id: 0, consumer_group_catalog_op: 0, @@ -452,7 +456,7 @@ stats: Arc::new(TopicStats::new(stream_stats)), partitions: Vec::new(), round_robin_counter: Arc::new(AtomicUsize::new(0)), - consumer_groups: AHashMap::default(), + consumer_groups: BTreeMap::new(), consumer_group_index: AHashMap::default(), next_consumer_group_id: 0, consumer_group_catalog_op: 0, @@ -484,6 +488,62 @@ WireIdentifier::String(name) => self.consumer_group_index.get(name.as_str()).copied(), } } + + /// The consumer groups after the group id `after`, in id order. Group ids + /// are never used again, so id order is creation order. + pub fn consumer_groups_after( + &self, + after: Option<u64>, + descending: bool, + ) -> impl Iterator<Item = &ConsumerGroup> { + Directed::new( + self.consumer_groups + .range(range_after(after.as_ref(), descending)), + descending, + ) + .map(|(_, group)| group.as_ref()) + } + + /// The list item of `group`, one of the consumer groups of this topic. + #[must_use] + #[allow(clippy::cast_possible_truncation, clippy::missing_panics_doc)] + pub fn consumer_group_response(&self, group: &ConsumerGroup) -> ConsumerGroupResponse { + ConsumerGroupResponse { + id: group.id as u32, + partitions_count: self.partitions.len() as u32, + members_count: group.members.len() as u32, + // The name was validated at create, so the fallback is unreachable. + name: WireName::new(group.name.as_ref()) + .unwrap_or_else(|_| WireName::new("unknown").expect("valid")), + } + } + + /// The partitions after the partition id `after`, in id order. A create + /// appends ids above the highest and a delete cuts the tail, so ids ascend + /// over the vector and id order is creation order. + #[must_use] + pub fn partitions_after( + &self, + after: Option<usize>, + descending: bool, + ) -> Directed<std::slice::Iter<'_, Partition>> { + slice_after( + &self.partitions, + |partition| partition.id, + after, + descending, + ) + } + + /// [`Self::partitions_after`] skips or repeats partitions when ids do not + /// ascend over `partitions`. Only the primary mints the ids of a create. + fn debug_assert_partition_ids_ascend(&self) { + debug_assert!( + self.partitions + .is_sorted_by(|left, right| left.id < right.id), + "partition ids must ascend over Topic::partitions" + ); + } } /// Stream snapshot representation for serialization. @@ -560,6 +620,20 @@ } } + /// The topics in creation order, keyed by `(created_at micros, topic id)`. + /// A stream holds at most `MAX_TOPICS` topics, so a page sorts them for + /// each read in place of an index that every topic apply keeps. + #[must_use] + pub fn topics_by_created(&self) -> Vec<((u64, usize), &Topic)> { + let mut topics: Vec<_> = self + .topics + .iter() + .map(|(id, topic)| ((topic.created_at.as_micros(), id), topic)) + .collect(); + topics.sort_unstable_by_key(|(key, _)| *key); + topics + } + #[must_use] pub fn with_stats(name: Arc<str>, created_at: IggyTimestamp, stats: Arc<StreamStats>) -> Self { Self { @@ -1020,6 +1094,29 @@ // left-right buffers (see `StatsRegistry`). Not snapshotted -- rebuilt // as streams/topics restore. pub stats_registry: Arc<StatsRegistry>, + // `(created_at micros, stream id)` of every stream, so a page in + // creation order seeks by key. Never persisted, rebuilt on restore. + pub(crate) created_index: BTreeSet<(u64, usize)>, + } +} + +impl StreamsInner { + /// The streams after `after` in creation order, newest first when + /// `descending`. The key of a stream is `(created_at micros, stream id)`. + pub fn streams_by_created( + &self, + after: Option<(u64, usize)>, + descending: bool, + ) -> impl Iterator<Item = ((u64, usize), &Stream)> { + Directed::new( + self.created_index + .range(range_after(after.as_ref(), descending)), + descending, + ) + .filter_map(|&key| { + let stream = self.items.get(key.1)?; + (stream.created_at.as_micros() == key.0).then_some((key, stream)) + }) } } @@ -1856,7 +1953,7 @@ /// round-robin partition assignment). `partitions_count` is the topic's /// total partition count. `None` if the stream/topic/group is unknown. #[must_use] - #[allow(clippy::cast_possible_truncation, clippy::missing_panics_doc)] + #[allow(clippy::cast_possible_truncation)] pub fn consumer_group_details( &self, stream_id: &WireIdentifier, @@ -1880,50 +1977,12 @@ }) .collect(); Some(ConsumerGroupDetailsResponse { - group: ConsumerGroupResponse { - id: group.id as u32, - partitions_count: topic.partitions.len() as u32, - members_count: group.members.len() as u32, - // The name was validated at create, so the fallback is - // unreachable. - name: WireName::new(group.name.as_ref()) - .unwrap_or_else(|_| WireName::new("unknown").expect("valid")), - }, + group: topic.consumer_group_response(group), members, }) }) } - /// All consumer groups of a topic (for `GetConsumerGroups`). `None` if the - /// stream/topic is unknown. - #[must_use] - #[allow(clippy::cast_possible_truncation, clippy::missing_panics_doc)] - pub fn consumer_group_list( - &self, - stream_id: &WireIdentifier, - topic_id: &WireIdentifier, - ) -> Option<Vec<ConsumerGroupResponse>> { - self.inner.read(|inner| { - let stream_id = inner.resolve_stream_id(stream_id)?; - let topic_id = inner.resolve_topic_id(stream_id, topic_id)?; - let topic = inner.items.get(stream_id)?.topics.get(topic_id)?; - let partitions_count = topic.partitions.len() as u32; - Some( - topic - .consumer_groups - .values() - .map(|group| ConsumerGroupResponse { - id: group.id as u32, - partitions_count, - members_count: group.members.len() as u32, - name: WireName::new(group.name.as_ref()) - .unwrap_or_else(|_| WireName::new("unknown").expect("valid")), - }) - .collect(), - ) - }) - } - /// The requesting member's `(generation, partitions)` -- served by the /// `SyncConsumerGroup` endpoint for client-side partition selection. #[must_use] @@ -3170,6 +3229,7 @@ let inserted = state.items.insert(stream); debug_assert_eq!(inserted, id, "vacant_key must match the insert slot"); state.index.insert(name_arc, id); + state.created_index.insert((timestamp.as_micros(), id)); let changes = state .items .get(id) @@ -3298,6 +3358,9 @@ state.stats_registry.remove_stream(stream_id, stream); let removed = state.items.remove(stream_id); state.index.remove(&name); + state + .created_index + .remove(&(removed.created_at.as_micros(), stream_id)); state.revision = state.revision.wrapping_add(1); state.namespace_revision = state.revision; for (topic_id, topic) in &removed.topics { @@ -3422,7 +3485,7 @@ stats: topic_stats, partitions: Vec::new(), round_robin_counter: Arc::new(AtomicUsize::new(0)), - consumer_groups: AHashMap::default(), + consumer_groups: BTreeMap::new(), consumer_group_index: AHashMap::default(), next_consumer_group_id: 0, consumer_group_catalog_op: 0, @@ -3454,6 +3517,7 @@ ); topic.partitions.push(partition); } + topic.debug_assert_partition_ids_ascend(); } stream.topic_index.insert(name_arc, topic_id); @@ -3494,7 +3558,7 @@ .unwrap_or_else(|_| (WireOptions::empty(), WireOptions::empty())) } -/// Encode the `CreateTopic` reply as `[TopicHeader][PartitionResponse]*`, +/// Encode the `CreateTopic` reply as `[TopicResponse][PartitionResponse]*`, /// the `GetTopicResponse` shape the SDK already decodes, so the create /// reply deserializes without a schema break. Returns empty bytes on a /// `u32` overflow (same contract as a validation rejection) rather than @@ -3512,7 +3576,7 @@ return Bytes::new(); }; let (options, derived_options) = public_reply_options(OptionsScope::Topic, &topic.options); - let header = TopicHeader { + let header = TopicResponse { id: topic_id_u32, created_at: topic.created_at.into(), partitions_count: partitions_count_u32, @@ -3948,6 +4012,7 @@ ); topic.partitions.push(partition); } + topic.debug_assert_partition_ids_ascend(); // Added partitions are unassigned until the groups rebalance. topic.rebalance_consumer_groups(state.apply_context.metadata_op, timestamp); state.recompute_consumer_group_metadata(); @@ -4062,9 +4127,7 @@ /// /// Serialized-form invariant (see [`crate::stm::snapshot::MetadataSnapshot`]): /// `items` and the nested `topics` / `consumer_groups` / `partitions` stay ordered -/// `Vec`s even though the runtime holds them in `AHashMap`s and an [`IdSlab`]. Swapping -/// any back to an unordered map reorders on a decode and re-encode, breaking the -/// checkpoint checksum cross-check recovery relies on. +/// `Vec`s, so two replicas with the same state write the same bytes. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StreamsSnapshot { pub items: Vec<(usize, StreamSnapshot)>, @@ -4290,7 +4353,7 @@ consumer_groups: topic_snap .consumer_groups .into_iter() - .map(|(id, group_snap)| (id, group_snap.into_group())) + .map(|(id, group_snap)| (id, Box::new(group_snap.into_group()))) .collect(), }; topic_index.insert(topic_name, topic_slab_key); @@ -4332,9 +4395,14 @@ .map(|partition| partition.retirement_debt_op) .max() .unwrap_or(0); + let created_index = items + .iter() + .map(|(id, stream)| (stream.created_at.as_micros(), id)) + .collect(); let mut inner = Self { index, items, + created_index, revision: snapshot.revision, namespace_revision: snapshot.namespace_revision, retirement_debt_revision, @@ -5774,7 +5842,7 @@ #[test] fn create_topic_apply_returns_get_topic_response_compatible_bytes() { - // STM apply must emit `[TopicHeader][PartitionResponse]*` so existing + // STM apply must emit `[TopicResponse][PartitionResponse]*` so existing // SDK decoders (`decode_response::<GetTopicResponse>`) parse the reply // without a wire-schema break. let mut inner = StreamsInner::new(); @@ -6861,7 +6929,7 @@ .assignments .insert(2, owner(OTHER_CLIENT, incarnation)); group.assignments.insert(3, owner(CLIENT, incarnation + 1)); - topic.consumer_groups.insert(group.id, group); + topic.consumer_groups.insert(group.id, Box::new(group)); topic.consumer_group_index.insert(Arc::from("readers"), 3); let streams = Streams::from(inner); let stream_id = WireIdentifier::numeric(0); @@ -7743,4 +7811,198 @@ assert_eq!(streams.member_outside_cluster(3), Some((namespace, 4))); assert_eq!(streams.member_outside_cluster(5), None); } + + fn stream_creation_keys(inner: &StreamsInner) -> BTreeSet<(u64, usize)> { + inner + .items + .iter() + .map(|(id, stream)| (stream.created_at.as_micros(), id)) + .collect() + } + + fn create_stream_at(inner: &mut StreamsInner, name: &str, micros: u64) { + let create = CreateStreamRequest { + name: WireName::new(name).unwrap(), + options: WireOptions::empty(), + }; + let reply = StateHandler::apply(&create, inner, IggyTimestamp::from(micros)); + assert_eq!(reply.code, 0); + } + + fn delete_stream_at(inner: &mut StreamsInner, stream_id: usize, micros: u64) { + let delete = DeleteStreamRequest { + stream_id: WireIdentifier::numeric(u32::try_from(stream_id).unwrap()), + }; + let reply = crate::stm::lifecycle::apply_with_lifecycle_completion( + &delete, + inner, + IggyTimestamp::from(micros), + ); + assert_eq!(reply.code, 0); + } + + #[test] + fn given_random_stream_creates_and_deletes_when_applied_should_keep_the_creation_index_exact() { + let mut inner = StreamsInner::new(); + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + for step in 1..=400u64 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let live: Vec<usize> = inner.items.iter().map(|(id, _)| id).collect(); + if live.is_empty() || !seed.is_multiple_of(3) { + create_stream_at(&mut inner, &format!("s{step}"), step); + } else { + let pick = usize::try_from(seed % live.len() as u64).unwrap(); + delete_stream_at(&mut inner, live[pick], step); + } + assert_eq!( + inner.created_index, + stream_creation_keys(&inner), + "step {step}" + ); + } + assert!(inner.created_index.len() > 10); + let snapshot = Streams::from(inner.clone()).to_snapshot(); + let restored = StreamsInner::inner_from_snapshot(snapshot, Arc::default()); + assert_eq!(restored.created_index, stream_creation_keys(&inner)); + } + + #[test] + fn given_a_reused_stream_id_when_walking_by_creation_should_list_the_new_stream_last() { + let mut inner = StreamsInner::new(); + for (micros, name) in [(10, "a"), (20, "b"), (30, "c")] { + create_stream_at(&mut inner, name, micros); + } + delete_stream_at(&mut inner, 0, 40); + create_stream_at(&mut inner, "d", 50); + assert_eq!(inner.items[0].name.as_ref(), "d"); + + let by_created = |after, descending| { + inner + .streams_by_created(after, descending) + .map(|((_, id), _)| id) + .collect::<Vec<_>>() + }; + assert_eq!(by_created(None, false), [1, 2, 0]); + assert_eq!(by_created(None, true), [0, 2, 1]); + assert_eq!(by_created(Some((20, 1)), false), [2, 0]); + assert_eq!(by_created(Some((50, 0)), true), [2, 1]); + assert_eq!( + by_created(Some((10, 0)), false), + [1, 2, 0], + "a deleted key still splits" + ); + let by_id: Vec<usize> = inner.items.walk(None, false).map(|(id, _)| id).collect(); + assert_eq!(by_id, [0, 1, 2]); + } + + #[test] + fn given_a_reused_topic_id_when_sorting_by_creation_should_list_the_new_topic_last() { + let create_topic_at = |inner: &mut StreamsInner, name: &str, micros: u64| { + let create = CreateTopicWithAssignmentsRequest { + request: make_topic_request(0, 1, name), + derived_options: WireOptions::empty(), + partitions: vec![CreatedPartitionAssignment { + initial_view: 0, + partition_id: 0, + consensus_group_id: micros, + members: Vec::new(), + }], + }; + let reply = crate::stm::lifecycle::apply_with_lifecycle_completion( + &create, + inner, + IggyTimestamp::from(micros), + ); + assert_eq!(reply.code, 0); + }; + let mut inner = StreamsInner::new(); + create_stream_at(&mut inner, "stream", 1); + for (micros, name) in [(10, "a"), (20, "b"), (30, "c")] { + create_topic_at(&mut inner, name, micros); + } + let delete = DeleteTopicRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(0), + }; + let reply = crate::stm::lifecycle::apply_with_lifecycle_completion( + &delete, + &mut inner, + IggyTimestamp::from(40), + ); + assert_eq!(reply.code, 0); + create_topic_at(&mut inner, "d", 50); + + let stream = &inner.items[0]; + assert_eq!(stream.topics[0].name.as_ref(), "d"); + let order: Vec<usize> = stream + .topics_by_created() + .into_iter() + .map(|((_, id), _)| id) + .collect(); + assert_eq!(order, [1, 2, 0]); + } + + #[test] + fn given_partition_deletes_and_creates_when_walking_should_yield_ascending_ids() { + let mut inner = StreamsInner::new(); + create_stream(&mut inner, "stream"); + create_topic_with_partitions(&mut inner, 4); + let delete = DeletePartitionsRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(0), + partitions_count: 2, + }; + let reply = crate::stm::lifecycle::apply_with_lifecycle_completion( + &delete, + &mut inner, + IggyTimestamp::now(), + ); + assert_eq!(reply.code, 0); + let create = CreatePartitionsWithAssignmentsRequest { + request: WireCreatePartitionsRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(0), + partitions_count: 3, + }, + partitions: (0..3) + .map(|partition_id| CreatedPartitionAssignment { + initial_view: 0, + partition_id, + consensus_group_id: 100 + u64::from(partition_id), + members: Vec::new(), + }) + .collect(), + }; + let reply = crate::stm::lifecycle::apply_with_lifecycle_completion( + &create, + &mut inner, + IggyTimestamp::now(), + ); + assert_eq!(reply.code, 0); + + let walk = |topic: &Topic, after, descending| { + topic + .partitions_after(after, descending) + .map(|partition| partition.id) + .collect::<Vec<_>>() + }; + let topic = &inner.items[0].topics[0]; + assert_eq!(walk(topic, None, false), [0, 1, 2, 3, 4]); + assert_eq!(walk(topic, Some(1), false), [2, 3, 4]); + assert_eq!(walk(topic, Some(3), true), [2, 1, 0]); + let snapshot = Streams::from(inner.clone()).to_snapshot(); + let restored = StreamsInner::inner_from_snapshot(snapshot, Arc::default()); + assert_eq!( + walk(&restored.items[0].topics[0], None, false), + [0, 1, 2, 3, 4] + ); + + let mut sparse = topic.clone(); + sparse.partitions.remove(2); + assert_eq!(walk(&sparse, Some(2), false), [3, 4]); + assert_eq!(walk(&sparse, Some(2), true), [1, 0]); + assert_eq!(walk(&sparse, None, true), [4, 3, 1, 0]); + } }
diff --git a/core/metadata/src/stm/user.rs b/core/metadata/src/stm/user.rs index 2b30302..1dcd711 100644 --- a/core/metadata/src/stm/user.rs +++ b/core/metadata/src/stm/user.rs
@@ -25,6 +25,7 @@ }; use crate::stm::snapshot::Snapshotable; use crate::stm::stream::{PatchError, patched_options, public_reply_options}; +use crate::stm::walk::{Directed, range_after}; use crate::stm::{ApplyContext, StateHandler}; use crate::{collect_handlers, define_state, impl_fill_restore}; use ahash::AHashMap; @@ -130,6 +131,29 @@ // seek by key instead of sorting the per-user maps. Never persisted. pub(crate) personal_access_token_name_index: BTreeSet<(UserId, Arc<str>)>, pub(crate) permissioner: Permissioner, + // `(created_at micros, user id)` of every user, so a page in creation + // order seeks by key. Never persisted, rebuilt on restore. + pub(crate) created_index: BTreeSet<(u64, usize)>, + } +} + +impl UsersInner { + /// The users after `after` in creation order, newest first when + /// `descending`. The key of a user is `(created_at micros, user id)`. + pub fn users_by_created( + &self, + after: Option<(u64, usize)>, + descending: bool, + ) -> impl Iterator<Item = ((u64, usize), &User)> { + Directed::new( + self.created_index + .range(range_after(after.as_ref(), descending)), + descending, + ) + .filter_map(|&key| { + let user = self.items.get(key.1)?; + (user.created_at.as_micros() == key.0).then_some((key, user)) + }) } } @@ -585,6 +609,7 @@ if let Some(user) = state.items.get_mut(id) { user.id = id as UserId; } + state.created_index.insert((timestamp.as_micros(), id)); state.index.insert(username_arc, id as UserId); // A reused ID must not inherit token-index entries from its previous holder. @@ -742,7 +767,10 @@ change_actor(&state.apply_context), ) })); - state.items.remove(user_id); + let removed = state.items.remove(user_id); + state + .created_index + .remove(&(removed.created_at.as_micros(), user_id)); state.index.remove(&username); state.remove_personal_access_tokens(user_id as UserId); state @@ -1302,10 +1330,15 @@ // Rebuild the permissioner from the restored users rather than the // snapshot vecs, which are intentionally empty (see `to_snapshot`). let permissioner = permissioner_of(&items); + let created_index = items + .iter() + .map(|(id, user)| (user.created_at.as_micros(), id)) + .collect(); Self { index, items, + created_index, personal_access_tokens, personal_access_token_index, personal_access_token_expiry_index, @@ -2397,4 +2430,91 @@ Some(UserStatus::Active) ); } + + fn user_creation_keys(users: &UsersInner) -> BTreeSet<(u64, usize)> { + users + .items + .iter() + .map(|(id, user)| (user.created_at.as_micros(), id)) + .collect() + } + + fn create_user_at(users: &mut UsersInner, username: &str, micros: u64) { + let request = CreateUserRequest { + username: WireName::new(username).unwrap(), + password: "hash".to_owned(), + status: 1, + permissions: None, + options: WireOptions::empty(), + }; + let reply = StateHandler::apply(&request, users, IggyTimestamp::from(micros)); + assert_eq!(reply.code, 0); + } + + fn delete_user_at(users: &mut UsersInner, user_id: usize, micros: u64) { + let request = DeleteUserRequest { + user_id: WireIdentifier::numeric(u32::try_from(user_id).unwrap()), + }; + let reply = StateHandler::apply(&request, users, IggyTimestamp::from(micros)); + assert_eq!(reply.code, 0); + } + + #[test] + fn given_random_user_creates_and_deletes_when_applied_should_keep_the_creation_index_exact() { + let mut users = UsersInner::new(); + create_user_at(&mut users, "root", 1); + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + for step in 2..=400u64 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let deletable: Vec<usize> = users + .items + .iter() + .map(|(id, _)| id) + .filter(|&id| id != DEFAULT_ROOT_USER_ID as usize) + .collect(); + if deletable.is_empty() || !seed.is_multiple_of(3) { + create_user_at(&mut users, &format!("user{step}"), step); + } else { + let pick = usize::try_from(seed % deletable.len() as u64).unwrap(); + delete_user_at(&mut users, deletable[pick], step); + } + assert_eq!( + users.created_index, + user_creation_keys(&users), + "step {step}" + ); + } + assert!(users.created_index.len() > 10); + let snapshot = Users::from(users.clone()).to_snapshot(); + let restored = UsersInner::inner_from_snapshot(snapshot); + assert_eq!(restored.created_index, user_creation_keys(&users)); + } + + #[test] + fn given_a_reused_user_id_when_walking_by_creation_should_list_the_new_user_last() { + let mut users = UsersInner::new(); + for (micros, username) in [(10, "root"), (20, "bravo"), (30, "charlie")] { + create_user_at(&mut users, username, micros); + } + delete_user_at(&mut users, 1, 40); + create_user_at(&mut users, "delta", 50); + assert_eq!(users.items[1].username.as_ref(), "delta"); + + let by_created = |after, descending| { + users + .users_by_created(after, descending) + .map(|((_, id), _)| id) + .collect::<Vec<_>>() + }; + assert_eq!(by_created(None, false), [0, 2, 1]); + assert_eq!(by_created(None, true), [1, 2, 0]); + assert_eq!(by_created(Some((30, 2)), false), [1]); + assert_eq!( + by_created(Some((20, 1)), true), + [0], + "a deleted key still splits" + ); + } }
diff --git a/core/metadata/src/stm/walk.rs b/core/metadata/src/stm/walk.rs new file mode 100644 index 0000000..5cbe987 --- /dev/null +++ b/core/metadata/src/stm/walk.rs
@@ -0,0 +1,130 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Ordered walks behind the list pages. +//! +//! A walk yields the entries after a position in one direction: the larger +//! keys, or the smaller keys when it is descending. The entry at the position +//! itself need not exist any more, so a client can continue after a deleted +//! entry. + +use std::ops::Bound; + +/// The items of a double-ended iterator, from its front or, when descending, +/// from its back. Both directions of a walk then share one iterator type. +#[derive(Debug, Clone)] +pub struct Directed<I> { + inner: I, + descending: bool, +} + +impl<I> Directed<I> { + pub(crate) const fn new(inner: I, descending: bool) -> Self { + Self { inner, descending } + } +} + +impl<I: DoubleEndedIterator> Iterator for Directed<I> { + type Item = I::Item; + + fn next(&mut self) -> Option<Self::Item> { + if self.descending { + self.inner.next_back() + } else { + self.inner.next() + } + } +} + +/// The range of an ordered map or set that holds the keys after `after`. +#[must_use] +pub(crate) const fn range_after<K>(after: Option<&K>, descending: bool) -> (Bound<&K>, Bound<&K>) { + match (after, descending) { + (None, _) => (Bound::Unbounded, Bound::Unbounded), + (Some(key), false) => (Bound::Excluded(key), Bound::Unbounded), + (Some(key), true) => (Bound::Unbounded, Bound::Excluded(key)), + } +} + +/// The items of `sorted` after `after`, where `key` ascends over `sorted`. +pub fn slice_after<T, K: Ord>( + sorted: &[T], + key: impl Fn(&T) -> K, + after: Option<K>, + descending: bool, +) -> Directed<std::slice::Iter<'_, T>> { + let range = match after { + None => sorted, + Some(after) if descending => &sorted[..sorted.partition_point(|item| key(item) < after)], + Some(after) => &sorted[sorted.partition_point(|item| key(item) <= after)..], + }; + Directed::new(range.iter(), descending) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeSet; + + #[test] + fn given_a_position_when_walking_a_set_should_yield_the_keys_past_it_in_its_direction() { + let set: BTreeSet<u64> = [1, 3, 5, 7].into_iter().collect(); + let walk = |after: Option<u64>, descending| { + Directed::new( + set.range(range_after(after.as_ref(), descending)), + descending, + ) + .copied() + .collect::<Vec<_>>() + }; + assert_eq!(walk(None, false), [1, 3, 5, 7]); + assert_eq!(walk(None, true), [7, 5, 3, 1]); + assert_eq!(walk(Some(3), false), [5, 7]); + assert_eq!(walk(Some(3), true), [1]); + assert_eq!( + walk(Some(4), false), + [5, 7], + "an absent position still splits" + ); + assert_eq!(walk(Some(4), true), [3, 1]); + assert_eq!(walk(Some(7), false), Vec::<u64>::new()); + assert_eq!(walk(Some(1), true), Vec::<u64>::new()); + } + + #[test] + fn given_a_position_when_walking_a_sorted_slice_should_match_the_set_walk() { + let sorted = [2u64, 4, 6, 8, 10]; + let set: BTreeSet<u64> = sorted.into_iter().collect(); + for descending in [false, true] { + for after in [None, Some(0), Some(2), Some(5), Some(10), Some(11)] { + let from_slice: Vec<u64> = slice_after(&sorted, |item| *item, after, descending) + .copied() + .collect(); + let from_set: Vec<u64> = Directed::new( + set.range(range_after(after.as_ref(), descending)), + descending, + ) + .copied() + .collect(); + assert_eq!( + from_slice, from_set, + "after {after:?}, descending {descending}" + ); + } + } + } +}
diff --git a/core/sdk/Cargo.toml b/core/sdk/Cargo.toml index ab8de36..ba64d62 100644 --- a/core/sdk/Cargo.toml +++ b/core/sdk/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy" -version = "0.12.0" +version = "0.12.1-edge.1" description = "Iggy is the persistent message streaming platform written in Rust, supporting QUIC, TCP and HTTP transport protocols, capable of processing millions of messages per second." edition = "2024" rust-version.workspace = true
diff --git a/core/sdk/README.md b/core/sdk/README.md index 00ccd36..81abe3b 100644 --- a/core/sdk/README.md +++ b/core/sdk/README.md
@@ -53,7 +53,7 @@ Mixed versions and rolling upgrades are unsupported. Binary clients share one logical session across replica links using BindSession (15) and discover partition primaries with GetPartitionRoute (105). The minimum binary protocol -version is 0.12.2. Commands 14, 103, 104, 107, 123 and 124 are retired. HTTP clients +version is 0.12.3. Commands 14, 103, 104, 107, 123 and 124 are retired. HTTP clients use server-side forwarding. ```bash @@ -694,6 +694,40 @@ Upgrade every server node first as well. A node of an older release cannot store a batch with a producer. +## List pages + +`get_streams_page`, `get_topics_page`, `get_partitions_page`, `get_consumer_groups_page` and `get_users_page` read one page of a list. A `PageQuery` sets the order, the direction, the limit and the cursor. The lists of named entities take a `NamedPageQuery`, which adds a name filter to a `PageQuery`. A partition has no name, so `get_partitions_page` takes a `PageQuery`. + +To read the next page, send the same query with the `next` cursor of the page. The `next` method of either query builds that query and returns `None` after the last page. A page can be empty and still have a `next`. + +```rust +use iggy::prelude::*; + +async fn print_streams(client: &IggyClient) -> Result<(), IggyError> { + let mut query = NamedPageQuery { + page: PageQuery { + order: PageOrder::Created, + ..PageQuery::default() + }, + name: Some("orders".to_owned()), + }; + loop { + let page = client.get_streams_page(&query).await?; + for stream in &page.items { + println!("{} {}", stream.id, stream.name); + } + match query.next(&page)? { + Some(next) => query = next, + None => return Ok(()), + } + } +} +``` + +The page methods call `validate` on the query before they send anything. It refuses a limit outside 1 to 1000, and a name that is empty or longer than 255 bytes, with `InvalidCommand`. If a page answers the cursor that it was read with, `next` fails with `InvalidFormat`, so a walk cannot loop forever. A `PageCursor` prints as `pg1_` text, the form that the CLI and the HTTP API use, and `str::parse` reads it back. + +`get_streams`, `get_topics`, `get_consumer_groups` and `get_users` return the whole list. Over TCP, QUIC and WebSocket, they read pages of 1000 in id order, so the result is not one consistent read. Over HTTP, they read the bare array, which the server also builds from pages. + ## Metadata changes `get_metadata_changes` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `next` cursor. The call needs root or the global `manage_servers` permission.
diff --git a/core/sdk/src/client_wrappers/client_wrapper.rs b/core/sdk/src/client_wrappers/client_wrapper.rs index 15e2ad9..3072672 100644 --- a/core/sdk/src/client_wrappers/client_wrapper.rs +++ b/core/sdk/src/client_wrappers/client_wrapper.rs
@@ -44,13 +44,13 @@ BatchProducer, Checkpoint, Client, ClientInfo, ClientInfoDetails, ClusterClient, ClusterMetadata, ConsumerGroup, ConsumerGroupAssignment, ConsumerGroupClient, ConsumerGroupDetails, ConsumerOffsetClient, ConsumerOffsetInfo, DecodeError, DiagnosticEvent, - IdentityInfo, MetadataChanges, MetadataChangesQuery, NonZeroIggyDuration, OptionSpec, - OptionsScope, PartitionClient, Permissions, PersonalAccessTokenClient, - PersonalAccessTokenExpiry, PersonalAccessTokenInfo, PolledMessages, RawPersonalAccessToken, - SegmentClient, Snapshot, SnapshotCompression, Stats, Stream, StreamClient, StreamCreateOptions, - StreamDetails, StreamUpdateOptions, SystemSnapshotType, Topic, TopicClient, TopicCreateOptions, - TopicDetails, TopicUpdateOptions, UserClient, UserCreateOptions, UserInfo, UserInfoDetails, - UserStatus, UserUpdateOptions, + IdentityInfo, MetadataChanges, MetadataChangesQuery, NamedPageQuery, NonZeroIggyDuration, + OptionSpec, OptionsScope, Page, PageQuery, Partition, PartitionClient, Permissions, + PersonalAccessTokenClient, PersonalAccessTokenExpiry, PersonalAccessTokenInfo, PolledMessages, + RawPersonalAccessToken, SegmentClient, Snapshot, SnapshotCompression, Stats, Stream, + StreamClient, StreamCreateOptions, StreamDetails, StreamUpdateOptions, SystemSnapshotType, + Topic, TopicClient, TopicCreateOptions, TopicDetails, TopicUpdateOptions, UserClient, + UserCreateOptions, UserInfo, UserInfoDetails, UserStatus, UserUpdateOptions, }; use std::time::Instant;
diff --git a/core/sdk/src/clients/binary_consumer_group.rs b/core/sdk/src/clients/binary_consumer_group.rs index a0f8913..5b080c6 100644 --- a/core/sdk/src/clients/binary_consumer_group.rs +++ b/core/sdk/src/clients/binary_consumer_group.rs
@@ -20,7 +20,7 @@ use async_trait::async_trait; use iggy_common::{ ConsumerGroup, ConsumerGroupAssignment, ConsumerGroupDetails, Identifier, IggyError, - locking::IggyRwLockFn, + NamedPageQuery, Page, locking::IggyRwLockFn, }; use iggy_common::{ConsumerGroupClient, UserClient}; @@ -43,6 +43,15 @@ super::with_client!(self, client => client.get_consumer_groups(stream_id, topic_id).await) } + async fn get_consumer_groups_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<ConsumerGroup>, IggyError> { + super::with_client!(self, client => client.get_consumer_groups_page(stream_id, topic_id, query).await) + } + async fn create_consumer_group( &self, stream_id: &Identifier,
diff --git a/core/sdk/src/clients/binary_partitions.rs b/core/sdk/src/clients/binary_partitions.rs index 256a271..89b90d9 100644 --- a/core/sdk/src/clients/binary_partitions.rs +++ b/core/sdk/src/clients/binary_partitions.rs
@@ -19,7 +19,7 @@ use async_trait::async_trait; use iggy_common::PartitionClient; use iggy_common::locking::IggyRwLockFn; -use iggy_common::{Identifier, IggyError}; +use iggy_common::{Identifier, IggyError, Page, PageQuery, Partition}; #[async_trait] impl PartitionClient for IggyClient { @@ -40,4 +40,13 @@ ) -> Result<(), IggyError> { super::with_client!(self, client => client.delete_partitions(stream_id, topic_id, partitions_count).await) } + + async fn get_partitions_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &PageQuery, + ) -> Result<Page<Partition>, IggyError> { + super::with_client!(self, client => client.get_partitions_page(stream_id, topic_id, query).await) + } }
diff --git a/core/sdk/src/clients/binary_streams.rs b/core/sdk/src/clients/binary_streams.rs index 16ac9fd..2659562 100644 --- a/core/sdk/src/clients/binary_streams.rs +++ b/core/sdk/src/clients/binary_streams.rs
@@ -19,7 +19,7 @@ use async_trait::async_trait; use iggy_common::StreamClient; use iggy_common::locking::IggyRwLockFn; -use iggy_common::{Identifier, IggyError, Stream, StreamDetails}; +use iggy_common::{Identifier, IggyError, NamedPageQuery, Page, Stream, StreamDetails}; use iggy_common::{StreamCreateOptions, StreamUpdateOptions}; #[async_trait] @@ -32,6 +32,10 @@ super::with_client!(self, client => client.get_streams().await) } + async fn get_streams_page(&self, query: &NamedPageQuery) -> Result<Page<Stream>, IggyError> { + super::with_client!(self, client => client.get_streams_page(query).await) + } + async fn create_stream( &self, name: &str,
diff --git a/core/sdk/src/clients/binary_topics.rs b/core/sdk/src/clients/binary_topics.rs index 92a7cec..a0bcf8f 100644 --- a/core/sdk/src/clients/binary_topics.rs +++ b/core/sdk/src/clients/binary_topics.rs
@@ -20,7 +20,8 @@ use iggy_common::TopicClient; use iggy_common::locking::IggyRwLockFn; use iggy_common::{ - Identifier, IggyError, Topic, TopicCreateOptions, TopicDetails, TopicUpdateOptions, + Identifier, IggyError, NamedPageQuery, Page, Topic, TopicCreateOptions, TopicDetails, + TopicUpdateOptions, }; #[async_trait] @@ -37,6 +38,14 @@ super::with_client!(self, client => client.get_topics(stream_id).await) } + async fn get_topics_page( + &self, + stream_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<Topic>, IggyError> { + super::with_client!(self, client => client.get_topics_page(stream_id, query).await) + } + async fn create_topic( &self, stream_id: &Identifier,
diff --git a/core/sdk/src/clients/binary_users.rs b/core/sdk/src/clients/binary_users.rs index 5ba389d..80cc079 100644 --- a/core/sdk/src/clients/binary_users.rs +++ b/core/sdk/src/clients/binary_users.rs
@@ -20,7 +20,8 @@ use iggy_common::UserClient; use iggy_common::locking::IggyRwLockFn; use iggy_common::{ - Identifier, IdentityInfo, IggyError, Permissions, UserInfo, UserInfoDetails, UserStatus, + Identifier, IdentityInfo, IggyError, NamedPageQuery, Page, Permissions, UserInfo, + UserInfoDetails, UserStatus, }; use iggy_common::{UserCreateOptions, UserUpdateOptions}; @@ -34,6 +35,10 @@ super::with_client!(self, client => client.get_users().await) } + async fn get_users_page(&self, query: &NamedPageQuery) -> Result<Page<UserInfo>, IggyError> { + super::with_client!(self, client => client.get_users_page(query).await) + } + async fn create_user( &self, username: &str,
diff --git a/core/sdk/src/http/consumer_groups.rs b/core/sdk/src/http/consumer_groups.rs index dc3e811..2afe3d9 100644 --- a/core/sdk/src/http/consumer_groups.rs +++ b/core/sdk/src/http/consumer_groups.rs
@@ -23,7 +23,7 @@ use iggy_common::ConsumerGroupClient; use iggy_common::Identifier; use iggy_common::create_consumer_group::CreateConsumerGroup; -use iggy_common::{ConsumerGroup, ConsumerGroupDetails}; +use iggy_common::{ConsumerGroup, ConsumerGroupDetails, NamedPageQuery, Page}; #[async_trait] impl ConsumerGroupClient for HttpClient { @@ -70,6 +70,25 @@ Ok(consumer_groups) } + async fn get_consumer_groups_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<ConsumerGroup>, IggyError> { + query.validate()?; + let response = self + .get_with_query( + &get_path(&stream_id.as_cow_str(), &topic_id.as_cow_str()), + &query.http_query_pairs(), + ) + .await?; + response + .json() + .await + .map_err(|_| IggyError::InvalidJsonResponse) + } + async fn create_consumer_group( &self, stream_id: &Identifier,
diff --git a/core/sdk/src/http/partitions.rs b/core/sdk/src/http/partitions.rs index e216003..55bfc4e 100644 --- a/core/sdk/src/http/partitions.rs +++ b/core/sdk/src/http/partitions.rs
@@ -20,9 +20,9 @@ use crate::http::path::encode_segment; use crate::prelude::{Identifier, IggyError}; use async_trait::async_trait; -use iggy_common::PartitionClient; use iggy_common::create_partitions::CreatePartitions; use iggy_common::delete_partitions::DeletePartitions; +use iggy_common::{Page, PageQuery, Partition, PartitionClient}; #[async_trait] impl PartitionClient for HttpClient { @@ -63,6 +63,25 @@ self.send_contexts.invalidate_topic_discovery(); Ok(()) } + + async fn get_partitions_page( + &self, + stream_id: &Identifier, + topic_id: &Identifier, + query: &PageQuery, + ) -> Result<Page<Partition>, IggyError> { + query.validate()?; + let response = self + .get_with_query( + &get_path(&stream_id.as_cow_str(), &topic_id.as_cow_str()), + &query.http_query_pairs(), + ) + .await?; + response + .json() + .await + .map_err(|_| IggyError::InvalidJsonResponse) + } } fn get_path(stream_id: &str, topic_id: &str) -> String {
diff --git a/core/sdk/src/http/streams.rs b/core/sdk/src/http/streams.rs index cc7801d..1afdd00 100644 --- a/core/sdk/src/http/streams.rs +++ b/core/sdk/src/http/streams.rs
@@ -23,7 +23,8 @@ use async_trait::async_trait; use iggy_common::create_stream::CreateStream; use iggy_common::{ - OptionInputMap, Stream, StreamClient, StreamCreateOptions, StreamDetails, StreamUpdateOptions, + NamedPageQuery, OptionInputMap, Page, Stream, StreamClient, StreamCreateOptions, StreamDetails, + StreamUpdateOptions, }; const PATH: &str = "/streams"; @@ -56,6 +57,15 @@ Ok(streams) } + async fn get_streams_page(&self, query: &NamedPageQuery) -> Result<Page<Stream>, IggyError> { + query.validate()?; + let response = self.get_with_query(PATH, &query.http_query_pairs()).await?; + response + .json() + .await + .map_err(|_| IggyError::InvalidJsonResponse) + } + async fn create_stream( &self, name: &str,
diff --git a/core/sdk/src/http/topics.rs b/core/sdk/src/http/topics.rs index 496caa8..a3c9506 100644 --- a/core/sdk/src/http/topics.rs +++ b/core/sdk/src/http/topics.rs
@@ -22,8 +22,8 @@ use async_trait::async_trait; use iggy_common::create_topic::CreateTopic; use iggy_common::{ - DEFAULT_PARTITIONS_COUNT, OptionInputMap, Topic, TopicClient, TopicCreateOptions, TopicDetails, - TopicUpdateOptions, + DEFAULT_PARTITIONS_COUNT, NamedPageQuery, OptionInputMap, Page, Topic, TopicClient, + TopicCreateOptions, TopicDetails, TopicUpdateOptions, }; #[async_trait] @@ -49,6 +49,24 @@ Ok(topics) } + async fn get_topics_page( + &self, + stream_id: &Identifier, + query: &NamedPageQuery, + ) -> Result<Page<Topic>, IggyError> { + query.validate()?; + let response = self + .get_with_query( + &get_path(&stream_id.as_cow_str()), + &query.http_query_pairs(), + ) + .await?; + response + .json() + .await + .map_err(|_| IggyError::InvalidJsonResponse) + } + async fn create_topic( &self, stream_id: &Identifier,
diff --git a/core/sdk/src/http/users.rs b/core/sdk/src/http/users.rs index 18f340a..d08cfde 100644 --- a/core/sdk/src/http/users.rs +++ b/core/sdk/src/http/users.rs
@@ -25,8 +25,8 @@ use iggy_common::login_user::LoginUser; use iggy_common::update_permissions::UpdatePermissions; use iggy_common::{ - IdentityInfo, OptionInputMap, Permissions, UserClient, UserCreateOptions, UserInfo, - UserInfoDetails, UserStatus, UserUpdateOptions, + IdentityInfo, NamedPageQuery, OptionInputMap, Page, Permissions, UserClient, UserCreateOptions, + UserInfo, UserInfoDetails, UserStatus, UserUpdateOptions, }; use secrecy::SecretString; @@ -60,6 +60,15 @@ Ok(users) } + async fn get_users_page(&self, query: &NamedPageQuery) -> Result<Page<UserInfo>, IggyError> { + query.validate()?; + let response = self.get_with_query(PATH, &query.http_query_pairs()).await?; + response + .json() + .await + .map_err(|_| IggyError::InvalidJsonResponse) + } + async fn create_user( &self, username: &str,
diff --git a/core/sdk/src/links/fake_cluster.rs b/core/sdk/src/links/fake_cluster.rs index 08f5b2c..14b6cdd 100644 --- a/core/sdk/src/links/fake_cluster.rs +++ b/core/sdk/src/links/fake_cluster.rs
@@ -36,7 +36,7 @@ use iggy_binary_protocol::requests::messages::FetchMessagesRequest; use iggy_binary_protocol::requests::users::LoginRegisterRequest; use iggy_binary_protocol::responses::messages::PartitionRouteResponse; -use iggy_binary_protocol::responses::streams::get_stream::TopicHeader; +use iggy_binary_protocol::responses::streams::get_stream::TopicResponse; use iggy_binary_protocol::responses::system::{ClusterMetadataResponse, ClusterNodeResponse}; use iggy_binary_protocol::responses::topics::{GetTopicResponse, PartitionResponse}; use iggy_binary_protocol::responses::users::LoginRegisterResponse; @@ -522,7 +522,7 @@ pub(crate) fn topic_body(partitions_count: u32) -> Vec<u8> { GetTopicResponse { - topic: TopicHeader { + topic: TopicResponse { id: 1, created_at: 0, partitions_count,
diff --git a/core/sdk/src/prelude.rs b/core/sdk/src/prelude.rs index 345322b..31e6ece 100644 --- a/core/sdk/src/prelude.rs +++ b/core/sdk/src/prelude.rs
@@ -79,6 +79,10 @@ TopicClient, UserClient, }; pub use iggy_common::{ + DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT, NamedPageQuery, PAGE_CURSOR_PREFIX, Page, PageCursor, + PageOrder, PageQuery, +}; +pub use iggy_common::{ DEFAULT_POLL_MAX_BYTES, IGGY_MESSAGE_CHECKSUM_OFFSET_RANGE, IGGY_MESSAGE_HEADER_SIZE, IGGY_MESSAGE_HEADERS_LENGTH_OFFSET_RANGE, IGGY_MESSAGE_ID_OFFSET_RANGE, IGGY_MESSAGE_OFFSET_OFFSET_RANGE, IGGY_MESSAGE_ORIGIN_TIMESTAMP_OFFSET_RANGE,
diff --git a/core/server/Cargo.toml b/core/server/Cargo.toml index e4652bb..fe9fec3 100644 --- a/core/server/Cargo.toml +++ b/core/server/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "server" -version = "0.10.0" +version = "0.10.1-edge.1" edition = "2024" license = "Apache-2.0" publish = false
diff --git a/core/server/README.md b/core/server/README.md index cabe286..b66d4f5 100644 --- a/core/server/README.md +++ b/core/server/README.md
@@ -595,6 +595,30 @@ A stream created during phase 1 also carries a wrap under the old key until phase 2 drops it. Rotation changes only the wraps, so whoever already holds a stream's data key, or an old wrap together with the old server key, can still read that stream. Changing a stream's own data key is not supported. +## List pages + +The binary list commands answer one page at a time: `GetUsers` (32), `GetStreams` (201), `GetTopics` (301), `GetPartitions` (404) and `GetConsumerGroups` (601). Each request ends with a page block. The block holds the order (`id` or `created`), a descending flag and a limit from 1 to 1000. It can also hold a cursor and a name filter. The server refuses a request without the block, or with a value out of range, with `InvalidCommand` (3). + +On the command line, `iggy stream list`, `iggy topic list`, `iggy partition list`, `iggy consumer-group list` and `iggy user list` read pages. They take `--desc`, `--limit` and `--after`, and all but `iggy partition list` also take `--sort` and `--name`. + +The `created` order sorts by creation time and then by id, so entities created at the same time keep a fixed order. Partitions and consumer groups walk by id in both orders, because their ids follow creation. The name filter keeps the entries whose name holds the text, case-sensitive. A partition has no name, so the server refuses `GetPartitions` with a name. + +A page ends at its limit, before its items pass 1 MiB, or after the walk passes 65536 entries. The first item always fits, so every read moves forward. A page can hold fewer items than the limit, or none, and still carry a `next` cursor. Read pages until `next` is absent. Cursors print as `pg1_` tokens. A cursor holds only a position, so send it back with the same order, direction, filter and parent. + +Each page is a separate read of one node. An entity that exists during the whole walk and matches the filter appears exactly once. An entity that someone creates or deletes during the walk can appear or not appear, so a walk is not a snapshot. Use `GetMetadataChanges` for an exact copy. If the pages of one walk come from different nodes, a later page can come from an older state. Over HTTP, `consistency=linearizable` sends every page read to the primary. + +`GetTopics` for a stream that does not exist answers an empty last page if the request has no cursor. With a cursor, it answers `StreamIdNotFound` (1009), because the stream was deleted during the walk. `GetPartitions` and `GetConsumerGroups` answer the not-found error of the missing stream or topic. + +Over HTTP, four routes take the page keys `order`, `descending`, `limit`, `cursor` and `name`, next to `consistency`. They are `GET /streams`, `GET /streams/{stream_id}/topics`, `GET /streams/{stream_id}/topics/{topic_id}/consumer-groups` and `GET /users`. If the query has `limit` or `cursor`, the route returns one page as `{"items": [...], "next": "pg1_..."}`, and the last page has no `next`. + +Without `limit` and `cursor`, these four routes return a bare array of every item. The array follows `order` and `descending` and holds only the items that match `name`. The server builds that array from pages of 1000, so it is not one consistent read either. `GET /streams/{stream_id}/topics/{topic_id}/partitions` always returns a page. + +The server refuses an unknown, repeated or malformed query key with 400. The list routes of server 0.10.0 ignored an unknown key, for example the cache buster `?_=1699`, so a client that sends one now gets 400. + +The cap `MAX_RECORD_REPLY_SIZE` is a little over 64 MB. If the binary reply frame of `GetClients` or of a metadata read passes it, the server answers with `ReplyTooLarge` (97). The metadata reads are those of streams, topics, partitions, consumer groups, users, options, stats and cluster metadata. The connection stays open. A page stays far below that cap. `GetStream`, `GetTopic` and `GetClients` can pass it on a very large catalog. + +`GetSnapshot` does not use this cap. It refuses an archive frame above 64 MiB, the frame limit of the message bus, with `SnapshotFileCompletionFailed`. HTTP replies have no such cap. + ## Metadata changes Each node keeps a bounded log of the public results of committed metadata operations: streams, topics, partition counts, consumer groups and their members, users, personal access tokens and sessions. One operation can produce several records, for example a stream delete followed by the permission updates that pruned grants on it. Refused, denied and no-op operations produce none. Records are produced by the state machine on every replica alike, so a cursor taken on one node continues on another.
diff --git a/core/server/src/dispatch/authz.rs b/core/server/src/dispatch/authz.rs index 497ebbc..8b7be1f 100644 --- a/core/server/src/dispatch/authz.rs +++ b/core/server/src/dispatch/authz.rs
@@ -31,12 +31,14 @@ use consensus::client_table::SessionAttachment; use iggy_binary_protocol::codes::{ DESCRIBE_OPTIONS_CODE, GET_CLUSTER_METADATA_CODE, GET_CONSUMER_GROUP_CODE, - GET_CONSUMER_GROUPS_CODE, GET_PERSONAL_ACCESS_TOKENS_CODE, GET_STATS_CODE, GET_STREAM_CODE, - GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE, GET_USERS_CODE, + GET_CONSUMER_GROUPS_CODE, GET_PARTITIONS_CODE, GET_PERSONAL_ACCESS_TOKENS_CODE, GET_STATS_CODE, + GET_STREAM_CODE, GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE, + GET_USERS_CODE, }; use iggy_binary_protocol::requests::consumer_groups::{ GetConsumerGroupRequest, GetConsumerGroupsRequest, }; +use iggy_binary_protocol::requests::partitions::GetPartitionsRequest; use iggy_binary_protocol::requests::streams::GetStreamRequest; use iggy_binary_protocol::requests::topics::{GetTopicRequest, GetTopicsRequest}; use iggy_binary_protocol::requests::users::GetUserRequest; @@ -360,6 +362,14 @@ |request| (&request.stream_id, &request.topic_id), Permissioner::get_topic, ), + // A partitions page shows what GetTopic shows about each partition. + GET_PARTITIONS_CODE => gate_topic_scoped::<GetPartitionsRequest, _, _, _, _>( + shard, + user_id, + body, + |request| (&request.stream_id, &request.topic_id), + Permissioner::get_topic, + ), GET_CONSUMER_GROUP_CODE => gate_topic_scoped::<GetConsumerGroupRequest, _, _, _, _>( shard, user_id, @@ -591,6 +601,7 @@ (GET_STREAMS_CODE, unauthenticated, allow), (GET_TOPIC_CODE, allow, allow), (GET_TOPICS_CODE, allow, allow), + (GET_PARTITIONS_CODE, allow, allow), (GET_CONSUMER_GROUP_CODE, allow, allow), (GET_CONSUMER_GROUPS_CODE, allow, allow), (SYNC_CONSUMER_GROUP_CODE, invalid_command, invalid_command),
diff --git a/core/server/src/dispatch/fetch.rs b/core/server/src/dispatch/fetch.rs index f66023a..c6665c7 100644 --- a/core/server/src/dispatch/fetch.rs +++ b/core/server/src/dispatch/fetch.rs
@@ -1183,7 +1183,9 @@ }; use iggy_binary_protocol::responses::messages::poll_messages::POLL_RESPONSE_HEADER_SIZE; use iggy_binary_protocol::responses::messages::{FetchMessagesResponse, FetchMessagesSection}; - use iggy_binary_protocol::{Operation, ReplyHeader, WireConsumer, WireEncode, WireIdentifier}; + use iggy_binary_protocol::{ + MAX_RECORD_REPLY_SIZE, Operation, ReplyHeader, WireConsumer, WireEncode, WireIdentifier, + }; use iggy_common::defaults::DEFAULT_ROOT_USER_ID; use iggy_common::{Aes256GcmEncryptor, PollingKind}; use message_bus::MessageBus; @@ -3546,6 +3548,7 @@ address: None, metadata_watermark: 0, }, + MAX_RECORD_REPLY_SIZE, ) .await; }
diff --git a/core/server/src/dispatch/mod.rs b/core/server/src/dispatch/mod.rs index 2fb5018..e969827 100644 --- a/core/server/src/dispatch/mod.rs +++ b/core/server/src/dispatch/mod.rs
@@ -75,8 +75,8 @@ use iggy_binary_protocol::requests::system::SessionIdentity; use iggy_binary_protocol::requests::users::login_register::BindSecret; use iggy_binary_protocol::{ - EvictionReason, GenericHeader, HEADER_SIZE, Operation, RequestHeader, RoutedRequestHeader, - WireDecode, + EvictionReason, GenericHeader, HEADER_SIZE, MAX_RECORD_REPLY_SIZE, Operation, RequestHeader, + RoutedRequestHeader, WireDecode, }; use iggy_common::{IggyError, UserStatus}; use journal::superblock::SuperblockStore; @@ -1029,6 +1029,7 @@ origin, request, context, + MAX_RECORD_REPLY_SIZE, ) .await; return; @@ -1051,6 +1052,7 @@ origin, request, context, + MAX_RECORD_REPLY_SIZE, ) .await; }); @@ -1392,10 +1394,10 @@ use consensus::client_table::bind_verifier; use iggy_binary_protocol::Command; use iggy_binary_protocol::codes::{ - FETCH_MESSAGES_CODE, GET_CLIENT_CODE, GET_CLIENTS_CODE, GET_CLUSTER_METADATA_CODE, - GET_CONSUMER_OFFSET_CODE, GET_ME_CODE, GET_METADATA_CHANGES_CODE, GET_PARTITION_ROUTE_CODE, - GET_STATS_CODE, POLL_MESSAGES_CODE, POLL_MESSAGES_DEFERRED_CODE, - STORE_CONSUMER_OFFSET_CODE, + DESCRIBE_OPTIONS_CODE, FETCH_MESSAGES_CODE, GET_CLIENT_CODE, GET_CLIENTS_CODE, + GET_CLUSTER_METADATA_CODE, GET_CONSUMER_OFFSET_CODE, GET_ME_CODE, + GET_METADATA_CHANGES_CODE, GET_PARTITION_ROUTE_CODE, GET_STATS_CODE, POLL_MESSAGES_CODE, + POLL_MESSAGES_DEFERRED_CODE, STORE_CONSUMER_OFFSET_CODE, }; use iggy_binary_protocol::dispatch::lookup_command; use iggy_binary_protocol::primitives::metadata_changes::WireMetadataChangeStatus; @@ -1413,8 +1415,9 @@ CreateStreamRequest, UpdateStreamResolvedRequest, }; use iggy_binary_protocol::requests::system::{ - BindSessionRequest, GetClientRequest, GetClientsRequest, GetMetadataChangesRequest, - GetStatsRequest, ResourceTarget, UpdateResourceRequest, + BindSessionRequest, DescribeOptionsRequest, GetClientRequest, GetClientsRequest, + GetMetadataChangesRequest, GetStatsRequest, OPTIONS_SCOPE_TOPIC, ResourceTarget, + UpdateResourceRequest, }; use iggy_binary_protocol::requests::topics::{DeleteTopicRequest, UpdateTopicResolvedRequest}; use iggy_binary_protocol::requests::users::login_register::{ @@ -2034,6 +2037,100 @@ .await; } + /// `GetClients` and the reads of `build_non_replicated_response` answer a + /// reply frame above the cap with a bare `ReplyTooLarge`, and the same + /// read under the cap still answers on that connection. + #[compio::test] + async fn given_a_reply_above_the_cap_when_reading_should_refuse_it_and_keep_the_connection() { + let describe_options = DescribeOptionsRequest { + scope: OPTIONS_SCOPE_TOPIC, + }; + for (code, body) in [ + (GET_CLIENTS_CODE, GetClientsRequest.to_bytes()), + (DESCRIBE_OPTIONS_CODE, describe_options.to_bytes()), + ] { + let bus = SpyBus::default(); + let mut shard = test_shard(&bus, 0, 1, FIRST_BOOT); + let (sender, shard_inbox, _shard_replies) = shard_channel(0, 1, 1); + shard.attach_senders(vec![sender]); + let shard = Rc::new(shard); + shard + .plane + .metadata() + .mux_stm + .users() + .ensure_root_user("iggy", "hash"); + let sessions = bind_reader_session(&shard).await; + let server_config = Arc::new(ServerConfig::default()); + for reply_cap in [HEADER_SIZE, MAX_RECORD_REPLY_SIZE] { + let context = sessions + .borrow_mut() + .touch_connection(READER_TRANSPORT, true, std::time::Instant::now()) + .unwrap(); + let request = request_message( + Operation::NonReplicated, + READER_CLIENT, + READER_SESSION, + 1, + &body, + ) + .transmute_header(|old, header: &mut RoutedRequestHeader| { + *header = old; + header.reserved[..4].copy_from_slice(&code.to_le_bytes()); + }); + let mut read = Box::pin(handle_non_replicated_request( + &shard, + &sessions, + &server_config, + ClientOrigin::capture(&shard.bus, READER_TRANSPORT), + request, + context, + reply_cap, + )); + if code == GET_CLIENTS_CODE { + assert!(futures::poll!(read.as_mut()).is_pending()); + let Ok(ShardFrame::Lifecycle(LifecycleFrame::ListClients { + reply: ListClientsReply::Clients(reply), + })) = shard_inbox.try_recv() + else { + panic!("GetClients must ask the shard for its clients"); + }; + let reader = sessions.borrow().client_record(READER_TRANSPORT).unwrap(); + reply.try_send(vec![reader]).unwrap(); + } + read.await; + } + await_replies(&bus, 2).await; + let replies: Vec<_> = bus + .client_replies + .borrow() + .iter() + .map(|(client, frame)| { + ( + *client, + frame_command(frame), + reply_status(frame), + frame.len() > HEADER_SIZE, + ) + }) + .collect(); + let reply = Command::Reply as u8; + assert_eq!( + replies, + [ + ( + READER_TRANSPORT, + reply, + IggyError::ReplyTooLarge.as_code(), + false + ), + (READER_TRANSPORT, reply, 0, true), + ], + "code {code}: a refusal without a body, then the reply under the cap" + ); + } + } + /// Every read that asks another shard before it answers: the client reads /// ask every shard, the rest ask the owner of the partition. fn shard_waiting_reads() -> [(u32, Bytes); 6] {
diff --git a/core/server/src/dispatch/reads.rs b/core/server/src/dispatch/reads.rs index 56caf1c..0bebc88 100644 --- a/core/server/src/dispatch/reads.rs +++ b/core/server/src/dispatch/reads.rs
@@ -368,6 +368,9 @@ Ok(()) } +/// `reply_cap` is the largest reply frame a client accepts, see +/// [`deny_oversized_reply`]. Outside tests it is +/// [`MAX_RECORD_REPLY_SIZE`](iggy_binary_protocol::MAX_RECORD_REPLY_SIZE). #[allow(clippy::future_not_send, clippy::too_many_lines)] pub(in crate::dispatch) async fn handle_non_replicated_request<B, MJ, S, SB>( shard: &Rc<ShellShard<B, MJ, S, SB>>, @@ -388,6 +391,7 @@ address: client_address, metadata_watermark: watermark, }: ConnectionContext, + reply_cap: usize, ) where B: ShellBus, MJ: JournalHandle + 'static, @@ -460,17 +464,21 @@ send_non_replicated_deny(shard, &request, origin, error.as_code()).await; return; } - let response = GetClientsResponse { + let body = GetClientsResponse { clients: infos .iter() .map(|info| connected_client_to_response(shard, info)) .collect(), - }; + } + .to_bytes(); + if deny_oversized_reply(shard, &request, origin, code, body.len(), reply_cap).await { + return; + } send_non_replicated_bytes( shard, &request, origin, - response.to_bytes(), + body, FrameChannel::Reply, "get_clients", ) @@ -651,6 +659,7 @@ } handle_default_non_replicated( shard, origin, code, &request, user_id, attachment, watermark, &roster, client_ip, + reply_cap, ) .await; } @@ -1018,6 +1027,7 @@ watermark: u64, roster: &ClusterRoster, client_ip: Option<IpAddr>, + reply_cap: usize, ) where B: ShellBus, MJ: JournalHandle + 'static, @@ -1083,6 +1093,11 @@ ) }) { Ok(response) => { + if deny_oversized_reply(shard, request, origin, code, response.body_len(), reply_cap) + .await + { + return; + } let commit = current_metadata_commit(shard); let reply = response.into_reply( request.header(), @@ -1115,6 +1130,50 @@ } } +/// Sends `ReplyTooLarge` in place of a reply whose frame passes `reply_cap` +/// and returns `true`. The QUIC and WebSocket links of the Rust SDK refuse a +/// frame above [`MAX_RECORD_REPLY_SIZE`](iggy_binary_protocol::MAX_RECORD_REPLY_SIZE) +/// by default and drop the connection, so the typed error keeps the link of +/// every client. +/// +/// Only `GetClients` and the reads of `build_non_replicated_response` pass +/// this check. `GetSnapshot` checks a cap of its own, and `GetMetadataChanges` +/// pages under a budget of its own. HTTP replies do not pass this check, +/// because HTTP has no such cap. +#[allow(clippy::future_not_send)] +async fn deny_oversized_reply<B, MJ, S, SB>( + shard: &Rc<ShellShard<B, MJ, S, SB>>, + request: &Message<RoutedRequestHeader>, + origin: ClientOrigin, + code: u32, + body_len: usize, + reply_cap: usize, +) -> bool +where + B: ShellBus, + MJ: JournalHandle + 'static, + MJ::Target: Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>, + S: 'static, + SB: SuperblockStore + 'static, +{ + if reply_frame_fits(body_len, reply_cap) { + return false; + } + warn!( + transport_client_id = origin.id, + code, + frame_size = HEADER_SIZE.saturating_add(body_len), + max = reply_cap, + "reply exceeds the client reply limit; refusing to send" + ); + send_non_replicated_deny(shard, request, origin, IggyError::ReplyTooLarge.as_code()).await; + true +} + +const fn reply_frame_fits(body_len: usize, cap: usize) -> bool { + HEADER_SIZE.saturating_add(body_len) <= cap +} + /// Serve `GET_SNAPSHOT_FILE`: gate on the snapshot rule (`manage_servers`, /// since the archive dumps server logs and host diagnostics), then await the /// off-thread collection (see `snapshot::collect`), gate again, and reply @@ -1268,9 +1327,10 @@ mod tests { use super::{ FrontierUnreached, FrontierWait, MIN_DEFERRED_POLL_REPLY_MARGIN_US, hold_for_frontier, - read_frontier_budget, read_needs_metadata_frontier, remaining_timers, + read_frontier_budget, read_needs_metadata_frontier, remaining_timers, reply_frame_fits, }; use configs::server::ServerConfig; + use iggy_binary_protocol::HEADER_SIZE; use iggy_binary_protocol::codes::{ CANCEL_DEFERRED_REQUEST_CODE, DESCRIBE_OPTIONS_CODE, FETCH_MESSAGES_CODE, GET_CLUSTER_METADATA_CODE, GET_CONSUMER_OFFSET_CODE, GET_ME_CODE, GET_SNAPSHOT_FILE_CODE, @@ -1451,4 +1511,13 @@ "a frame that outlived its timeout is not served" ); } + + #[test] + fn given_a_reply_frame_at_the_cap_when_sized_should_fit_and_one_byte_more_should_not() { + let cap = HEADER_SIZE + 10; + assert!(reply_frame_fits(10, cap)); + assert!(!reply_frame_fits(11, cap)); + assert!(reply_frame_fits(0, HEADER_SIZE)); + assert!(!reply_frame_fits(0, HEADER_SIZE - 1)); + } }
diff --git a/core/server/src/http.rs b/core/server/src/http.rs index 0846e37..678e94f 100644 --- a/core/server/src/http.rs +++ b/core/server/src/http.rs
@@ -73,8 +73,8 @@ create_user, delete_cg, delete_consumer_offset, delete_partitions, delete_pat, delete_pat_named_login, delete_segments, delete_stream, delete_topic, delete_user, describe_options, get_cg, get_cgs, get_client, get_clients, get_cluster_metadata, - get_consumer_offset, get_metadata_changes, get_pats, get_snapshot, get_stats, get_stream, - get_streams, get_topic, get_topics, get_user, get_users, login_user, + get_consumer_offset, get_metadata_changes, get_partitions, get_pats, get_snapshot, get_stats, + get_stream, get_streams, get_topic, get_topics, get_user, get_users, login_user, login_with_personal_access_token, logout_user, ping, poll_messages, poll_messages_committing, poll_messages_deferred, refresh_token, send_messages, store_consumer_offset, update_permissions, update_stream, update_topic, update_user, @@ -530,7 +530,9 @@ ) .route( "/streams/{stream_id}/topics/{topic_id}/partitions", - post(create_partitions).delete(delete_partitions), + get(get_partitions) + .post(create_partitions) + .delete(delete_partitions), ) .route( "/streams/{stream_id}/topics/{topic_id}/partitions/{partition_id}",
diff --git a/core/server/src/http/error.rs b/core/server/src/http/error.rs index 921d148..d8fca1b 100644 --- a/core/server/src/http/error.rs +++ b/core/server/src/http/error.rs
@@ -28,6 +28,7 @@ use configs::cluster::ResolvedClusterNode; use iggy_binary_protocol::Operation; use iggy_common::IggyError; +use serde::de::IntoDeserializer; use serde::{Deserialize, Serialize}; use thiserror::Error; use tracing::error; @@ -482,6 +483,33 @@ pub(in crate::http) consistency: Consistency, } +const CONSISTENCY_KEY: &str = "consistency"; + +/// The page keys of a list query, for the strict parser of `PageQuery`. +pub(in crate::http) type PagePairs<'a> = Vec<(&'a str, &'a str)>; + +/// Split the query of a list route into its read consistency and its page +/// keys. A repeated or unknown `consistency` value is refused. +pub(in crate::http) fn split_list_query( + pairs: &[(String, String)], +) -> Result<(Consistency, PagePairs<'_>), IggyError> { + let mut consistency = None; + let mut page_pairs = Vec::with_capacity(pairs.len()); + for (key, value) in pairs { + if key != CONSISTENCY_KEY { + page_pairs.push((key.as_str(), value.as_str())); + continue; + } + if consistency.is_some() { + return Err(IggyError::InvalidCommand); + } + let parsed: Result<Consistency, serde::de::value::Error> = + Consistency::deserialize(value.as_str().into_deserializer()); + consistency = Some(parsed.map_err(|_| IggyError::InvalidCommand)?); + } + Ok((consistency.unwrap_or_default(), page_pairs)) +} + /// Produce acknowledgement selected by the `?ack=` query param. /// /// `replicated` (the default) answers 201 only after the partition group's
diff --git a/core/server/src/http/handlers.rs b/core/server/src/http/handlers.rs index 9eb38a3..ea01a27 100644 --- a/core/server/src/http/handlers.rs +++ b/core/server/src/http/handlers.rs
@@ -34,17 +34,18 @@ use iggy_binary_protocol::codes::{ DESCRIBE_OPTIONS_CODE, GET_CLIENT_CODE, GET_CLIENTS_CODE, GET_CONSUMER_GROUP_CODE, GET_CONSUMER_GROUPS_CODE, GET_CONSUMER_OFFSET_CODE, GET_METADATA_CHANGES_CODE, - GET_PERSONAL_ACCESS_TOKENS_CODE, GET_SNAPSHOT_FILE_CODE, GET_STATS_CODE, GET_STREAM_CODE, - GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE, GET_USERS_CODE, - POLL_MESSAGES_CODE, + GET_PARTITIONS_CODE, GET_PERSONAL_ACCESS_TOKENS_CODE, GET_SNAPSHOT_FILE_CODE, GET_STATS_CODE, + GET_STREAM_CODE, GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE, + GET_USERS_CODE, POLL_MESSAGES_CODE, }; +use iggy_binary_protocol::primitives::page::WirePageQuery; use iggy_binary_protocol::primitives::partition_history::PartitionContext; use iggy_binary_protocol::requests::consumer_groups::{ CreateConsumerGroupRequest, DeleteConsumerGroupRequest, GetConsumerGroupRequest, GetConsumerGroupsRequest, }; use iggy_binary_protocol::requests::partitions::{ - CreatePartitionsRequest, DeletePartitionsRequest, + CreatePartitionsRequest, DeletePartitionsRequest, GetPartitionsRequest, }; use iggy_binary_protocol::requests::personal_access_tokens::{ CreatePersonalAccessTokenRequest, DeletePersonalAccessTokenRequest, @@ -64,20 +65,20 @@ ChangePasswordRequest, CreateUserRequest, DeleteUserRequest, GetUserRequest, GetUsersRequest, UpdatePermissionsRequest, }; +use iggy_binary_protocol::responses::PageResponse; use iggy_binary_protocol::responses::clients::client_response::ConsumerGroupInfoResponse; use iggy_binary_protocol::responses::clients::get_client::ClientDetailsResponse; use iggy_binary_protocol::responses::clients::get_clients::GetClientsResponse; +use iggy_binary_protocol::responses::consumer_groups::ConsumerGroupResponse; use iggy_binary_protocol::responses::consumer_groups::get_consumer_group::ConsumerGroupDetailsResponse; -use iggy_binary_protocol::responses::consumer_groups::get_consumer_groups::GetConsumerGroupsResponse; use iggy_binary_protocol::responses::personal_access_tokens::GetPersonalAccessTokensResponse; use iggy_binary_protocol::responses::streams::get_stream::GetStreamResponse; -use iggy_binary_protocol::responses::streams::get_streams::GetStreamsResponse; +use iggy_binary_protocol::responses::streams::{StreamResponse, TopicResponse}; use iggy_binary_protocol::responses::system::DescribeOptionsResponse; use iggy_binary_protocol::responses::system::get_stats::StatsResponse; -use iggy_binary_protocol::responses::topics::get_topic::GetTopicResponse; -use iggy_binary_protocol::responses::topics::get_topics::GetTopicsResponse; +use iggy_binary_protocol::responses::topics::get_topic::{GetTopicResponse, PartitionResponse}; +use iggy_binary_protocol::responses::users::UserResponse; use iggy_binary_protocol::responses::users::get_user::UserDetailsResponse; -use iggy_binary_protocol::responses::users::get_users::GetUsersResponse; use iggy_binary_protocol::{Operation, WireDecode, WireEncode, WireIdentifier, WireName}; use iggy_common::change_password::ChangePassword; use iggy_common::create_consumer_group::CreateConsumerGroup; @@ -96,24 +97,24 @@ use iggy_common::store_consumer_offset::StoreConsumerOffset; use iggy_common::update_permissions::UpdatePermissions; use iggy_common::wire_conversions::{ - clients_from_wire, consumer_groups_from_wire, identifier_to_wire, option_specs_from_wire, - permissions_to_wire, personal_access_tokens_from_wire, streams_from_wire, topics_from_wire, - users_from_wire, + clients_from_wire, identifier_to_wire, option_specs_from_wire, page_from_wire, + permissions_to_wire, personal_access_tokens_from_wire, }; use iggy_common::{ ClientInfo, ClientInfoDetails, ClusterMetadata, Consumer, ConsumerGroup, ConsumerGroupDetails, ConsumerOffsetInfo, DEFAULT_MAX_TOPIC_SIZE, Identifier, IdentityInfo, IggyError, IggyTimestamp, - MetadataChanges, MetadataChangesQuery, OptionSpec, OptionStorage, OptionsScope, Partitioning, - PersonalAccessTokenInfo, PollMessages, PolledMessages, PollingStrategy, RawPersonalAccessToken, - SendMessagesConfirmations, Stats, Stream, StreamDetails, TokenInfo, Topic, TopicDetails, - UserInfo, UserInfoDetails, Validatable, descriptors_for, erase_buffer, + MetadataChanges, MetadataChangesQuery, NamedPageQuery, OptionSpec, OptionStorage, OptionsScope, + Page, PageQuery, Partition, Partitioning, PersonalAccessTokenInfo, PollMessages, + PolledMessages, PollingStrategy, RawPersonalAccessToken, SendMessagesConfirmations, Stats, + Stream, StreamDetails, TokenInfo, Topic, TopicDetails, UserInfo, UserInfoDetails, Validatable, + descriptors_for, erase_buffer, }; use metadata::impls::metadata::StreamsFrontend; use metadata::permissioner::Permissioner; use secrecy::zeroize::Zeroizing; use secrecy::{ExposeSecret, SecretString}; use send_wrapper::SendWrapper; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use shard::{ DeferredPollContext, DeferredPollRequest, PartitionRead, PartitionReadReply, PollQuotaIdentity, }; @@ -127,7 +128,7 @@ use crate::dispatch::session_ops::{verify_login_credentials, verify_pat_credentials}; use crate::http::error::{ Consistency, ConsistencyQuery, CustomError, PartitionWriteError, ProduceAck, ProduceQuery, - ReadError, WriteError, + ReadError, WriteError, split_list_query, }; use crate::http::extractor::{ Authenticated, Credential, Identity, JsonMembers, JsonSendMessages, JsonUpdate, @@ -140,8 +141,8 @@ use crate::http::reads::{ authorize_data_plane, authorize_read, await_metadata_floor, await_recovery_barrier, check_partition_freshness, check_partition_incarnation, gate_local_read, read_local, - resolve_gate_stream, resolve_gate_topic, resolve_gate_topic_ids, resolve_gate_user, - topic_durability, + read_whole_list, resolve_gate_stream, resolve_gate_topic, resolve_gate_topic_ids, + resolve_gate_user, topic_durability, }; use crate::http::reply::{ committed_payload, decode_consumer_group_details, decode_raw_pat_token, decode_stream_details, @@ -317,28 +318,23 @@ )) } -/// `GET /streams`: list every stream as the same `Vec<Stream>` JSON the legacy -/// server returns. A consensus-free local STM read via [`read_local`]. +/// `GET /streams`: every stream as the `Vec<Stream>` JSON of the legacy +/// server, or one page of them. See [`read_list`]. pub(in crate::http) async fn get_streams( State(state): State<HttpState>, identity: Identity, - Query(query): Query<ConsistencyQuery>, -) -> Result<Json<Vec<Stream>>, ReadError> { - let body = GetStreamsRequest.to_bytes(); - let bytes = SendWrapper::new(read_local( + Query(pairs): Query<Vec<(String, String)>>, +) -> Result<Json<ListReply<Stream>>, ReadError> { + SendWrapper::new(read_list::<StreamResponse, _>( &state, &identity, - query.consistency, + &pairs, GET_STREAMS_CODE, - &body, + |page| GetStreamsRequest { page }.to_bytes(), Permissioner::get_streams, + Stream::try_from, )) - .await?; - let response = GetStreamsResponse::decode_from(&bytes) - .map_err(|_| ReadError::Rejected(IggyError::InvalidCommand))?; - Ok(Json( - streams_from_wire(response).map_err(ReadError::Rejected)?, - )) + .await } /// `GET /streams/{stream_id}`: fetch one stream by numeric id or name as the @@ -380,38 +376,36 @@ )) } -/// `GET /streams/{stream_id}/topics`: list a stream's topics as the same -/// `Vec<Topic>` JSON the legacy server returns. A consensus-free local STM read -/// via [`read_local`]. +/// `GET /streams/{stream_id}/topics`: every topic of a stream as the +/// `Vec<Topic>` JSON of the legacy server, or one page of them. See +/// [`read_list`]. pub(in crate::http) async fn get_topics( State(state): State<HttpState>, identity: Identity, Path(stream_id): Path<String>, - Query(query): Query<ConsistencyQuery>, -) -> Result<Json<Vec<Topic>>, ReadError> { + Query(pairs): Query<Vec<(String, String)>>, +) -> Result<Json<ListReply<Topic>>, ReadError> { let stream_id = Identifier::from_str_value(&stream_id).map_err(ReadError::Rejected)?; - let wire_stream_id = identifier_to_wire(&stream_id).map_err(ReadError::Rejected)?; - let request = GetTopicsRequest { - stream_id: wire_stream_id, - }; - let body = request.to_bytes(); - let bytes = SendWrapper::new(read_local( + let stream_id = identifier_to_wire(&stream_id).map_err(ReadError::Rejected)?; + SendWrapper::new(read_list::<TopicResponse, _>( &state, &identity, - query.consistency, + &pairs, GET_TOPICS_CODE, - &body, + |page| { + GetTopicsRequest { + stream_id: stream_id.clone(), + page, + } + .to_bytes() + }, |permissioner, uid| { - resolve_gate_stream(&state, &request.stream_id) + resolve_gate_stream(&state, &stream_id) .map_or(Ok(()), |stream_id| permissioner.get_topics(uid, stream_id)) }, + Topic::try_from, )) - .await?; - let response = GetTopicsResponse::decode_from(&bytes) - .map_err(|_| ReadError::Rejected(IggyError::InvalidCommand))?; - Ok(Json( - topics_from_wire(response).map_err(ReadError::Rejected)?, - )) + .await } /// `GET /streams/{stream_id}/topics/{topic_id}`: fetch one topic by numeric id @@ -453,28 +447,23 @@ )) } -/// `GET /users`: list every user as the same `Vec<UserInfo>` JSON the legacy -/// server returns. A consensus-free local STM read via [`read_local`]. +/// `GET /users`: every user as the `Vec<UserInfo>` JSON of the legacy server, +/// or one page of them. See [`read_list`]. pub(in crate::http) async fn get_users( State(state): State<HttpState>, identity: Identity, - Query(query): Query<ConsistencyQuery>, -) -> Result<Json<Vec<UserInfo>>, ReadError> { - let body = GetUsersRequest.to_bytes(); - let bytes = SendWrapper::new(read_local( + Query(pairs): Query<Vec<(String, String)>>, +) -> Result<Json<ListReply<UserInfo>>, ReadError> { + SendWrapper::new(read_list::<UserResponse, _>( &state, &identity, - query.consistency, + &pairs, GET_USERS_CODE, - &body, + |page| GetUsersRequest { page }.to_bytes(), Permissioner::get_users, + UserInfo::try_from, )) - .await?; - let response = GetUsersResponse::decode_from(&bytes) - .map_err(|_| ReadError::Rejected(IggyError::InvalidCommand))?; - Ok(Json( - users_from_wire(response).map_err(ReadError::Rejected)?, - )) + .await } /// `GET /users/{user_id}`: fetch one user by numeric id or name as the same @@ -523,41 +512,87 @@ )) } -/// `GET /streams/{stream_id}/topics/{topic_id}/consumer-groups`: list a topic's -/// consumer groups as the same `Vec<ConsumerGroup>` JSON the legacy server -/// returns. A consensus-free local STM read via [`read_local`]. +/// `GET /streams/{stream_id}/topics/{topic_id}/consumer-groups`: every +/// consumer group of a topic as the `Vec<ConsumerGroup>` JSON of the legacy +/// server, or one page of them. See [`read_list`]. pub(in crate::http) async fn get_cgs( State(state): State<HttpState>, identity: Identity, Path((stream_id, topic_id)): Path<(String, String)>, - Query(query): Query<ConsistencyQuery>, -) -> Result<Json<Vec<ConsumerGroup>>, ReadError> { + Query(pairs): Query<Vec<(String, String)>>, +) -> Result<Json<ListReply<ConsumerGroup>>, ReadError> { let stream_id = Identifier::from_str_value(&stream_id).map_err(ReadError::Rejected)?; let topic_id = Identifier::from_str_value(&topic_id).map_err(ReadError::Rejected)?; - let wire_stream_id = identifier_to_wire(&stream_id).map_err(ReadError::Rejected)?; - let wire_topic_id = identifier_to_wire(&topic_id).map_err(ReadError::Rejected)?; - let request = GetConsumerGroupsRequest { - stream_id: wire_stream_id, - topic_id: wire_topic_id, - }; - let body = request.to_bytes(); - let bytes = SendWrapper::new(read_local( + let stream_id = identifier_to_wire(&stream_id).map_err(ReadError::Rejected)?; + let topic_id = identifier_to_wire(&topic_id).map_err(ReadError::Rejected)?; + SendWrapper::new(read_list::<ConsumerGroupResponse, _>( &state, &identity, - query.consistency, + &pairs, GET_CONSUMER_GROUPS_CODE, - &body, + |page| { + GetConsumerGroupsRequest { + stream_id: stream_id.clone(), + topic_id: topic_id.clone(), + page, + } + .to_bytes() + }, |permissioner, uid| { - resolve_gate_topic(&state, &request.stream_id, &request.topic_id) + resolve_gate_topic(&state, &stream_id, &topic_id) .map_or(Ok(()), |(stream_id, topic_id)| { permissioner.get_consumer_groups(uid, stream_id, topic_id) }) }, + |group| Ok(ConsumerGroup::from(group)), )) - .await?; - let response = GetConsumerGroupsResponse::decode_from(&bytes) + .await +} + +/// The JSON of a list route: the bare array of every item, or one page. +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub(in crate::http) enum ListReply<T> { + Whole(Vec<T>), + Page(Page<T>), +} + +/// Serves one of the four list routes. A query with `limit` or `cursor` gets +/// the one page that its keys name. A query without both gets every item as +/// the bare array of the legacy server, in the order of its `order` and +/// `descending` keys and filtered by its `name` key, built from the server's +/// own pages by [`read_whole_list`]. The query is strict: an unknown, +/// repeated or malformed key is a 400. +async fn read_list<W: WireDecode, T>( + state: &HttpInner, + identity: &Identity, + pairs: &[(String, String)], + code: u32, + request: impl Fn(WirePageQuery) -> Bytes, + rule: impl Fn(&Permissioner, u32) -> Result<(), IggyError>, + convert: impl FnMut(W) -> Result<T, IggyError>, +) -> Result<Json<ListReply<T>>, ReadError> { + let (consistency, page_pairs) = split_list_query(pairs).map_err(ReadError::Rejected)?; + let selects_page = NamedPageQuery::selects_page(&page_pairs); + let query = NamedPageQuery::from_http_query(page_pairs).map_err(ReadError::Rejected)?; + let page = WirePageQuery::try_from(&query).map_err(ReadError::Rejected)?; + if !selects_page { + let items = + read_whole_list::<W>(state, identity, consistency, code, page, request, rule).await?; + return items + .into_iter() + .map(convert) + .collect::<Result<_, _>>() + .map(|items| Json(ListReply::Whole(items))) + .map_err(ReadError::Rejected); + } + let body = request(page); + let bytes = read_local(state, identity, consistency, code, &body, rule).await?; + let page = PageResponse::<W>::decode_from(&bytes) .map_err(|_| ReadError::Rejected(IggyError::InvalidCommand))?; - Ok(Json(consumer_groups_from_wire(response))) + page_from_wire(page, convert) + .map(|page| Json(ListReply::Page(page))) + .map_err(ReadError::Rejected) } /// `GET /streams/{stream_id}/topics/{topic_id}/consumer-groups/{group_id}`: @@ -1098,6 +1133,47 @@ Ok(StatusCode::NO_CONTENT) } +/// `GET /streams/{stream_id}/topics/{topic_id}/partitions`: one page of a +/// topic's partitions, as `{ "items": [...], "next": "pg1_..." }`. A request +/// without page keys reads the first page with the default limit. The query +/// is strict: an unknown, repeated or malformed key is a 400. +pub(in crate::http) async fn get_partitions( + State(state): State<HttpState>, + identity: Identity, + Path((stream_id, topic_id)): Path<(String, String)>, + Query(pairs): Query<Vec<(String, String)>>, +) -> Result<Json<Page<Partition>>, ReadError> { + let (consistency, page_pairs) = split_list_query(&pairs).map_err(ReadError::Rejected)?; + let query = PageQuery::from_http_query(page_pairs).map_err(ReadError::Rejected)?; + let stream_id = Identifier::from_str_value(&stream_id).map_err(ReadError::Rejected)?; + let topic_id = Identifier::from_str_value(&topic_id).map_err(ReadError::Rejected)?; + let request = GetPartitionsRequest { + stream_id: identifier_to_wire(&stream_id).map_err(ReadError::Rejected)?, + topic_id: identifier_to_wire(&topic_id).map_err(ReadError::Rejected)?, + page: WirePageQuery::try_from(&query).map_err(ReadError::Rejected)?, + }; + let body = request.to_bytes(); + let bytes = SendWrapper::new(read_local( + &state, + &identity, + consistency, + GET_PARTITIONS_CODE, + &body, + |permissioner, uid| { + resolve_gate_topic(&state, &request.stream_id, &request.topic_id) + .map_or(Ok(()), |(stream_id, topic_id)| { + permissioner.get_topic(uid, stream_id, topic_id) + }) + }, + )) + .await?; + let page = PageResponse::<PartitionResponse>::decode_from(&bytes) + .map_err(|_| ReadError::Rejected(IggyError::InvalidCommand))?; + page_from_wire(page, |partition| Ok(Partition::from(partition))) + .map(Json) + .map_err(ReadError::Rejected) +} + /// `POST /streams/{stream_id}/topics/{topic_id}/partitions`: add partitions to a /// topic. Returns 200 (this listener answers create routes 200, the /// legacy-majority parity). `partitions_count` comes from the JSON body; stream
diff --git a/core/server/src/http/reads.rs b/core/server/src/http/reads.rs index b139964..34948a8 100644 --- a/core/server/src/http/reads.rs +++ b/core/server/src/http/reads.rs
@@ -27,8 +27,10 @@ use crate::shell::ServerShard; use bytes::Bytes; use consensus::MetadataHandle; -use iggy_binary_protocol::WireIdentifier; use iggy_binary_protocol::codes::GET_STATS_CODE; +use iggy_binary_protocol::primitives::page::{MAX_PAGE_LIMIT, WirePageQuery}; +use iggy_binary_protocol::responses::PageResponse; +use iggy_binary_protocol::{WireDecode, WireIdentifier}; use iggy_common::wire_conversions::identifier_to_wire; use iggy_common::{Identifier, IggyError}; use message_bus::MessageBus; @@ -36,6 +38,7 @@ use metadata::permissioner::Permissioner; use send_wrapper::SendWrapper; use server_common::sharding::IggyNamespace; +use server_common::yield_to_reactor; use std::rc::Rc; use std::time::Instant; @@ -155,6 +158,58 @@ } } +/// Every item of a list route for a request without `limit` and `cursor`: +/// the bare array of the legacy server, read from the page builder in pages +/// of [`MAX_PAGE_LIMIT`]. `first` is the page block of the request, with its +/// order, direction and name filter. `request` builds the body of one page +/// read. +/// +/// The gates run once, as for [`read_local`]. Between two pages the task hands +/// the core back to the reactor, so a long list does not hold the shard +/// thread. The rule then runs again, because the account and its grants can +/// change during that await (see [`authorize_read`]). The reply is not one +/// consistent read. +pub(in crate::http) async fn read_whole_list<W: WireDecode>( + state: &HttpInner, + identity: &Identity, + consistency: Consistency, + code: u32, + first: WirePageQuery, + request: impl Fn(WirePageQuery) -> Bytes, + rule: impl Fn(&Permissioner, u32) -> Result<(), IggyError>, +) -> Result<Vec<W>, ReadError> { + gate_local_read(state, identity, consistency, code, &rule).await?; + let mut page = WirePageQuery { + limit: MAX_PAGE_LIMIT, + ..first + }; + let mut items = Vec::new(); + loop { + let NonReplicatedResponse::Bytes(bytes) = build_non_replicated_response( + &state.shard, + code, + &request(page.clone()), + Some(identity.user_id), + &state.roster, + identity.client_ip, + 0, + ) + .map_err(ReadError::Rejected)? + else { + return Err(ReadError::NotFound); + }; + let reply = PageResponse::<W>::decode_from(&bytes) + .map_err(|_| ReadError::Rejected(IggyError::InvalidCommand))?; + items.extend(reply.items); + let Some(next) = reply.next else { + return Ok(items); + }; + page.cursor = Some(next); + yield_to_reactor().await; + authorize_read(state, identity, consistency, &rule)?; + } +} + /// Every gate a read served from THIS node's state has to pass, in the one /// order that is safe. /// @@ -587,9 +642,9 @@ use hyper::service::Service as _; use hyper_util::service::TowerToHyperService; use iggy_binary_protocol::codes::{ - DESCRIBE_OPTIONS_CODE, GET_CONSUMER_GROUPS_CODE, GET_PERSONAL_ACCESS_TOKENS_CODE, - GET_STATS_CODE, GET_STREAM_CODE, GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, - GET_USER_CODE, GET_USERS_CODE, + DESCRIBE_OPTIONS_CODE, GET_CONSUMER_GROUPS_CODE, GET_PARTITIONS_CODE, + GET_PERSONAL_ACCESS_TOKENS_CODE, GET_STATS_CODE, GET_STREAM_CODE, GET_STREAMS_CODE, + GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE, GET_USERS_CODE, }; use iggy_binary_protocol::primitives::partition_assignment::CreatedPartitionAssignment; use iggy_binary_protocol::requests::messages::SendMessagesHeader; @@ -1561,6 +1616,7 @@ GET_STREAM_CODE, GET_TOPICS_CODE, GET_TOPIC_CODE, + GET_PARTITIONS_CODE, GET_USERS_CODE, GET_USER_CODE, GET_CONSUMER_GROUPS_CODE,
diff --git a/core/server/src/namespace.rs b/core/server/src/namespace.rs index 21b59bb..0a2d8e2 100644 --- a/core/server/src/namespace.rs +++ b/core/server/src/namespace.rs
@@ -41,7 +41,7 @@ use journal::superblock::SuperblockStore; use journal::{Journal, JournalHandle}; use metadata::impls::metadata::StreamsFrontend; -use metadata::stm::stream::Streams; +use metadata::stm::stream::{Streams, StreamsInner}; use server_common::Message; use server_common::sharding::IggyNamespace; use shard::{PartitionRead, PartitionReadReply}; @@ -292,15 +292,29 @@ S: 'static, SB: SuperblockStore + 'static, { - shard.plane.metadata().mux_stm.streams().read(|streams| { - let resolved_stream = streams - .resolve_stream_id(stream_id) - .ok_or_else(|| stream_not_found(stream_id))?; - streams - .resolve_topic_id(resolved_stream, topic_id) - .ok_or_else(|| topic_not_found(stream_id, topic_id))?; - Ok(()) - }) + shard + .plane + .metadata() + .mux_stm + .streams() + .read(|streams| resolve_topic(streams, stream_id, topic_id).map(|_| ())) +} + +/// The stream and topic ids of an existing topic, or the typed error of +/// [`ensure_topic_exists`]. A read that walks the topic resolves it in the +/// same state. +pub fn resolve_topic( + streams: &StreamsInner, + stream_id: &WireIdentifier, + topic_id: &WireIdentifier, +) -> Result<(usize, usize), IggyError> { + let resolved_stream = streams + .resolve_stream_id(stream_id) + .ok_or_else(|| stream_not_found(stream_id))?; + let resolved_topic = streams + .resolve_topic_id(resolved_stream, topic_id) + .ok_or_else(|| topic_not_found(stream_id, topic_id))?; + Ok((resolved_stream, resolved_topic)) } /// Fence a consumer-group offset commit/delete: a group consumer may only @@ -406,7 +420,7 @@ /// shape. The identifier only feeds the error message; a wire form with no /// domain equivalent (numeric 0 is a live slab id here but not a legacy id) /// falls back to the default identifier. -fn stream_not_found(stream_id: &WireIdentifier) -> IggyError { +pub fn stream_not_found(stream_id: &WireIdentifier) -> IggyError { IggyError::StreamIdNotFound(Identifier::try_from(stream_id).unwrap_or_default()) }
diff --git a/core/server/src/responses.rs b/core/server/src/responses.rs index a2919e5..48fee61 100644 --- a/core/server/src/responses.rs +++ b/core/server/src/responses.rs
@@ -23,7 +23,7 @@ //! `NonReplicatedResponse` dispatch shim. use crate::cluster_meta::ClusterRoster; -use crate::namespace::ensure_topic_exists; +use crate::namespace::{ensure_topic_exists, resolve_topic, stream_not_found}; use crate::reply_frame::{build_empty_reply, build_reply_from_bytes}; use crate::session_manager::SessionManager; use crate::shell::{ShellBus, ShellShard}; @@ -34,67 +34,72 @@ use iggy_binary_protocol::PrepareHeader; use iggy_binary_protocol::codes::{ DESCRIBE_OPTIONS_CODE, GET_CLUSTER_METADATA_CODE, GET_CONSUMER_GROUP_CODE, - GET_CONSUMER_GROUPS_CODE, GET_PERSONAL_ACCESS_TOKENS_CODE, GET_STATS_CODE, GET_STREAM_CODE, - GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE, GET_USERS_CODE, + GET_CONSUMER_GROUPS_CODE, GET_PARTITIONS_CODE, GET_PERSONAL_ACCESS_TOKENS_CODE, GET_STATS_CODE, + GET_STREAM_CODE, GET_STREAMS_CODE, GET_TOPIC_CODE, GET_TOPICS_CODE, GET_USER_CODE, + GET_USERS_CODE, }; +use iggy_binary_protocol::primitives::page::{WirePageCursor, WirePageQuery}; use iggy_binary_protocol::requests::consumer_groups::{ GetConsumerGroupRequest, GetConsumerGroupsRequest, }; +use iggy_binary_protocol::requests::partitions::GetPartitionsRequest; use iggy_binary_protocol::requests::personal_access_tokens::GetPersonalAccessTokensRequest; use iggy_binary_protocol::requests::streams::{GetStreamRequest, GetStreamsRequest}; use iggy_binary_protocol::requests::system::{ DescribeOptionsRequest, OPTIONS_SCOPE_STREAM, OPTIONS_SCOPE_TOPIC, OPTIONS_SCOPE_USER, }; use iggy_binary_protocol::requests::topics::{GetTopicRequest, GetTopicsRequest}; -use iggy_binary_protocol::requests::users::GetUserRequest; +use iggy_binary_protocol::requests::users::{GetUserRequest, GetUsersRequest}; +use iggy_binary_protocol::responses::PageResponse; use iggy_binary_protocol::responses::clients::client_response::ClientResponse; use iggy_binary_protocol::responses::clients::client_response::ConsumerGroupInfoResponse; use iggy_binary_protocol::responses::clients::get_client::ClientDetailsResponse; -use iggy_binary_protocol::responses::consumer_groups::GetConsumerGroupsResponse; +use iggy_binary_protocol::responses::consumer_groups::ConsumerGroupResponse; use iggy_binary_protocol::responses::personal_access_tokens::get_personal_access_tokens::{ GetPersonalAccessTokensResponse, PersonalAccessTokenResponse, }; use iggy_binary_protocol::responses::streams::StreamResponse; -use iggy_binary_protocol::responses::streams::get_stream::{ - GetStreamResponse, TopicHeader as StreamTopicHeader, -}; -use iggy_binary_protocol::responses::streams::get_streams::GetStreamsResponse; +use iggy_binary_protocol::responses::streams::get_stream::{GetStreamResponse, TopicResponse}; use iggy_binary_protocol::responses::system::DescribeOptionsResponse; use iggy_binary_protocol::responses::system::get_cluster_metadata::{ ClusterMetadataResponse, ClusterNodeResponse, }; use iggy_binary_protocol::responses::system::get_stats::StatsResponse; use iggy_binary_protocol::responses::topics::get_topic::{GetTopicResponse, PartitionResponse}; -use iggy_binary_protocol::responses::topics::get_topics::GetTopicsResponse; use iggy_binary_protocol::responses::users::get_user::UserDetailsResponse; -use iggy_binary_protocol::responses::users::get_users::GetUsersResponse; use iggy_binary_protocol::responses::users::user_response::UserResponse; use iggy_binary_protocol::{ ReplyHeader, RoutedRequestHeader, WireDecode, WireEncode, WireIdentifier, WireName, WireOptions, }; use iggy_common::wire_conversions::{describe_options_response, resource_options_to_wire_split}; use iggy_common::{ - HeaderValue, IggyError, IggyTimestamp, OptionKey, OptionsScope, ResourceOptions, UserStatus, - public_options, + HeaderValue, IggyError, IggyTimestamp, NamedPageQuery, OptionKey, OptionsScope, PageCursor, + PageOrder, PageQuery, ResourceOptions, UserStatus, public_options, }; use journal::superblock::SuperblockStore; use journal::{Journal, JournalHandle}; +use metadata::change_log::{MAX_PAGE_BYTES, MAX_SCANNED_ENTRIES}; use metadata::impls::metadata::StreamsFrontend; use metadata::stm::stream::{Stream, StreamsInner, Topic}; -use metadata::stm::user::User; +use metadata::stm::user::{User, UsersInner}; +use metadata::stm::walk::slice_after; use server_common::Message; use server_common::sharding::IggyNamespace; use shard::ConnectedClientInfo; +use std::borrow::Cow; use std::cell::RefCell; use std::net::IpAddr; use std::rc::Rc; use std::sync::Arc; use tracing::warn; -/// The stored fields a stream or topic read returns. Reads copy them under the -/// metadata read guard and project the options after it, because the writer -/// publishing the next apply waits for every reader to leave. -struct StoredEntry { +/// The stored fields a stream or topic read returns. A page projects them +/// under the metadata read guard with the options borrowed, because it holds +/// at most `MAX_PAGE_LIMIT` items. A detail read copies them with +/// [`Self::into_owned`] under the guard and projects the options after it, +/// because the writer publishing the next apply waits for every reader to +/// leave. +struct StoredEntry<'a> { id: usize, created_at: IggyTimestamp, /// Topics of a stream, partitions of a topic. @@ -102,20 +107,46 @@ size_bytes: u64, messages_count: u64, name: Arc<str>, - options: ResourceOptions, + options: Cow<'a, ResourceOptions>, } -/// The stored fields a user read returns, copied like [`StoredEntry`]. -struct StoredUser { +/// The stored fields a user read returns, read like [`StoredEntry`]. +struct StoredUser<'a> { id: u32, created_at: IggyTimestamp, status: UserStatus, username: Arc<str>, - options: ResourceOptions, + options: Cow<'a, ResourceOptions>, } -impl From<&Stream> for StoredEntry { - fn from(stream: &Stream) -> Self { +impl StoredEntry<'_> { + fn into_owned(self) -> StoredEntry<'static> { + StoredEntry { + id: self.id, + created_at: self.created_at, + children_count: self.children_count, + size_bytes: self.size_bytes, + messages_count: self.messages_count, + name: self.name, + options: Cow::Owned(self.options.into_owned()), + } + } +} + +impl StoredUser<'_> { + fn into_owned(self) -> StoredUser<'static> { + StoredUser { + id: self.id, + created_at: self.created_at, + status: self.status, + username: self.username, + options: Cow::Owned(self.options.into_owned()), + } + } +} + +impl<'a> From<&'a Stream> for StoredEntry<'a> { + fn from(stream: &'a Stream) -> Self { Self { id: stream.id, created_at: stream.created_at, @@ -123,13 +154,13 @@ size_bytes: stream.stats.size_bytes_inconsistent(), messages_count: stream.stats.messages_count_inconsistent(), name: Arc::clone(&stream.name), - options: stream.options.clone(), + options: Cow::Borrowed(&stream.options), } } } -impl From<&Topic> for StoredEntry { - fn from(topic: &Topic) -> Self { +impl<'a> From<&'a Topic> for StoredEntry<'a> { + fn from(topic: &'a Topic) -> Self { Self { id: topic.id, created_at: topic.created_at, @@ -137,19 +168,19 @@ size_bytes: topic.stats.size_bytes_inconsistent(), messages_count: topic.stats.messages_count_inconsistent(), name: Arc::clone(&topic.name), - options: topic.options.clone(), + options: Cow::Borrowed(&topic.options), } } } -impl From<&User> for StoredUser { - fn from(user: &User) -> Self { +impl<'a> From<&'a User> for StoredUser<'a> { + fn from(user: &'a User) -> Self { Self { id: user.id, created_at: user.created_at, status: user.status, username: Arc::clone(&user.username), - options: user.options.clone(), + options: Cow::Borrowed(&user.options), } } } @@ -353,12 +384,9 @@ }) }) } - GET_STREAMS_CODE => { - let _ = GetStreamsRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; - Ok(NonReplicatedResponse::Bytes( - build_get_streams_response(shard)?.to_bytes(), - )) - } + GET_STREAMS_CODE => Ok(NonReplicatedResponse::Bytes( + build_get_streams_response(shard, body)?.to_bytes(), + )), GET_TOPIC_CODE => { let request = GetTopicRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; @@ -368,15 +396,14 @@ }) }) } - GET_TOPICS_CODE => { - let request = - GetTopicsRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; - Ok(NonReplicatedResponse::Bytes( - build_get_topics_response(shard, &request.stream_id)?.to_bytes(), - )) - } + GET_TOPICS_CODE => Ok(NonReplicatedResponse::Bytes( + build_get_topics_response(shard, body)?.to_bytes(), + )), + GET_PARTITIONS_CODE => Ok(NonReplicatedResponse::Bytes( + build_get_partitions_response(shard, body)?.to_bytes(), + )), GET_USERS_CODE => Ok(NonReplicatedResponse::Bytes( - build_get_users_response(shard)?.to_bytes(), + build_get_users_response(shard, body)?.to_bytes(), )), GET_USER_CODE => { let request = @@ -405,7 +432,9 @@ )) } GET_CONSUMER_GROUP_CODE => build_consumer_group_response(shard, body), - GET_CONSUMER_GROUPS_CODE => build_consumer_groups_response(shard, body), + GET_CONSUMER_GROUPS_CODE => Ok(NonReplicatedResponse::Bytes( + build_consumer_groups_response(shard, body)?.to_bytes(), + )), // A table-listed non-replicated code with no arm is a routing bug and // an unknown code is a client bug; the empty-ok that used to cover both // attested a read that never ran. Only the named arms return `Empty`, @@ -445,7 +474,7 @@ fn build_consumer_groups_response<B, MJ, S, SB>( shard: &Rc<ShellShard<B, MJ, S, SB>>, body: &[u8], -) -> Result<NonReplicatedResponse, IggyError> +) -> Result<PageResponse<ConsumerGroupResponse>, IggyError> where B: ShellBus, MJ: JournalHandle + 'static, @@ -455,16 +484,12 @@ { let request = GetConsumerGroupsRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; - ensure_topic_exists(shard, &request.stream_id, &request.topic_id)?; - let groups = shard + shard .plane .metadata() .mux_stm .streams() - .consumer_group_list(&request.stream_id, &request.topic_id); - Ok(groups.map_or(NonReplicatedResponse::Empty, |groups| { - NonReplicatedResponse::Bytes(GetConsumerGroupsResponse { groups }.to_bytes()) - })) + .read(|streams| consumer_groups_page(streams, request, PAGE_BUDGET)) } /// Build the binary `GetClusterMetadata` reply from the shared roster assembly. @@ -649,7 +674,10 @@ .items .get(stream_id) .ok_or(IggyError::InvalidIdentifier)?; - Ok(Some((StoredEntry::from(stream), stored_topics(stream)))) + Ok(Some(( + StoredEntry::from(stream).into_owned(), + stored_topics(stream), + ))) })?; let Some((stream, topics)) = stored else { return Ok(None); @@ -662,7 +690,8 @@ fn build_get_streams_response<B, MJ, S, SB>( shard: &Rc<ShellShard<B, MJ, S, SB>>, -) -> Result<GetStreamsResponse, IggyError> + body: &[u8], +) -> Result<PageResponse<StreamResponse>, IggyError> where B: ShellBus, MJ: JournalHandle + 'static, @@ -670,71 +699,63 @@ S: 'static, SB: SuperblockStore + 'static, { - let streams = shard + let request = GetStreamsRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; + let (page, skipped) = shard .plane .metadata() .mux_stm .streams() - .read(stored_streams); - listed_streams(&streams).map(|streams| GetStreamsResponse { streams }) + .read(|streams| streams_page(streams, request.page, PAGE_BUDGET))?; + log_skipped(&skipped); + Ok(page) } -fn stored_streams(streams: &StreamsInner) -> Vec<StoredEntry> { - streams - .items - .iter() - .map(|(_, stream)| StoredEntry::from(stream)) - .collect() -} - -fn stored_topics(stream: &Stream) -> Vec<StoredEntry> { +fn stored_topics(stream: &Stream) -> Vec<StoredEntry<'static>> { stream .topics .iter() - .map(|(_, topic)| StoredEntry::from(topic)) - .collect() -} - -/// Every stream a list read serves, see [`servable`]. -fn listed_streams(streams: &[StoredEntry]) -> Result<Vec<StreamResponse>, IggyError> { - streams - .iter() - .filter_map(|stream| { - servable( - stream_response(stream), - OptionsScope::Stream, - stream.id, - None, - ) - .transpose() - }) + .map(|(_, topic)| StoredEntry::from(topic).into_owned()) .collect() } /// Every topic of stream `stream_id` a list read serves, see [`servable`]. fn listed_topics( stream_id: usize, - topics: &[StoredEntry], -) -> Result<Vec<StreamTopicHeader>, IggyError> { - topics + topics: &[StoredEntry<'_>], +) -> Result<Vec<TopicResponse>, IggyError> { + let mut skipped = Vec::new(); + let listed = topics .iter() .filter_map(|topic| { servable( - topic_header(topic), + topic_response(topic), + &mut skipped, OptionsScope::Topic, topic.id, Some(stream_id), ) .transpose() }) - .collect() + .collect(); + log_skipped(&skipped); + listed +} + +/// A list entry that this build cannot read, see [`servable`]. +struct SkippedEntry { + scope: OptionsScope, + resource_id: usize, + stream_id: Option<usize>, + key: String, } /// A list entry, or `None` for a resource whose stored critical state this /// build cannot read. That resource still fails its own read, but it must not -/// fail the list every other resource is served in. +/// fail the list every other resource is served in. It lands in `skipped`, and +/// the caller logs it with [`log_skipped`] after the metadata read guard. fn servable<T>( entry: Result<T, IggyError>, + skipped: &mut Vec<SkippedEntry>, scope: OptionsScope, resource_id: usize, stream_id: Option<usize>, @@ -742,18 +763,30 @@ match entry { Ok(entry) => Ok(Some(entry)), Err(IggyError::UnsupportedCriticalOption(key)) => { - warn!( - scope = %scope, + skipped.push(SkippedEntry { + scope, resource_id, stream_id, - "Leaving {scope} {resource_id} out of the list, its critical option {key} is not readable by this build." - ); + key, + }); Ok(None) } Err(error) => Err(error), } } +fn log_skipped(skipped: &[SkippedEntry]) { + for entry in skipped { + let (scope, resource_id, key) = (entry.scope, entry.resource_id, &entry.key); + warn!( + scope = %scope, + resource_id, + stream_id = entry.stream_id, + "Leaving {scope} {resource_id} out of the list, its critical option {key} is not readable by this build." + ); + } +} + /// Serve the option catalog for one resource scope, with the replication /// factor this node gives a topic created without one. fn build_describe_options_response( @@ -785,7 +818,7 @@ resource_options_to_wire_split(&public_options(scope, stored)?) } -fn user_response(user: &StoredUser) -> Result<UserResponse, IggyError> { +fn user_response(user: &StoredUser<'_>) -> Result<UserResponse, IggyError> { let (options, derived_options) = public_blocks(OptionsScope::User, &user.options)?; Ok(UserResponse { id: user.id, @@ -799,7 +832,8 @@ fn build_get_users_response<B, MJ, S, SB>( shard: &Rc<ShellShard<B, MJ, S, SB>>, -) -> Result<GetUsersResponse, IggyError> + body: &[u8], +) -> Result<PageResponse<UserResponse>, IggyError> where B: ShellBus, MJ: JournalHandle + 'static, @@ -807,26 +841,15 @@ S: 'static, SB: SuperblockStore + 'static, { - let users = shard.plane.metadata().mux_stm.users().read(|users| { - users - .items - .iter() - .map(|(_, user)| StoredUser::from(user)) - .collect::<Vec<_>>() - }); - users - .iter() - .filter_map(|user| { - servable( - user_response(user), - OptionsScope::User, - user.id as usize, - None, - ) - .transpose() - }) - .collect::<Result<Vec<_>, _>>() - .map(|users| GetUsersResponse { users }) + let request = GetUsersRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; + let (page, skipped) = shard + .plane + .metadata() + .mux_stm + .users() + .read(|users| users_page(users, request.page, PAGE_BUDGET))?; + log_skipped(&skipped); + Ok(page) } fn build_get_user_response<B, MJ, S, SB>( @@ -850,7 +873,10 @@ return Ok(None); }; let user = users.items.get(id).ok_or(IggyError::InvalidIdentifier)?; - Ok(Some((StoredUser::from(user), user.permissions.clone()))) + Ok(Some(( + StoredUser::from(user).into_owned(), + user.permissions.clone(), + ))) })?; let Some((user, permissions)) = stored else { return Ok(None); @@ -928,21 +954,21 @@ ) }) .collect::<Result<Vec<_>, _>>()?; - Ok(Some((StoredEntry::from(topic), partitions))) + Ok(Some((StoredEntry::from(topic).into_owned(), partitions))) })?; let Some((topic, partitions)) = stored else { return Ok(None); }; Ok(Some(GetTopicResponse { - topic: topic_header(&topic)?, + topic: topic_response(&topic)?, partitions, })) } fn build_get_topics_response<B, MJ, S, SB>( shard: &Rc<ShellShard<B, MJ, S, SB>>, - stream_id: &WireIdentifier, -) -> Result<GetTopicsResponse, IggyError> + body: &[u8], +) -> Result<PageResponse<TopicResponse>, IggyError> where B: ShellBus, MJ: JournalHandle + 'static, @@ -950,30 +976,18 @@ S: 'static, SB: SuperblockStore + 'static, { - let stored = - shard - .plane - .metadata() - .mux_stm - .streams() - .read(|streams| -> Result<_, IggyError> { - // Legacy parity: a missing stream lists as empty, not StreamNotFound. - let Some(resolved_stream) = streams.resolve_stream_id(stream_id) else { - return Ok(None); - }; - let stream = streams - .items - .get(resolved_stream) - .ok_or(IggyError::InvalidIdentifier)?; - Ok(Some((stream.id, stored_topics(stream)))) - })?; - let Some((stream_id, topics)) = stored else { - return Ok(GetTopicsResponse { topics: Vec::new() }); - }; - listed_topics(stream_id, &topics).map(|topics| GetTopicsResponse { topics }) + let request = GetTopicsRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; + let (page, skipped) = shard + .plane + .metadata() + .mux_stm + .streams() + .read(|streams| topics_page(streams, request, PAGE_BUDGET))?; + log_skipped(&skipped); + Ok(page) } -fn stream_response(stream: &StoredEntry) -> Result<StreamResponse, IggyError> { +fn stream_response(stream: &StoredEntry<'_>) -> Result<StreamResponse, IggyError> { let (options, derived_options) = public_blocks(OptionsScope::Stream, &stream.options)?; Ok(StreamResponse { id: usize_to_u32(stream.id)?, @@ -987,9 +1001,9 @@ }) } -fn topic_header(topic: &StoredEntry) -> Result<StreamTopicHeader, IggyError> { +fn topic_response(topic: &StoredEntry<'_>) -> Result<TopicResponse, IggyError> { let (options, derived_options) = public_blocks(OptionsScope::Topic, &topic.options)?; - Ok(StreamTopicHeader { + Ok(TopicResponse { id: usize_to_u32(topic.id)?, created_at: topic.created_at.as_micros(), partitions_count: usize_to_u32(topic.children_count)?, @@ -1099,12 +1113,355 @@ }) } +/// The budgets of one page read, see [`collect_page`]. +#[derive(Debug, Clone, Copy)] +struct PageBudget { + scanned_entries: usize, + page_bytes: usize, +} + +const PAGE_BUDGET: PageBudget = PageBudget { + scanned_entries: MAX_SCANNED_ENTRIES, + page_bytes: MAX_PAGE_BYTES, +}; + +/// One page of an ordered walk, built under the metadata read guard. +/// +/// `walk` yields each entry after the cursor with its position, and `project` +/// builds the wire item of an entry, or `None` for an entry the page skips. +/// The page stops after `limit` items, after `scanned_entries` walked entries, +/// or before the item that would take it past `page_bytes`. The first item +/// always fits, so every page read makes progress. `next` is the position of +/// the last walked entry, absent once the walk reached the end of the order. +/// +/// An id walk over an `IdSlab` also passes the free slots of deleted entries, +/// and they do not count. One page can therefore walk every slot up to the +/// highest id ever used: at most `MAX_STREAMS` for streams and `MAX_TOPICS` for +/// topics, and the peak number of users for users. +fn collect_page<E, T: WireEncode>( + mut walk: impl Iterator<Item = (WirePageCursor, E)>, + limit: usize, + budget: PageBudget, + mut project: impl FnMut(E) -> Result<Option<T>, IggyError>, +) -> Result<PageResponse<T>, IggyError> { + let mut items = Vec::new(); + let mut bytes = 0; + let mut scanned = 0; + let mut walked = None; + while let Some((position, entry)) = walk.next() { + if let Some(item) = project(entry)? { + let size = item.encoded_size(); + if !items.is_empty() && bytes + size > budget.page_bytes { + return Ok(PageResponse { + items, + next: walked, + }); + } + bytes += size; + items.push(item); + } + walked = Some(position); + scanned += 1; + if items.len() == limit || scanned == budget.scanned_entries { + // The look-ahead only tells whether the order goes on. + let next = walk.next().and(walked); + return Ok(PageResponse { items, next }); + } + } + Ok(PageResponse { items, next: None }) +} + +/// The start of a walk in id order. A creation cursor names no position in it. +fn id_after(cursor: Option<PageCursor>) -> Result<Option<usize>, IggyError> { + match cursor.map(WirePageCursor::from) { + None => Ok(None), + // An id beyond `usize` lies past every entry, as `usize::MAX` does. + Some(WirePageCursor::Id(id)) => Ok(Some(usize::try_from(id).unwrap_or(usize::MAX))), + Some(WirePageCursor::Created { .. }) => Err(IggyError::InvalidCommand), + } +} + +fn build_get_partitions_response<B, MJ, S, SB>( + shard: &Rc<ShellShard<B, MJ, S, SB>>, + body: &[u8], +) -> Result<PageResponse<PartitionResponse>, IggyError> +where + B: ShellBus, + MJ: JournalHandle + 'static, + MJ::Target: Journal<Entry = Message<PrepareHeader>, Header = PrepareHeader>, + S: 'static, + SB: SuperblockStore + 'static, +{ + let request = GetPartitionsRequest::decode_from(body).map_err(|_| IggyError::InvalidCommand)?; + let nodes = shard.replica_topology().replica_count; + shard.plane.metadata().mux_stm.streams().read(|streams| { + let metadata_op = shard.plane.metadata().applied_frontier().get(); + partitions_page(streams, request, metadata_op, nodes) + }) +} + +/// One page of the partitions of a topic, in id order. Partition ids follow +/// creation, so the creation order walks the same way. +fn partitions_page( + streams: &StreamsInner, + request: GetPartitionsRequest, + metadata_op: u64, + nodes: u8, +) -> Result<PageResponse<PartitionResponse>, IggyError> { + let query = PageQuery::try_from(request.page)?; + let after = id_after(query.cursor)?; + let (stream_id, topic_id) = resolve_topic(streams, &request.stream_id, &request.topic_id)?; + let topic = streams + .items + .get(stream_id) + .and_then(|stream| stream.topics.get(topic_id)) + .ok_or(IggyError::InvalidIdentifier)?; + let walk = topic + .partitions_after(after, query.descending) + .map(|partition| (WirePageCursor::Id(partition.id as u64), partition)); + collect_page(walk, query.limit as usize, PAGE_BUDGET, |partition| { + partition_response(streams, stream_id, topic_id, partition, metadata_op, nodes).map(Some) + }) +} + +/// One page of the streams, and the streams it leaves out because this build +/// cannot read them. +fn streams_page( + streams: &StreamsInner, + page: WirePageQuery, + budget: PageBudget, +) -> Result<(PageResponse<StreamResponse>, Vec<SkippedEntry>), IggyError> { + let NamedPageQuery { page: query, name } = NamedPageQuery::try_from(page)?; + let start = WalkStart::try_from(&query)?; + let limit = query.limit as usize; + let mut skipped = Vec::new(); + let project = |stream: &Stream| { + if !matches_name(&stream.name, name.as_deref()) { + return Ok(None); + } + servable( + stream_response(&StoredEntry::from(stream)), + &mut skipped, + OptionsScope::Stream, + stream.id, + None, + ) + }; + let page = match start { + WalkStart::Id(after) => collect_page( + streams + .items + .walk(after, query.descending) + .map(|(id, stream)| (WirePageCursor::Id(id as u64), stream)), + limit, + budget, + project, + ), + WalkStart::Created(after) => collect_page( + streams + .streams_by_created(after, query.descending) + .map(|((created_at, id), stream)| (created_cursor(created_at, id), stream)), + limit, + budget, + project, + ), + }?; + Ok((page, skipped)) +} + +/// One page of the topics of a stream, and the topics it leaves out because +/// this build cannot read them. A missing stream lists as an empty last page, +/// as the full list did. After the first page it is `StreamIdNotFound`: the +/// stream was deleted during the walk, so the pages read are not the list. +fn topics_page( + streams: &StreamsInner, + request: GetTopicsRequest, + budget: PageBudget, +) -> Result<(PageResponse<TopicResponse>, Vec<SkippedEntry>), IggyError> { + let NamedPageQuery { page: query, name } = NamedPageQuery::try_from(request.page)?; + let start = WalkStart::try_from(&query)?; + let Some(stream_id) = streams.resolve_stream_id(&request.stream_id) else { + if query.cursor.is_some() { + return Err(stream_not_found(&request.stream_id)); + } + return Ok(( + PageResponse { + items: Vec::new(), + next: None, + }, + Vec::new(), + )); + }; + let stream = streams + .items + .get(stream_id) + .ok_or(IggyError::InvalidIdentifier)?; + let limit = query.limit as usize; + let mut skipped = Vec::new(); + let project = |topic: &Topic| { + if !matches_name(&topic.name, name.as_deref()) { + return Ok(None); + } + servable( + topic_response(&StoredEntry::from(topic)), + &mut skipped, + OptionsScope::Topic, + topic.id, + Some(stream_id), + ) + }; + let page = match start { + WalkStart::Id(after) => collect_page( + stream + .topics + .walk(after, query.descending) + .map(|(id, topic)| (WirePageCursor::Id(id as u64), topic)), + limit, + budget, + project, + ), + WalkStart::Created(after) => { + let topics = stream.topics_by_created(); + collect_page( + slice_after(&topics, |(key, _)| *key, after, query.descending) + .map(|&((created_at, id), topic)| (created_cursor(created_at, id), topic)), + limit, + budget, + project, + ) + } + }?; + Ok((page, skipped)) +} + +/// One page of the consumer groups of a topic, in id order. Group ids follow +/// creation, so the creation order walks the same way. +fn consumer_groups_page( + streams: &StreamsInner, + request: GetConsumerGroupsRequest, + budget: PageBudget, +) -> Result<PageResponse<ConsumerGroupResponse>, IggyError> { + let NamedPageQuery { page: query, name } = NamedPageQuery::try_from(request.page)?; + let after = id_after(query.cursor)?; + let (stream_id, topic_id) = resolve_topic(streams, &request.stream_id, &request.topic_id)?; + let topic = streams + .items + .get(stream_id) + .and_then(|stream| stream.topics.get(topic_id)) + .ok_or(IggyError::InvalidIdentifier)?; + let walk = topic + .consumer_groups_after(after.map(|id| id as u64), query.descending) + .map(|group| (WirePageCursor::Id(group.id), group)); + collect_page(walk, query.limit as usize, budget, |group| { + Ok( + matches_name(&group.name, name.as_deref()) + .then(|| topic.consumer_group_response(group)), + ) + }) +} + +/// One page of the users, and the users it leaves out because this build +/// cannot read them. +fn users_page( + users: &UsersInner, + page: WirePageQuery, + budget: PageBudget, +) -> Result<(PageResponse<UserResponse>, Vec<SkippedEntry>), IggyError> { + let NamedPageQuery { page: query, name } = NamedPageQuery::try_from(page)?; + let start = WalkStart::try_from(&query)?; + let limit = query.limit as usize; + let mut skipped = Vec::new(); + let project = |user: &User| { + if !matches_name(&user.username, name.as_deref()) { + return Ok(None); + } + servable( + user_response(&StoredUser::from(user)), + &mut skipped, + OptionsScope::User, + user.id as usize, + None, + ) + }; + let page = match start { + WalkStart::Id(after) => collect_page( + users + .items + .walk(after, query.descending) + .map(|(id, user)| (WirePageCursor::Id(id as u64), user)), + limit, + budget, + project, + ), + WalkStart::Created(after) => collect_page( + users + .users_by_created(after, query.descending) + .map(|((created_at, id), user)| (created_cursor(created_at, id), user)), + limit, + budget, + project, + ), + }?; + Ok((page, skipped)) +} + +/// Where a walk in the order of a query starts. +enum WalkStart { + Id(Option<usize>), + Created(Option<(u64, usize)>), +} + +impl TryFrom<&PageQuery> for WalkStart { + type Error = IggyError; + + fn try_from(query: &PageQuery) -> Result<Self, Self::Error> { + match query.order { + PageOrder::Id => id_after(query.cursor).map(Self::Id), + PageOrder::Created => created_after(query.cursor).map(Self::Created), + } + } +} + +/// The start of a walk in creation order. An id cursor names no position in +/// it. +fn created_after(cursor: Option<PageCursor>) -> Result<Option<(u64, usize)>, IggyError> { + match cursor.map(WirePageCursor::from) { + None => Ok(None), + // An id beyond `usize` lies past every entry of its time, as `usize::MAX` does. + Some(WirePageCursor::Created { created_at, id }) => Ok(Some(( + created_at, + usize::try_from(id).unwrap_or(usize::MAX), + ))), + Some(WirePageCursor::Id(_)) => Err(IggyError::InvalidCommand), + } +} + +const fn created_cursor(created_at: u64, id: usize) -> WirePageCursor { + WirePageCursor::Created { + created_at, + id: id as u64, + } +} + +/// Whether `name` holds the name filter of a page, as a case-sensitive +/// substring. +fn matches_name(name: &str, filter: Option<&str>) -> bool { + filter.is_none_or(|filter| name.contains(filter)) +} + pub enum NonReplicatedResponse { Empty, Bytes(Bytes), } impl NonReplicatedResponse { + pub(crate) const fn body_len(&self) -> usize { + match self { + Self::Empty => 0, + Self::Bytes(body) => body.len(), + } + } + pub(crate) fn into_reply( self, request_header: &RoutedRequestHeader, @@ -1124,7 +1481,16 @@ #[cfg(test)] mod tests { use super::*; - use iggy_common::{HeaderKey, OptionValue}; + use iggy_binary_protocol::primitives::page::WirePageOrder; + use iggy_binary_protocol::requests::consumer_groups::CreateConsumerGroupRequest; + use iggy_binary_protocol::requests::streams::{CreateStreamRequest, DeleteStreamRequest}; + use iggy_binary_protocol::requests::topics::{ + CreateTopicRequest, CreateTopicWithAssignmentsRequest, DeleteTopicRequest, + }; + use iggy_binary_protocol::requests::users::{CreateUserRequest, DeleteUserRequest}; + use iggy_common::{HeaderKey, Identifier, OptionValue}; + use metadata::stm::StateHandler; + use metadata::stm::stream::Partition; use std::str::FromStr; #[test] @@ -1157,11 +1523,37 @@ let names = |names: Vec<&WireName>| -> Vec<String> { names.iter().map(|name| name.as_str().to_owned()).collect() }; - let listed = listed_streams(&stored_streams(&streams)).expect("the stream list builds"); + let skipped_keys = |skipped: Vec<SkippedEntry>| -> Vec<(OptionsScope, String)> { + skipped + .into_iter() + .map(|entry| (entry.scope, entry.key)) + .collect() + }; + let (page, skipped) = + streams_page(&streams, WirePageQuery::default(), PAGE_BUDGET).expect("a stream page"); assert_eq!( - names(listed.iter().map(|stream| &stream.name).collect()), + names(page.items.iter().map(|stream| &stream.name).collect()), ["readable"] ); + assert_eq!(page.next, None); + assert_eq!( + skipped_keys(skipped), + [(OptionsScope::Stream, "future_key".to_owned())] + ); + let topics_request = GetTopicsRequest { + stream_id: WireIdentifier::numeric(u32::try_from(readable_slot).unwrap()), + page: WirePageQuery::default(), + }; + let (page, skipped) = + topics_page(&streams, topics_request, PAGE_BUDGET).expect("a topic page"); + assert_eq!( + names(page.items.iter().map(|topic| &topic.name).collect()), + ["kept"] + ); + assert_eq!( + skipped_keys(skipped), + [(OptionsScope::Topic, "future_key".to_owned())] + ); let readable = streams.items.get(readable_slot).expect("stream stored"); let topics = listed_topics(readable.id, &stored_topics(readable)).expect("the topic list builds"); @@ -1317,7 +1709,7 @@ Partition::new(1, 1, created_at, 0, 0), ], round_robin_counter: Arc::new(AtomicUsize::new(0)), - consumer_groups: ahash::AHashMap::default(), + consumer_groups: std::collections::BTreeMap::new(), consumer_group_index: ahash::AHashMap::default(), next_consumer_group_id: 0, consumer_group_catalog_op: 0, @@ -1380,7 +1772,7 @@ ); topic.set_options(options.clone()); - let header = topic_header(&StoredEntry::from(&topic)).expect("topic header builds"); + let header = topic_response(&StoredEntry::from(&topic)).expect("topic header builds"); let mut explicit = resource_options_from_wire(&header.options, true).unwrap(); explicit.extend(resource_options_from_wire(&header.derived_options, false).unwrap()); @@ -1388,4 +1780,616 @@ assert_eq!((&header.options).into_iter().count(), 1); assert_eq!((&header.derived_options).into_iter().count(), 1); } + + const ENTRIES: u64 = 10; + /// The encoded size of each test item, `e0` to `e9` behind a length byte. + const ITEM_BYTES: usize = 3; + + /// One page of the entries 0 to 9 after `after`, keeping the entries that + /// `keep` accepts. + fn entries_page( + after: Option<u64>, + limit: usize, + budget: PageBudget, + keep: impl Fn(u64) -> bool, + ) -> PageResponse<WireName> { + let walk = (0..ENTRIES) + .filter(|id| after.is_none_or(|after| *id > after)) + .map(|id| (WirePageCursor::Id(id), id)); + collect_page(walk, limit, budget, |id| { + Ok(keep(id).then(|| WireName::new(format!("e{id}")).unwrap())) + }) + .unwrap() + } + + /// Every page from the start, as (items, pages read). `read_page` reads the + /// page after a cursor, as a client does with the `next` of each page. + fn walk_pages<T>( + mut read_page: impl FnMut(Option<WirePageCursor>) -> PageResponse<T>, + ) -> (Vec<T>, usize) { + let mut items = Vec::new(); + let mut cursor = None; + let mut pages = 0; + loop { + pages += 1; + let page = read_page(cursor); + items.extend(page.items); + let Some(next) = page.next else { + return (items, pages); + }; + cursor = Some(next); + } + } + + /// Every page of the entries from the start, as (item names, pages read). + fn walk_entries( + limit: usize, + budget: PageBudget, + keep: impl Fn(u64) -> bool + Copy, + ) -> (Vec<String>, usize) { + let (items, pages) = walk_pages(|cursor| { + let after = cursor.map(|cursor| match cursor { + WirePageCursor::Id(id) => id, + cursor @ WirePageCursor::Created { .. } => { + panic!("an id walk returned {cursor:?}") + } + }); + entries_page(after, limit, budget, keep) + }); + let names = items.iter().map(|name| name.as_str().to_owned()).collect(); + (names, pages) + } + + fn names(ids: impl IntoIterator<Item = u64>) -> Vec<String> { + ids.into_iter().map(|id| format!("e{id}")).collect() + } + + #[test] + fn given_any_limit_when_walking_every_page_should_return_each_entry_once() { + for limit in [1, 2, 3, 5, 9, 10, 11, 1000] { + let (walked, pages) = walk_entries(limit, PAGE_BUDGET, |_| true); + assert_eq!(walked, names(0..ENTRIES), "limit {limit}"); + assert_eq!( + pages, + 10_usize.div_ceil(limit), + "limit {limit}: only the page that reaches the end has no next" + ); + let (even, _) = walk_entries(limit, PAGE_BUDGET, |id| id % 2 == 0); + assert_eq!(even, names((0..ENTRIES).step_by(2)), "limit {limit}"); + } + } + + #[test] + fn given_a_byte_budget_when_paging_should_stop_before_the_item_that_passes_it() { + let budget = |items| PageBudget { + page_bytes: items * ITEM_BYTES, + ..PAGE_BUDGET + }; + let page = entries_page(None, 1000, budget(3), |_| true); + assert_eq!(page.items.len(), 3); + assert_eq!(page.next, Some(WirePageCursor::Id(2))); + + let tight = PageBudget { + page_bytes: 1, + ..PAGE_BUDGET + }; + let page = entries_page(None, 1000, tight, |_| true); + assert_eq!(page.items.len(), 1, "the first item fits any budget"); + assert_eq!(page.next, Some(WirePageCursor::Id(0))); + assert_eq!(walk_entries(1000, tight, |_| true).0, names(0..ENTRIES)); + } + + #[test] + fn given_skipped_entries_before_the_byte_stop_when_paging_should_continue_after_them() { + let keep = |id| id != 1 && id != 2; + let one_item = PageBudget { + page_bytes: ITEM_BYTES, + ..PAGE_BUDGET + }; + let page = entries_page(None, 1000, one_item, keep); + assert_eq!(page.items.len(), 1); + assert_eq!(page.next, Some(WirePageCursor::Id(2))); + let page = entries_page(Some(2), 1000, one_item, keep); + assert_eq!(page.items[0].as_str(), "e3"); + } + + #[test] + fn given_a_filter_without_a_match_when_paging_should_end_after_the_scan_budget_pages() { + let scan = |entries| PageBudget { + scanned_entries: entries, + ..PAGE_BUDGET + }; + let page = entries_page(None, 1000, scan(4), |_| false); + assert_eq!(page.items, Vec::<WireName>::new()); + assert_eq!(page.next, Some(WirePageCursor::Id(3))); + assert_eq!(walk_entries(1000, scan(4), |_| false), (Vec::new(), 3)); + assert_eq!(walk_entries(1000, scan(5), |_| false), (Vec::new(), 2)); + } + + fn topic_with_partitions(count: usize) -> StreamsInner { + let created_at = IggyTimestamp::from(1u64); + let mut streams = StreamsInner::new(); + let mut stream = Stream::new(Arc::from("orders"), created_at); + let mut topic = Topic::new(Arc::from("events"), created_at, stream.stats.clone()); + topic.partitions = (0..count) + .map(|id| Partition::new(id, id as u64, created_at, 0, 0)) + .collect(); + stream.topics.insert(topic); + streams.items.insert(stream); + streams + } + + fn partition_ids( + streams: &StreamsInner, + stream_id: u32, + page: WirePageQuery, + ) -> Result<(Vec<u32>, Option<WirePageCursor>), IggyError> { + let request = GetPartitionsRequest { + stream_id: WireIdentifier::numeric(stream_id), + topic_id: WireIdentifier::numeric(0), + page, + }; + partitions_page(streams, request, 0, 1).map(|page| { + let ids = page.items.iter().map(|partition| partition.id).collect(); + (ids, page.next) + }) + } + + #[test] + fn given_a_topic_when_paging_its_partitions_should_walk_ids_in_both_directions() { + let streams = topic_with_partitions(5); + let page = |descending, limit, cursor: Option<u64>| { + let query = WirePageQuery { + descending, + limit, + cursor: cursor.map(WirePageCursor::Id), + ..WirePageQuery::default() + }; + partition_ids(&streams, 0, query).unwrap() + }; + let id = |id| Some(WirePageCursor::Id(id)); + assert_eq!(page(false, 2, None), (vec![0, 1], id(1))); + assert_eq!(page(false, 2, Some(1)), (vec![2, 3], id(3))); + assert_eq!(page(false, 2, Some(3)), (vec![4], None)); + assert_eq!(page(true, 2, None), (vec![4, 3], id(3))); + assert_eq!(page(true, 2, Some(3)), (vec![2, 1], id(1))); + assert_eq!(page(true, 2, Some(1)), (vec![0], None)); + assert_eq!(page(false, 5, None), (vec![0, 1, 2, 3, 4], None)); + assert_eq!(page(false, 10, Some(u64::MAX)), (Vec::new(), None)); + assert_eq!(page(true, 10, Some(u64::MAX)), (vec![4, 3, 2, 1, 0], None)); + + let created = WirePageQuery { + order: WirePageOrder::Created, + limit: 2, + ..WirePageQuery::default() + }; + assert_eq!( + partition_ids(&streams, 0, created).unwrap(), + (vec![0, 1], id(1)), + "partition ids follow creation" + ); + } + + #[test] + fn given_a_page_block_partitions_cannot_serve_when_paging_should_refuse_it() { + let streams = topic_with_partitions(3); + let refused = [ + WirePageQuery { + cursor: Some(WirePageCursor::Created { + created_at: 1, + id: 0, + }), + ..WirePageQuery::default() + }, + WirePageQuery { + name: Some(WireName::new("p").unwrap()), + ..WirePageQuery::default() + }, + WirePageQuery { + limit: 0, + ..WirePageQuery::default() + }, + WirePageQuery { + limit: 1001, + ..WirePageQuery::default() + }, + ]; + for query in refused { + assert_eq!( + partition_ids(&streams, 0, query.clone()), + Err(IggyError::InvalidCommand), + "{query:?}" + ); + } + assert_eq!( + partition_ids(&streams, 7, WirePageQuery::default()), + Err(IggyError::StreamIdNotFound(Identifier::default())) + ); + let missing_topic = GetPartitionsRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(7), + page: WirePageQuery::default(), + }; + assert_eq!( + partitions_page(&streams, missing_topic, 0, 1).map(|page| page.items.len()), + Err(IggyError::TopicIdNotFound( + Identifier::default(), + Identifier::default() + )) + ); + } + + /// Applies one fixture request at `micros`, as a commit does. + fn apply_at<R: StateHandler>(request: &R, state: &mut R::State, micros: u64) { + let reply = request.apply(state, IggyTimestamp::from(micros)); + assert_eq!(reply.code, 0, "the fixture request applies"); + } + + fn create_stream(name: &str) -> CreateStreamRequest { + CreateStreamRequest { + name: WireName::new(name).unwrap(), + options: WireOptions::empty(), + } + } + + /// A topic of stream 0 without partitions, so that a delete of it ends in + /// its own apply. + fn create_topic(name: &str) -> CreateTopicWithAssignmentsRequest { + CreateTopicWithAssignmentsRequest { + request: CreateTopicRequest { + stream_id: WireIdentifier::numeric(0), + partitions_count: 0, + name: WireName::new(name).unwrap(), + options: WireOptions::empty(), + }, + derived_options: WireOptions::empty(), + partitions: Vec::new(), + } + } + + fn create_user(username: &str) -> CreateUserRequest { + CreateUserRequest { + username: WireName::new(username).unwrap(), + password: "hash".to_owned(), + status: 1, + permissions: None, + options: WireOptions::empty(), + } + } + + /// Streams `a` to `e`, then `b` deleted and `f` created in its id: the id + /// order is `a f c d e`, the creation order `a c d e f`. Stream `a` holds + /// the topics `ta` to `tc`, then `ta` deleted and `td` created in its id: + /// the id order is `td tb tc`, the creation order `tb tc td`. Topic `tb` + /// holds the groups `g0` to `g4`. + fn paged_streams() -> StreamsInner { + let mut streams = StreamsInner::new(); + for (micros, name) in [(10, "a"), (20, "b"), (30, "c"), (40, "d"), (50, "e")] { + apply_at(&create_stream(name), &mut streams, micros); + } + let delete_stream = DeleteStreamRequest { + stream_id: WireIdentifier::numeric(1), + }; + apply_at(&delete_stream, &mut streams, 60); + apply_at(&create_stream("f"), &mut streams, 70); + for (micros, name) in [(80, "ta"), (90, "tb"), (100, "tc")] { + apply_at(&create_topic(name), &mut streams, micros); + } + let delete_topic = DeleteTopicRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(0), + }; + apply_at(&delete_topic, &mut streams, 110); + apply_at(&create_topic("td"), &mut streams, 120); + for (micros, name) in [ + (130, "g0"), + (140, "g1"), + (150, "g2"), + (160, "g3"), + (170, "g4"), + ] { + let create_group = CreateConsumerGroupRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(1), + name: WireName::new(name).unwrap(), + }; + apply_at(&create_group, &mut streams, micros); + } + streams + } + + /// Walks every page of `order` in both directions at each limit up to one + /// past the entry count, and checks the names against `ascending` and the + /// number of pages read. + fn assert_walks<T>( + order: WirePageOrder, + ascending: &[&str], + read_page: impl Fn(WirePageQuery) -> PageResponse<T>, + name: impl Fn(&T) -> &str, + ) { + for descending in [false, true] { + let mut expected = ascending.to_vec(); + if descending { + expected.reverse(); + } + for limit in 1..=expected.len() + 1 { + let (items, pages) = walk_pages(|cursor| { + read_page(WirePageQuery { + order, + descending, + limit: u32::try_from(limit).unwrap(), + cursor, + ..WirePageQuery::default() + }) + }); + let names: Vec<&str> = items.iter().map(&name).collect(); + let case = format!("{order:?} descending={descending} limit={limit}"); + assert_eq!(names, expected, "{case}"); + assert_eq!(pages, expected.len().div_ceil(limit), "{case}"); + } + } + } + + #[test] + fn given_a_reused_stream_id_when_paging_streams_should_walk_each_order_both_ways() { + let streams = paged_streams(); + let read_page = |page| streams_page(&streams, page, PAGE_BUDGET).unwrap().0; + assert_walks( + WirePageOrder::Id, + &["a", "f", "c", "d", "e"], + read_page, + |stream| stream.name.as_str(), + ); + assert_walks( + WirePageOrder::Created, + &["a", "c", "d", "e", "f"], + read_page, + |stream| stream.name.as_str(), + ); + } + + #[test] + fn given_creates_and_deletes_between_pages_when_walking_should_list_each_lasting_stream_once() { + let cases = [ + // `g` takes id 0 behind the cursor, `h` takes id 3 ahead of it. + (WirePageOrder::Id, ["a", "f", "c", "h", "e"].as_slice()), + ( + WirePageOrder::Created, + ["a", "c", "e", "f", "g", "h"].as_slice(), + ), + ]; + for (order, expected) in cases { + let mut streams = paged_streams(); + let page = |streams: &StreamsInner, cursor| { + let query = WirePageQuery { + order, + limit: 2, + cursor, + ..WirePageQuery::default() + }; + streams_page(streams, query, PAGE_BUDGET).unwrap().0 + }; + let first = page(&streams, None); + for (stream_id, micros) in [(0, 180), (3, 190)] { + let delete = DeleteStreamRequest { + stream_id: WireIdentifier::numeric(stream_id), + }; + apply_at(&delete, &mut streams, micros); + } + apply_at(&create_stream("g"), &mut streams, 200); + apply_at(&create_stream("h"), &mut streams, 210); + let resume = first.next.expect("a second page"); + let (rest, _) = walk_pages(|cursor| page(&streams, Some(cursor.unwrap_or(resume)))); + let names: Vec<&str> = first + .items + .iter() + .chain(&rest) + .map(|stream| stream.name.as_str()) + .collect(); + assert_eq!(names, expected, "{order:?} order"); + } + } + + #[test] + fn given_a_reused_topic_id_when_paging_topics_should_walk_each_order_both_ways() { + let streams = paged_streams(); + let read_page = |page| { + let request = GetTopicsRequest { + stream_id: WireIdentifier::numeric(0), + page, + }; + topics_page(&streams, request, PAGE_BUDGET).unwrap().0 + }; + assert_walks(WirePageOrder::Id, &["td", "tb", "tc"], read_page, |topic| { + topic.name.as_str() + }); + assert_walks( + WirePageOrder::Created, + &["tb", "tc", "td"], + read_page, + |topic| topic.name.as_str(), + ); + + let missing_stream = GetTopicsRequest { + stream_id: WireIdentifier::numeric(9), + page: WirePageQuery::default(), + }; + let (page, skipped) = topics_page(&streams, missing_stream, PAGE_BUDGET).unwrap(); + assert_eq!( + (page.items.len(), page.next, skipped.len()), + (0, None, 0), + "a missing stream lists as an empty last page" + ); + let stream_deleted_during_the_walk = GetTopicsRequest { + stream_id: WireIdentifier::numeric(9), + page: WirePageQuery { + cursor: Some(WirePageCursor::Id(0)), + ..WirePageQuery::default() + }, + }; + assert!( + matches!( + topics_page(&streams, stream_deleted_during_the_walk, PAGE_BUDGET), + Err(IggyError::StreamIdNotFound(_)) + ), + "a page after the first one needs its stream" + ); + } + + #[test] + fn given_a_reused_user_id_when_paging_users_should_start_the_creation_order_at_root() { + let mut users = UsersInner::new(); + for (micros, username) in [(10, "root"), (20, "bravo"), (30, "charlie"), (40, "delta")] { + apply_at(&create_user(username), &mut users, micros); + } + let delete_user = DeleteUserRequest { + user_id: WireIdentifier::numeric(1), + }; + apply_at(&delete_user, &mut users, 50); + apply_at(&create_user("echo"), &mut users, 60); + let read_page = |page| users_page(&users, page, PAGE_BUDGET).unwrap().0; + assert_walks( + WirePageOrder::Id, + &["root", "echo", "charlie", "delta"], + read_page, + |user| user.username.as_str(), + ); + assert_walks( + WirePageOrder::Created, + &["root", "charlie", "delta", "echo"], + read_page, + |user| user.username.as_str(), + ); + } + + #[test] + fn given_consumer_groups_when_paging_should_walk_ids_for_each_order() { + let streams = paged_streams(); + let request = |topic_id, page| GetConsumerGroupsRequest { + stream_id: WireIdentifier::numeric(0), + topic_id: WireIdentifier::numeric(topic_id), + page, + }; + let read_page = + |page| consumer_groups_page(&streams, request(1, page), PAGE_BUDGET).unwrap(); + let groups = ["g0", "g1", "g2", "g3", "g4"]; + for order in [WirePageOrder::Id, WirePageOrder::Created] { + assert_walks(order, &groups, read_page, |group| group.name.as_str()); + } + let created = WirePageQuery { + order: WirePageOrder::Created, + limit: 2, + ..WirePageQuery::default() + }; + assert!( + matches!(read_page(created).next, Some(WirePageCursor::Id(_))), + "a creation walk of groups goes on with an id cursor" + ); + + let created_cursor = WirePageQuery { + order: WirePageOrder::Created, + cursor: Some(WirePageCursor::Created { + created_at: 130, + id: 0, + }), + ..WirePageQuery::default() + }; + assert_eq!( + consumer_groups_page(&streams, request(1, created_cursor), PAGE_BUDGET) + .map(|page| page.items.len()), + Err(IggyError::InvalidCommand) + ); + assert_eq!( + consumer_groups_page(&streams, request(9, WirePageQuery::default()), PAGE_BUDGET) + .map(|page| page.items.len()), + Err(IggyError::TopicIdNotFound( + Identifier::default(), + Identifier::default() + )) + ); + let missing_stream = GetConsumerGroupsRequest { + stream_id: WireIdentifier::numeric(9), + ..request(1, WirePageQuery::default()) + }; + assert_eq!( + consumer_groups_page(&streams, missing_stream, PAGE_BUDGET) + .map(|page| page.items.len()), + Err(IggyError::StreamIdNotFound(Identifier::default())) + ); + } + + #[test] + fn given_a_name_filter_when_paging_streams_should_bound_the_scan_of_each_page() { + let streams = paged_streams(); + let two_scanned = PageBudget { + scanned_entries: 2, + ..PAGE_BUDGET + }; + let filtered = |name: &str, cursor| WirePageQuery { + name: Some(WireName::new(name).unwrap()), + cursor, + ..WirePageQuery::default() + }; + let read_page = |name, cursor| { + streams_page(&streams, filtered(name, cursor), two_scanned) + .unwrap() + .0 + }; + + let first = read_page("z", None); + assert_eq!( + (first.items.len(), first.next), + (0, Some(WirePageCursor::Id(1))), + "streams a and f scanned" + ); + let (found, pages) = walk_pages(|cursor| read_page("z", cursor)); + assert_eq!( + (found.len(), pages), + (0, 3), + "five streams, two scanned per page" + ); + let (found, _) = walk_pages(|cursor| read_page("d", cursor)); + let names: Vec<&str> = found.iter().map(|stream| stream.name.as_str()).collect(); + assert_eq!(names, ["d"]); + } + + #[test] + fn given_a_cursor_of_the_other_order_when_paging_should_refuse_it() { + let streams = paged_streams(); + let users = UsersInner::new(); + let created_cursor = WirePageCursor::Created { + created_at: 10, + id: 0, + }; + for (order, cursor) in [ + (WirePageOrder::Id, created_cursor), + (WirePageOrder::Created, WirePageCursor::Id(0)), + ] { + let page = WirePageQuery { + order, + cursor: Some(cursor), + ..WirePageQuery::default() + }; + assert_eq!( + streams_page(&streams, page.clone(), PAGE_BUDGET).map(|(page, _)| page.items.len()), + Err(IggyError::InvalidCommand), + "streams in {order:?} order" + ); + let missing_stream = GetTopicsRequest { + stream_id: WireIdentifier::numeric(9), + page: page.clone(), + }; + assert_eq!( + topics_page(&streams, missing_stream, PAGE_BUDGET) + .map(|(page, _)| page.items.len()), + Err(IggyError::InvalidCommand), + "the query is checked before the stream, in {order:?} order" + ); + assert_eq!( + users_page(&users, page, PAGE_BUDGET).map(|(page, _)| page.items.len()), + Err(IggyError::InvalidCommand), + "users in {order:?} order" + ); + } + } }
diff --git a/core/shard/src/poll/completion_tests.rs b/core/shard/src/poll/completion_tests.rs index f4e4807..1990600 100644 --- a/core/shard/src/poll/completion_tests.rs +++ b/core/shard/src/poll/completion_tests.rs
@@ -221,7 +221,7 @@ }; let op = install_group_owner(&mut partition, &config, installation).await; assert!(group.complete_revocation(0, &installation, op)); - topic.consumer_groups.insert(group_id, group); + topic.consumer_groups.insert(group_id, Box::new(group)); } stream.topics.insert(topic); inner.items.insert(stream); @@ -927,7 +927,7 @@ let mut topic = self.topic.clone(); topic .consumer_groups - .insert(BOUND_GROUP, self.group.clone()); + .insert(BOUND_GROUP, Box::new(self.group.clone())); stream.topics.insert(topic); let mut inner = StreamsInner::default(); inner.items.insert(stream); @@ -1264,7 +1264,7 @@ group.rebalance_members(&topic.partitions, 11, 2); assert!(group.assignments[&1].pending.is_some()); } - topic.consumer_groups.insert(GROUP, group); + topic.consumer_groups.insert(GROUP, Box::new(group)); stream.topics.insert(topic); inner.items.insert(stream); let metadata = PollTestMetadata::new((Users::default(), (inner.into(), ())));
diff --git a/core/shard/src/poll/deferred_tests.rs b/core/shard/src/poll/deferred_tests.rs index f20df63..2701357 100644 --- a/core/shard/src/poll/deferred_tests.rs +++ b/core/shard/src/poll/deferred_tests.rs
@@ -124,7 +124,7 @@ let op = install_group_owner(partition, &config, installation).await; assert!(group.complete_revocation(id, &installation, op)); } - topic.consumer_groups.insert(0, group); + topic.consumer_groups.insert(0, Box::new(group)); stream.topics.insert(topic); inner.items.insert(stream); let users = Users::default();
diff --git a/examples/node/package-lock.json b/examples/node/package-lock.json index 37cfba8..2cdc50c 100644 --- a/examples/node/package-lock.json +++ b/examples/node/package-lock.json
@@ -23,7 +23,7 @@ }, "../../foreign/node": { "name": "apache-iggy", - "version": "0.11.0", + "version": "0.11.1-edge.1", "license": "Apache-2.0", "dependencies": { "@node-rs/xxhash": "1.7.8",
diff --git a/examples/python/uv.lock b/examples/python/uv.lock index 765c612..aad6f55 100644 --- a/examples/python/uv.lock +++ b/examples/python/uv.lock
@@ -8,7 +8,7 @@ [[package]] name = "apache-iggy" -version = "0.10.0" +version = "0.10.1.dev1" source = { directory = "../../foreign/python" } [package.metadata]
diff --git a/foreign/cpp/BUILD.bazel b/foreign/cpp/BUILD.bazel index 6175a1d..ca5597e 100644 --- a/foreign/cpp/BUILD.bazel +++ b/foreign/cpp/BUILD.bazel
@@ -243,6 +243,7 @@ ], }), data = [ + "tests/fixtures/list_pages.json", "tests/fixtures/metadata_changes.json", "tests/fixtures/resource_options.json", ],
diff --git a/foreign/cpp/Cargo.toml b/foreign/cpp/Cargo.toml index c3c143b..5644b79 100644 --- a/foreign/cpp/Cargo.toml +++ b/foreign/cpp/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy-cpp" -version = "0.2.0" +version = "0.2.1" edition = "2024" license = "Apache-2.0"
diff --git a/foreign/cpp/MODULE.bazel b/foreign/cpp/MODULE.bazel index e52b770..4ab94b5 100644 --- a/foreign/cpp/MODULE.bazel +++ b/foreign/cpp/MODULE.bazel
@@ -17,7 +17,7 @@ module( name = "iggy_cpp", - version = "0.2.0", + version = "0.2.1", ) bazel_dep(name = "rules_cc", version = "0.2.27")
diff --git a/foreign/cpp/README.md b/foreign/cpp/README.md index 941ec65..bb67e18 100644 --- a/foreign/cpp/README.md +++ b/foreign/cpp/README.md
@@ -108,10 +108,12 @@ - `StoreConsumerOffset`, `StoreConsumerPosition`, `DeleteConsumerOffset`, and `DeleteConsumerPosition`. - `PollMessages`, `PendingPoll::Wait`, `Reader`, and the calls of `PartitionReader`. - `GetMetadataChanges`. +- `GetStreamsPage`, `GetTopicsPage`, `GetPartitionsPage`, `GetConsumerGroupsPage`, and `GetUsersPage`. -Other methods, including `Connect`, `Disconnect`, and `Shutdown`, report errors through the exception message only. C++ and bridge-local argument errors also leave `Code()` and `OperationId()` empty and `Kind()` empty, including for the methods listed above. `GetMetadataChanges` is the exception: it reports every invalid query as `invalid_command`, including one the bridge refuses. +Other methods, including `Connect`, `Disconnect`, and `Shutdown`, report errors through the exception message only. C++ and bridge-local argument errors also leave `Code()` and `OperationId()` empty and `Kind()` empty, including for the methods listed above. `GetMetadataChanges` and the page methods are the exception: they report every invalid query as `invalid_command`, including one the bridge refuses. -Direct generated-bridge callers pass a local `iggy::ffi::ErrorInfo` as the last argument to login/logout, mutations, polls, raw commands, recovery calls, and the metadata change functions. It is reset at entry and populated only when the Rust SDK returns an `IggyError`. Bridge-local argument errors leave it empty, except in the metadata change functions, which record invalid input as `invalid_command`. +Direct generated-bridge callers pass a local `iggy::ffi::ErrorInfo` as the last argument to login/logout, mutations, polls, raw commands, recovery calls, and the metadata change functions. The page functions take it as the last argument too. +It is reset at entry and populated only when the Rust SDK returns an `IggyError`. Bridge-local argument errors leave it empty, except in the metadata change functions, which record invalid input as `invalid_command`. The page functions record an invalid query as `invalid_command` too. `send_binary_request_to_replica(code, payload, replica_id, error_info)` sends a raw command to one node of a cluster, named by the replica id that cluster metadata returns. @@ -179,6 +181,40 @@ HTTP continues to use its configured transport behavior and has no retained operation recovery. +## List pages + +`GetStreamsPage()`, `GetTopicsPage()`, `GetPartitionsPage()`, `GetConsumerGroupsPage()` and `GetUsersPage()` read one page of a list. A page holds `Items()` and `Next()`, the cursor text of the next page. `Next()` is absent on the last page. + +A `PageQuery` sets the order, the direction, the limit and the cursor. The order is `PageOrder::Id` or `PageOrder::Created`, and the limit is 1 to 1000, 100 by default. A `NamedPageQuery` holds a `PageQuery` in `Page()` and adds a name filter. The streams, topics, consumer groups and users page methods take a `NamedPageQuery`. `GetPartitionsPage()` takes a `PageQuery`, which has no name. + +```cpp +// Reads every stream whose name holds "orders", 50 streams per page. +void PrintOrderStreams(iggy::IggyBlockingClient &client) { + iggy::NamedPageQuery query(iggy::PageQuery().SetLimit(50)); + query.SetName("orders"); + while (true) { + const auto page = client.GetStreamsPage(query); + for (const auto &stream : page.Items()) { + Print(stream); + } + if (!page.Next()) { + break; + } + query.Page().SetCursor(*page.Next()); + } +} +``` + +A cursor is valid only with the order, direction, name and parent of the query that returned it. If you pass `Next()` back, keep the other settings of the query. A page can be short or empty and still have a `Next()`. The name filter is case-sensitive text of 1 to 255 bytes. + +An invalid query is refused with `invalid_command` (3) before anything is sent. Over TCP, QUIC and WebSocket, the server refuses a cursor of another order with `invalid_command` too. Over HTTP, a refusal of the server arrives as `http_response_error` (300). + +Each transport reads pages through the Rust SDK, and the Rust integration tests cover all four transports. The E2E tests of this binding read pages over TCP only. + +`GetStreams()`, `GetTopics()`, `GetConsumerGroups()` and `GetUsers()` return the whole list. Over TCP, QUIC and WebSocket, they read pages of 1000 in id order, so the result is not one consistent read. If the server answers a page with the cursor it was sent, they throw, because such a walk never ends. Over HTTP, the server builds the list from its pages and sends one reply. + +Over TCP, QUIC and WebSocket, the `GetTopic()` reply of a topic with very many partitions can be too large. The server then sends the error `reply_too_large` (97) in place of the reply. `GetTopic()` reports it through the exception message only. `GetPartitionsPage()` reads those partitions in smaller replies. + ## Metadata changes `GetMetadataChanges()` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `Next()` cursor. The call needs root or the global `manage_servers` permission and works on every transport.
diff --git a/foreign/cpp/include/iggy.hpp b/foreign/cpp/include/iggy.hpp index 6ac1c7a..462912e 100644 --- a/foreign/cpp/include/iggy.hpp +++ b/foreign/cpp/include/iggy.hpp
@@ -85,6 +85,11 @@ class MetadataChangesQuery; class MetadataCurrentItem; class MetadataCurrentPageToken; +class StreamsPage; +class TopicsPage; +class PartitionsPage; +class ConsumerGroupsPage; +class UsersPage; namespace detail { /** @brief Internal base for string-backed option types. */ @@ -116,8 +121,8 @@ * Code() and Kind() are available only when a call forwards a typed Rust SDK * error. IggyBlockingClient documents the covered methods. Other calls and * C++ or bridge-local argument errors leave Code() empty and Kind() empty, - * except the metadata change calls, which report invalid input with the kind - * each one documents. + * except the metadata change calls and the page calls, which report invalid + * input with the kind each one documents. * OperationId() is present only for operation_uncertain, lane_blocked, * operation_not_retained, partition_lane_blocked and fetch_progress_uncertain * errors and preserves the full unsigned 64-bit ID. BlockedPartitionId() is @@ -1255,6 +1260,7 @@ static UserInfo FromFfi(ffi::UserInfo user); friend class IggyBlockingClient; + friend class UsersPage; std::uint32_t id_; std::uint64_t created_at_; @@ -1475,6 +1481,7 @@ friend class IggyBlockingClient; friend class StreamDetails; + friend class TopicsPage; std::uint32_t id_; std::uint64_t created_at_; @@ -1635,6 +1642,7 @@ static Partition FromFfi(ffi::Partition partition); friend class TopicDetails; + friend class PartitionsPage; std::uint32_t id_; std::uint64_t created_at_; @@ -2065,6 +2073,7 @@ static Stream FromFfi(ffi::Stream stream); friend class IggyBlockingClient; + friend class StreamsPage; std::uint32_t id_; std::uint64_t created_at_; @@ -2159,6 +2168,7 @@ static ConsumerGroup FromFfi(ffi::ConsumerGroup group); friend class IggyBlockingClient; + friend class ConsumerGroupsPage; std::uint32_t id_; std::string name_; @@ -5920,6 +5930,250 @@ std::optional<MetadataCurrentPageToken> current_page_token_; }; +/** @brief The order of a list page. The values are the wire codes. */ +enum class PageOrder : std::uint8_t { + Id = 0, ///< By numeric ID. + Created = 1, ///< By creation. Entries with one creation time keep the order of their IDs. +}; + +/** + * @brief One page request of a list. + * + * A new query reads the first page of up to kDefaultLimit entries in + * ascending ID order. To read the next page, pass the Next() of the page to + * SetCursor() and keep the other settings. + * + * GetPartitionsPage() takes this query. The lists of named entities take a + * NamedPageQuery, which holds this query and adds a name filter. + * + * The page methods of IggyBlockingClient refuse a query with Kind() + * invalid_command before anything is sent when the limit is outside 1 to + * kMaxLimit or the cursor is not a text that Next() can return. Over TCP, + * QUIC, and WebSocket the server refuses with invalid_command a cursor of + * another order. HTTP reports this refusal as http_response_error (300). + */ +class PageQuery final { + public: + static constexpr std::uint32_t kDefaultLimit = 100; + static constexpr std::uint32_t kMaxLimit = 1000; + + /** @brief Returns the order of the entries. */ + [[nodiscard]] PageOrder Order() const noexcept { return order_; } + + /** @brief Returns whether the entries come in descending order. */ + [[nodiscard]] bool Descending() const noexcept { return descending_; } + + /** @brief Returns the most entries one page returns. */ + [[nodiscard]] std::uint32_t Limit() const noexcept { return limit_; } + + /** @brief Returns the cursor text of the page to read, absent for the first page. */ + [[nodiscard]] const std::optional<std::string> &Cursor() const noexcept { return cursor_; } + + /** + * @brief Sets the order of the entries. + * @param order The default is PageOrder::Id. + * @return Reference to this query. + */ + PageQuery &SetOrder(PageOrder order) { + order_ = order; + return *this; + } + + /** + * @brief Sets the direction of the order. + * @param descending The default is false, ascending. + * @return Reference to this query. + */ + PageQuery &SetDescending(bool descending) { + descending_ = descending; + return *this; + } + + /** + * @brief Sets the most entries one page returns. + * @param limit From 1 to kMaxLimit. The default is kDefaultLimit. + * @return Reference to this query. + */ + PageQuery &SetLimit(std::uint32_t limit) { + limit_ = limit; + return *this; + } + + /** + * @brief Sets the page to read. + * @param cursor The Next() text of the previous page, unchanged. It is + * valid only with the order, direction, name filter, and parent of + * the query that returned it. + * @return Reference to this query. + */ + PageQuery &SetCursor(std::string cursor) { + cursor_ = std::move(cursor); + return *this; + } + + private: + [[nodiscard]] ffi::PageQuery ToFfi() const; + + friend class IggyBlockingClient; + friend class NamedPageQuery; + + PageOrder order_{PageOrder::Id}; + bool descending_{}; + std::uint32_t limit_{kDefaultLimit}; + std::optional<std::string> cursor_; +}; + +/** + * @brief One page request of a list of named entities: streams, topics, + * consumer groups, and users. + * + * It holds a PageQuery and adds a name filter. To read the next page, pass + * the Next() of the page to Page().SetCursor() and keep the other settings. + * + * The page methods of IggyBlockingClient refuse it with Kind() + * invalid_command before anything is sent when they refuse its PageQuery, + * or when the name is empty, longer than 255 bytes, or not UTF-8. + */ +class NamedPageQuery final { + public: + NamedPageQuery() = default; + + /** @brief Builds a query of the page that @p page describes, with no name filter. */ + explicit NamedPageQuery(PageQuery page) : page_(std::move(page)) {} + + /** @brief Returns the order, direction, limit, and cursor of the page. */ + [[nodiscard]] const PageQuery &Page() const noexcept { return page_; } + + /** @brief Returns the page settings to change, such as the cursor of the next page. */ + [[nodiscard]] PageQuery &Page() noexcept { return page_; } + + /** @brief Returns the text that the name of each entry holds, absent for no filter. */ + [[nodiscard]] const std::optional<std::string> &Name() const noexcept { return name_; } + + /** + * @brief Keeps only the entries whose name holds @p name, case-sensitive. + * @param name UTF-8 text of 1 to 255 bytes. + * @return Reference to this query. + */ + NamedPageQuery &SetName(std::string name) { + name_ = std::move(name); + return *this; + } + + private: + [[nodiscard]] ffi::NamedPageQuery ToFfi() const; + + friend class IggyBlockingClient; + + PageQuery page_; + std::optional<std::string> name_; +}; + +/** + * @brief One page of stream summaries. + * + * IggyBlockingClient::GetStreamsPage() returns this value. A page can be + * short or empty and still have a Next(). + */ +class StreamsPage final { + public: + /** @brief Returns the streams of the page. */ + [[nodiscard]] const std::vector<Stream> &Items() const noexcept { return items_; } + + /** @brief Returns the cursor text of the next page, absent on the last page. */ + [[nodiscard]] const std::optional<std::string> &Next() const noexcept { return next_; } + + private: + StreamsPage() = default; + + static StreamsPage FromFfi(ffi::StreamsPage page); + + friend class IggyBlockingClient; + + std::vector<Stream> items_; + std::optional<std::string> next_; +}; + +/** @brief One page of topic summaries. See StreamsPage. */ +class TopicsPage final { + public: + /** @brief Returns the topics of the page. */ + [[nodiscard]] const std::vector<Topic> &Items() const noexcept { return items_; } + + /** @brief Returns the cursor text of the next page, absent on the last page. */ + [[nodiscard]] const std::optional<std::string> &Next() const noexcept { return next_; } + + private: + TopicsPage() = default; + + static TopicsPage FromFfi(ffi::TopicsPage page); + + friend class IggyBlockingClient; + + std::vector<Topic> items_; + std::optional<std::string> next_; +}; + +/** @brief One page of partition summaries. See StreamsPage. */ +class PartitionsPage final { + public: + /** @brief Returns the partitions of the page. */ + [[nodiscard]] const std::vector<Partition> &Items() const noexcept { return items_; } + + /** @brief Returns the cursor text of the next page, absent on the last page. */ + [[nodiscard]] const std::optional<std::string> &Next() const noexcept { return next_; } + + private: + PartitionsPage() = default; + + static PartitionsPage FromFfi(ffi::PartitionsPage page); + + friend class IggyBlockingClient; + + std::vector<Partition> items_; + std::optional<std::string> next_; +}; + +/** @brief One page of consumer group summaries. See StreamsPage. */ +class ConsumerGroupsPage final { + public: + /** @brief Returns the consumer groups of the page. */ + [[nodiscard]] const std::vector<ConsumerGroup> &Items() const noexcept { return items_; } + + /** @brief Returns the cursor text of the next page, absent on the last page. */ + [[nodiscard]] const std::optional<std::string> &Next() const noexcept { return next_; } + + private: + ConsumerGroupsPage() = default; + + static ConsumerGroupsPage FromFfi(ffi::ConsumerGroupsPage page); + + friend class IggyBlockingClient; + + std::vector<ConsumerGroup> items_; + std::optional<std::string> next_; +}; + +/** @brief One page of user summaries. See StreamsPage. */ +class UsersPage final { + public: + /** @brief Returns the users of the page. */ + [[nodiscard]] const std::vector<UserInfo> &Items() const noexcept { return items_; } + + /** @brief Returns the cursor text of the next page, absent on the last page. */ + [[nodiscard]] const std::optional<std::string> &Next() const noexcept { return next_; } + + private: + UsersPage() = default; + + static UsersPage FromFfi(ffi::UsersPage page); + + friend class IggyBlockingClient; + + std::vector<UserInfo> items_; + std::optional<std::string> next_; +}; + /** * @brief Starting position for polling messages. * @@ -6677,12 +6931,14 @@ * - PollMessages(), Reader(), StandaloneConsumer(), GroupConsumer(), * PendingPoll::Wait(), and the calls of PartitionReader and IggyConsumer. * - GetMetadataChanges(). + * - GetStreamsPage(), GetTopicsPage(), GetPartitionsPage(), + * GetConsumerGroupsPage(), and GetUsersPage(). * * Other methods report errors through the exception message only. C++ and * bridge-local argument validation failures also have no structured error - * details, even for the methods listed above. GetMetadataChanges() is the - * exception: it reports every invalid query as invalid_command, including one - * the bridge refuses. + * details, even for the methods listed above. GetMetadataChanges() and the + * page methods are the exception: they report every invalid query as + * invalid_command, including one the bridge refuses. * * @code{.cpp} * auto client{iggy::IggyBlockingClient::Builder() @@ -6927,19 +7183,39 @@ UserInfoDetails GetUser(const Identifier &user); /** - * @brief Lists user summaries visible to the authenticated caller. + * @brief Lists user summaries visible to the authenticated caller, in ID order. * * The summaries omit permissions. Use GetUser() to retrieve one user's * permission assignment. * + * The list is read in pages, so it is not one consistent read: a user + * that someone creates or deletes during the read can appear or not + * appear. Over TCP, QUIC, and WebSocket the client reads pages of 1,000 + * users. Over HTTP the server builds the list from its pages and sends one + * reply. GetUsersPage() reads one page. + * * @return User summaries observed by the server for this request. * @throws IggyException if the client is unavailable or unauthenticated; * the caller lacks read-users or manage-users permission; or the - * request fails. + * request fails. Over TCP, QUIC, and WebSocket it also throws when + * the server answers a page with the cursor it was sent. */ std::vector<UserInfo> GetUsers(); /** + * @brief Reads one page of the user summaries. + * + * @param query Order, direction, limit, cursor, and name filter of the page. + * @return One page of user summaries. + * @throws IggyException with Kind() invalid_command before anything is + * sent when NamedPageQuery refuses @p query. Also if the client is + * unavailable or unauthenticated; the caller lacks read-users or + * manage-users permission; the server refuses the query; or the + * request fails. + */ + UsersPage GetUsersPage(const NamedPageQuery &query); + + /** * @brief Lists the personal access tokens owned by the authenticated caller. * * The result carries token names and expiry only. The server shows a @@ -7099,16 +7375,37 @@ void UpdateStream(const Identifier &stream, const StreamUpdateOptions &options); /** - * @brief Lists stream summaries visible to the authenticated user. + * @brief Lists stream summaries visible to the authenticated user, in ID order. * * The summaries exclude per-topic details. Use GetStream() for those. + * + * The list is read in pages, so it is not one consistent read: a stream + * that someone creates or deletes during the read can appear or not + * appear. Over TCP, QUIC, and WebSocket the client reads pages of 1,000 + * streams. Over HTTP the server builds the list from its pages and sends + * one reply. GetStreamsPage() reads one page. + * * @return Stream summaries visible to the authenticated user. * @throws IggyException if the client is unavailable, the caller lacks - * permission to read streams, or the request fails. + * permission to read streams, or the request fails. Over TCP, + * QUIC, and WebSocket it also throws when the server answers a + * page with the cursor it was sent. */ std::vector<Stream> GetStreams(); /** + * @brief Reads one page of the stream summaries. + * + * @param query Order, direction, limit, cursor, and name filter of the page. + * @return One page of stream summaries. + * @throws IggyException with Kind() invalid_command before anything is + * sent when NamedPageQuery refuses @p query. Also if the client is + * unavailable or unauthenticated; the caller lacks permission to + * read streams; the server refuses the query; or the request fails. + */ + StreamsPage GetStreamsPage(const NamedPageQuery &query); + + /** * @brief Retrieves one stream by numeric ID or name. * * The result includes observed aggregate statistics and topic summaries. @@ -7180,20 +7477,49 @@ void UpdateTopic(const Identifier &stream, const Identifier &topic, const TopicUpdateOptions &options); /** - * @brief Lists topic summaries in a stream. + * @brief Lists topic summaries in a stream, in ID order. * * The returned summaries do not include partition details. Use GetTopic() * when partition offsets, sizes, and segment counts are needed. * + * The list is read in pages, so it is not one consistent read: a topic + * that someone creates or deletes during the read can appear or not + * appear. Over TCP, QUIC, and WebSocket the client reads pages of 1,000 + * topics. Over HTTP the server builds the list from its pages and sends + * one reply. GetTopicsPage() reads one page. + * + * A stream that does not exist gives an empty list. If the stream goes + * missing after the first page, the read fails as GetTopicsPage() does. + * * @param stream Parent stream, addressed by numeric ID or name. * @return Topic summaries visible to the authenticated user. * @throws IggyException if the client is unavailable or unauthenticated; - * the stream does not exist; the caller lacks read permission; or - * the metadata read fails. + * the caller lacks read permission; or the metadata read fails. + * Over TCP, QUIC, and WebSocket it also throws when the server + * answers a page with the cursor it was sent. */ std::vector<Topic> GetTopics(const Identifier &stream); /** + * @brief Reads one page of the topic summaries in a stream. + * + * For a stream that does not exist, the first page is empty and has no + * Next(). A page read with a cursor fails instead, because the stream was + * deleted during the walk. Over TCP, QUIC, and WebSocket the error is + * stream_id_not_found (1009). Over HTTP it is resource_not_found (20). + * + * @param stream Parent stream, addressed by numeric ID or name. + * @param query Order, direction, limit, cursor, and name filter of the page. + * @return One page of topic summaries. + * @throws IggyException with Kind() invalid_command before anything is + * sent when NamedPageQuery refuses @p query. Also if the client is + * unavailable or unauthenticated; the identifier is invalid; the + * caller lacks read permission; the server refuses the query; or + * the request fails. + */ + TopicsPage GetTopicsPage(const Identifier &stream, const NamedPageQuery &query); + + /** * @brief Retrieves one topic and its partition summaries. * * The result is an observed metadata read. Partition offsets and retained @@ -7204,7 +7530,9 @@ * @return Topic metadata and one summary per partition. * @throws IggyException if the client is unavailable or unauthenticated; * the stream or topic does not exist; the caller lacks read - * permission; or the metadata read fails. + * permission; over TCP, QUIC, or WebSocket, the topic has more + * partitions than one reply can hold (server error 97, read them + * with GetPartitionsPage()); or the metadata read fails. */ TopicDetails GetTopic(const Identifier &stream, const Identifier &topic); @@ -7258,6 +7586,24 @@ void DeletePartitions(const Identifier &stream, const Identifier &topic, std::uint32_t partitions_count); /** + * @brief Reads one page of the partition summaries of a topic. + * + * Partition IDs follow creation, so PageOrder::Created reads in ID order + * too. + * + * @param stream Parent stream, addressed by numeric ID or name. + * @param topic Parent topic, addressed by numeric ID or name. + * @param query Order, direction, limit, and cursor of the page. + * @return One page of partition summaries. + * @throws IggyException with Kind() invalid_command before anything is + * sent when PageQuery refuses @p query. Also if the client is + * unavailable or unauthenticated; an identifier is invalid; the + * stream or topic does not exist; the caller lacks read + * permission; the server refuses the query; or the request fails. + */ + PartitionsPage GetPartitionsPage(const Identifier &stream, const Identifier &topic, const PageQuery &query); + + /** * @brief Deletes the oldest sealed segments from one partition. * * The active segment is never deleted. If fewer sealed segments exist than @@ -7322,7 +7668,7 @@ ConsumerGroupDetails GetConsumerGroup(const Identifier &stream, const Identifier &topic, const Identifier &group); /** - * @brief Lists consumer group summaries for a topic. + * @brief Lists consumer group summaries for a topic, in ID order. * * The summaries include member and partition counts but omit individual * member details. Use GetConsumerGroup() to retrieve those details. @@ -7332,16 +7678,43 @@ * result does not establish whether the parent resources exist across * server implementations. * + * The list is read in pages, so it is not one consistent read: a group + * that someone creates or deletes during the read can appear or not + * appear. Over TCP, QUIC, and WebSocket the client reads pages of 1,000 + * groups. Over HTTP the server builds the list from its pages and sends one + * reply. GetConsumerGroupsPage() reads one page. + * * @param stream Parent stream, addressed by numeric ID or name. * @param topic Parent topic, addressed by numeric ID or name. * @return Consumer group summaries for the requested topic. * @throws IggyException if the client is unavailable or unauthenticated; * an identifier is invalid; the stream or topic does not exist; * the caller lacks read permission; or the metadata read fails. + * Over TCP, QUIC, and WebSocket it also throws when the server + * answers a page with the cursor it was sent. */ std::vector<ConsumerGroup> GetConsumerGroups(const Identifier &stream, const Identifier &topic); /** + * @brief Reads one page of the consumer group summaries of a topic. + * + * Group IDs follow creation, so PageOrder::Created reads in ID order too. + * + * @param stream Parent stream, addressed by numeric ID or name. + * @param topic Parent topic, addressed by numeric ID or name. + * @param query Order, direction, limit, cursor, and name filter of the page. + * @return One page of consumer group summaries. + * @throws IggyException with Kind() invalid_command before anything is + * sent when NamedPageQuery refuses @p query. Also if the client is + * unavailable or unauthenticated; an identifier is invalid; the + * stream or topic does not exist; the caller lacks read + * permission; the server refuses the query; or the request fails. + */ + ConsumerGroupsPage GetConsumerGroupsPage(const Identifier &stream, + const Identifier &topic, + const NamedPageQuery &query); + + /** * @brief Deletes a consumer group from a topic. * * A failed or unknown transport outcome can leave the deletion committed.
diff --git a/foreign/cpp/src/client.cpp b/foreign/cpp/src/client.cpp index a038752..071c15b 100644 --- a/foreign/cpp/src/client.cpp +++ b/foreign/cpp/src/client.cpp
@@ -175,6 +175,12 @@ }); } +UsersPage IggyBlockingClient::GetUsersPage(const NamedPageQuery &query) { + return RethrowAsIggyException([this, &query](ffi::ErrorInfo &error_info) { + return UsersPage::FromFfi(Handle()->get_users_page(query.ToFfi(), error_info)); + }); +} + std::vector<PersonalAccessTokenInfo> IggyBlockingClient::GetPersonalAccessTokens() { return RethrowAsIggyException([this] { std::vector<PersonalAccessTokenInfo> tokens; @@ -274,6 +280,12 @@ }); } +StreamsPage IggyBlockingClient::GetStreamsPage(const NamedPageQuery &query) { + return RethrowAsIggyException([this, &query](ffi::ErrorInfo &error_info) { + return StreamsPage::FromFfi(Handle()->get_streams_page(query.ToFfi(), error_info)); + }); +} + StreamDetails IggyBlockingClient::GetStream(const Identifier &stream) { return RethrowAsIggyException( [this, &stream] { return StreamDetails::FromFfi(Handle()->get_stream(stream.ToFfi())); }); @@ -390,6 +402,12 @@ }); } +TopicsPage IggyBlockingClient::GetTopicsPage(const Identifier &stream, const NamedPageQuery &query) { + return RethrowAsIggyException([this, &stream, &query](ffi::ErrorInfo &error_info) { + return TopicsPage::FromFfi(Handle()->get_topics_page(stream.ToFfi(), query.ToFfi(), error_info)); + }); +} + TopicDetails IggyBlockingClient::GetTopic(const Identifier &stream, const Identifier &topic) { return RethrowAsIggyException( [this, &stream, &topic] { return TopicDetails::FromFfi(Handle()->get_topic(stream.ToFfi(), topic.ToFfi())); }); @@ -417,6 +435,15 @@ }); } +PartitionsPage IggyBlockingClient::GetPartitionsPage(const Identifier &stream, + const Identifier &topic, + const PageQuery &query) { + return RethrowAsIggyException([this, &stream, &topic, &query](ffi::ErrorInfo &error_info) { + return PartitionsPage::FromFfi( + Handle()->get_partitions_page(stream.ToFfi(), topic.ToFfi(), query.ToFfi(), error_info)); + }); +} + void IggyBlockingClient::DeleteSegments(const Identifier &stream, const Identifier &topic, const std::uint32_t partition_id, @@ -456,6 +483,15 @@ }); } +ConsumerGroupsPage IggyBlockingClient::GetConsumerGroupsPage(const Identifier &stream, + const Identifier &topic, + const NamedPageQuery &query) { + return RethrowAsIggyException([this, &stream, &topic, &query](ffi::ErrorInfo &error_info) { + return ConsumerGroupsPage::FromFfi( + Handle()->get_consumer_groups_page(stream.ToFfi(), topic.ToFfi(), query.ToFfi(), error_info)); + }); +} + void IggyBlockingClient::DeleteConsumerGroup(const Identifier &stream, const Identifier &topic, const Identifier &group) {
diff --git a/foreign/cpp/src/client.rs b/foreign/cpp/src/client.rs index 74c3be0..c94c7be 100644 --- a/foreign/cpp/src/client.rs +++ b/foreign/cpp/src/client.rs
@@ -47,7 +47,7 @@ use iggy_binary_protocol::{WireDecode, WireEncode}; use iggy_common::{ Credentials as RustCredentials, IggyError, MetadataChangeCursor, MetadataChangeRecord, - MetadataChanges, MetadataChangesQuery, MetadataCurrentItem, MetadataCurrentPageToken, + MetadataChanges, MetadataChangesQuery, MetadataCurrentItem, MetadataCurrentPageToken, Page, PendingOperationsConfig, stream_key_fingerprint, }; use serde::Deserialize; @@ -343,6 +343,19 @@ }) } + pub fn get_streams_page( + &self, + query: ffi::NamedPageQuery, + error_info: &mut ffi::ErrorInfo, + ) -> Result<ffi::StreamsPage, String> { + *error_info = ffi::ErrorInfo::default(); + read_page(query, |query| async move { + self.inner.get_streams_page(&query).await + }) + .inspect_err(|error| error_info.record(error)) + .map_err(|error| format!("Could not get streams page: {error}")) + } + pub fn create_stream( &self, stream_name: String, @@ -788,6 +801,24 @@ }) } + pub fn get_topics_page( + &self, + stream_id: ffi::Identifier, + query: ffi::NamedPageQuery, + error_info: &mut ffi::ErrorInfo, + ) -> Result<ffi::TopicsPage, String> { + *error_info = ffi::ErrorInfo::default(); + let rust_stream_id = RustIdentifier::try_from(stream_id).map_err(|error| { + format!("Could not get topics page: invalid stream identifier: {error}") + })?; + let stream_id = &rust_stream_id; + read_page(query, |query| async move { + self.inner.get_topics_page(stream_id, &query).await + }) + .inspect_err(|error| error_info.record(error)) + .map_err(|error| format!("Could not get topics page on stream '{rust_stream_id}': {error}")) + } + pub fn update_topic( &self, stream_id: ffi::Identifier, @@ -908,6 +939,34 @@ }) } + pub fn get_partitions_page( + &self, + stream_id: ffi::Identifier, + topic_id: ffi::Identifier, + query: ffi::PageQuery, + error_info: &mut ffi::ErrorInfo, + ) -> Result<ffi::PartitionsPage, String> { + *error_info = ffi::ErrorInfo::default(); + let rust_stream_id = RustIdentifier::try_from(stream_id).map_err(|error| { + format!("Could not get partitions page: invalid stream identifier: {error}") + })?; + let rust_topic_id = RustIdentifier::try_from(topic_id).map_err(|error| { + format!("Could not get partitions page: invalid topic identifier: {error}") + })?; + let (stream_id, topic_id) = (&rust_stream_id, &rust_topic_id); + read_page(query, |query| async move { + self.inner + .get_partitions_page(stream_id, topic_id, &query) + .await + }) + .inspect_err(|error| error_info.record(error)) + .map_err(|error| { + format!( + "Could not get partitions page for topic '{rust_topic_id}' on stream '{rust_stream_id}': {error}" + ) + }) + } + pub fn delete_segments( &self, stream_id: ffi::Identifier, @@ -1029,6 +1088,34 @@ }) } + pub fn get_consumer_groups_page( + &self, + stream_id: ffi::Identifier, + topic_id: ffi::Identifier, + query: ffi::NamedPageQuery, + error_info: &mut ffi::ErrorInfo, + ) -> Result<ffi::ConsumerGroupsPage, String> { + *error_info = ffi::ErrorInfo::default(); + let rust_stream_id = RustIdentifier::try_from(stream_id).map_err(|error| { + format!("Could not get consumer groups page: invalid stream identifier: {error}") + })?; + let rust_topic_id = RustIdentifier::try_from(topic_id).map_err(|error| { + format!("Could not get consumer groups page: invalid topic identifier: {error}") + })?; + let (stream_id, topic_id) = (&rust_stream_id, &rust_topic_id); + read_page(query, |query| async move { + self.inner + .get_consumer_groups_page(stream_id, topic_id, &query) + .await + }) + .inspect_err(|error| error_info.record(error)) + .map_err(|error| { + format!( + "Could not get consumer groups page for topic '{rust_topic_id}' on stream '{rust_stream_id}': {error}" + ) + }) + } + pub fn delete_consumer_group( &self, stream_id: ffi::Identifier, @@ -1551,6 +1638,19 @@ }) } + pub fn get_users_page( + &self, + query: ffi::NamedPageQuery, + error_info: &mut ffi::ErrorInfo, + ) -> Result<ffi::UsersPage, String> { + *error_info = ffi::ErrorInfo::default(); + read_page(query, |query| async move { + self.inner.get_users_page(&query).await + }) + .inspect_err(|error| error_info.record(error)) + .map_err(|error| format!("Could not get users page: {error}")) + } + #[allow(clippy::too_many_arguments)] pub fn create_user( &self, @@ -1841,6 +1941,21 @@ .map_err(|error| format!("Could not decode the metadata current item: {error}")) } +/// Parses and validates the query before anything is sent, then reads one page. +fn read_page<FfiQuery, Query, T, P, Read, Reply>( + query: FfiQuery, + read: Read, +) -> Result<P, IggyError> +where + Query: TryFrom<FfiQuery, Error = IggyError>, + Read: FnOnce(Query) -> Reply, + Reply: Future<Output = Result<Page<T>, IggyError>>, + P: From<Page<T>>, +{ + let query = Query::try_from(query)?; + RUNTIME.block_on(read(query)).map(P::from) +} + fn is_option_error(error: &IggyError) -> bool { matches!( error, @@ -1984,6 +2099,18 @@ } #[test] + fn given_reply_too_large_when_recording_should_keep_its_code_and_kind() { + let mut info = ffi::ErrorInfo::default(); + + info.record(&IggyError::ReplyTooLarge); + + assert_eq!(info.code, 97); + assert_eq!(info.kind, "reply_too_large"); + assert!(!info.has_operation_id); + assert!(!info.has_blocked_partition_id); + } + + #[test] fn should_clear_the_previous_error_info_when_a_poll_rejects_its_arguments() { let client = Client { inner: Arc::new(RustIggyClient::default()),
diff --git a/foreign/cpp/src/lib.rs b/foreign/cpp/src/lib.rs index 326fc09..67b73dc 100644 --- a/foreign/cpp/src/lib.rs +++ b/foreign/cpp/src/lib.rs
@@ -926,6 +926,65 @@ current_page_token: MetadataCurrentPageToken, } + /// The order of a list page. The values are the wire codes. + #[repr(u8)] + enum PageOrder { + Id = 0, + Created = 1, + } + + /// One list page query. The cursor travels as bytes, so the bridge refuses + /// text that is not UTF-8 with InvalidCommand. The flag keeps an absent + /// cursor apart from an empty one, which is refused. + struct PageQuery { + order: PageOrder, + descending: bool, + limit: u32, + has_cursor: bool, + cursor: Vec<u8>, + } + + /// One page query of a list of named entities: streams, topics, consumer + /// groups and users. The name travels as bytes with a flag, as the cursor + /// does. + struct NamedPageQuery { + page: PageQuery, + has_name: bool, + name: Vec<u8>, + } + + /// One page of a list, with one struct for each list. `next` is the + /// `pg1_` text of the cursor of the next page when `has_next` is set. + struct StreamsPage { + items: Vec<Stream>, + has_next: bool, + next: String, + } + + struct TopicsPage { + items: Vec<Topic>, + has_next: bool, + next: String, + } + + struct PartitionsPage { + items: Vec<Partition>, + has_next: bool, + next: String, + } + + struct ConsumerGroupsPage { + items: Vec<ConsumerGroup>, + has_next: bool, + next: String, + } + + struct UsersPage { + items: Vec<UserInfo>, + has_next: bool, + next: String, + } + extern "Rust" { /// The private part of a batch: the partition context and the reader /// stamp of its checkpoints, and its continuation. @@ -982,6 +1041,13 @@ error_info: &mut ErrorInfo, ) -> Result<()>; fn get_streams(self: &Client) -> Result<Vec<Stream>>; + /// Reads one page of the streams. An invalid query fails with + /// InvalidCommand (3) before anything is sent, as on the other page calls. + fn get_streams_page( + self: &Client, + query: NamedPageQuery, + error_info: &mut ErrorInfo, + ) -> Result<StreamsPage>; fn get_stream(self: &Client, stream_id: Identifier) -> Result<StreamDetails>; fn delete_stream( self: &Client, @@ -1001,6 +1067,12 @@ topic_id: Identifier, ) -> Result<TopicDetails>; fn get_topics(self: &Client, stream_id: Identifier) -> Result<Vec<Topic>>; + fn get_topics_page( + self: &Client, + stream_id: Identifier, + query: NamedPageQuery, + error_info: &mut ErrorInfo, + ) -> Result<TopicsPage>; fn update_topic( self: &Client, stream_id: Identifier, @@ -1028,6 +1100,13 @@ partitions_count: u32, error_info: &mut ErrorInfo, ) -> Result<()>; + fn get_partitions_page( + self: &Client, + stream_id: Identifier, + topic_id: Identifier, + query: PageQuery, + error_info: &mut ErrorInfo, + ) -> Result<PartitionsPage>; fn create_consumer_group( self: &Client, stream_id: Identifier, @@ -1046,6 +1125,13 @@ stream_id: Identifier, topic_id: Identifier, ) -> Result<Vec<ConsumerGroup>>; + fn get_consumer_groups_page( + self: &Client, + stream_id: Identifier, + topic_id: Identifier, + query: NamedPageQuery, + error_info: &mut ErrorInfo, + ) -> Result<ConsumerGroupsPage>; fn delete_consumer_group( self: &Client, stream_id: Identifier, @@ -1395,6 +1481,11 @@ ) -> Result<()>; fn get_user(self: &Client, user_id: Identifier) -> Result<UserInfoDetails>; fn get_users(self: &Client) -> Result<Vec<UserInfo>>; + fn get_users_page( + self: &Client, + query: NamedPageQuery, + error_info: &mut ErrorInfo, + ) -> Result<UsersPage>; #[allow(clippy::too_many_arguments)] fn create_user( self: &Client,
diff --git a/foreign/cpp/src/type_conversion.rs b/foreign/cpp/src/type_conversion.rs index d3c77ef..58907b7 100644 --- a/foreign/cpp/src/type_conversion.rs +++ b/foreign/cpp/src/type_conversion.rs
@@ -66,11 +66,11 @@ MetadataPartitionsItem, MetadataSession, MetadataSessionClosed, MetadataStreamChange, MetadataStreamDeleted, MetadataTokenChange, MetadataTokenDeleted, MetadataTopicChange, MetadataTopicDeleted, MetadataTopicItem, MetadataUserChange, MetadataUserIdentity, - MetadataUserPermissionsUpdated, Permissions as RustPermissions, - PersonalAccessTokenInfo as RustPersonalAccessTokenInfo, Stats as RustStats, - StreamPermissions as RustStreamPermissions, TopicPermissions as RustTopicPermissions, - TransportEndpoints as RustTransportEndpoints, UserInfo as RustUserInfo, - UserInfoDetails as RustUserInfoDetails, UserStatus as RustUserStatus, + MetadataUserPermissionsUpdated, NamedPageQuery, Page, PageCursor, PageOrder, PageQuery, + Permissions as RustPermissions, PersonalAccessTokenInfo as RustPersonalAccessTokenInfo, + Stats as RustStats, StreamPermissions as RustStreamPermissions, + TopicPermissions as RustTopicPermissions, TransportEndpoints as RustTransportEndpoints, + UserInfo as RustUserInfo, UserInfoDetails as RustUserInfoDetails, UserStatus as RustUserStatus, }; use crate::{ffi, messages::BatchPositions}; @@ -1382,6 +1382,72 @@ } } +impl TryFrom<ffi::PageQuery> for PageQuery { + type Error = IggyError; + + fn try_from(query: ffi::PageQuery) -> Result<Self, Self::Error> { + let order = match query.order { + ffi::PageOrder::Id => PageOrder::Id, + ffi::PageOrder::Created => PageOrder::Created, + _ => return Err(IggyError::InvalidCommand), + }; + let query = Self { + order, + descending: query.descending, + limit: query.limit, + cursor: page_query_text(query.has_cursor, query.cursor)? + .map(|cursor| PageCursor::from_str(&cursor)) + .transpose()?, + }; + // The binary transports check the session first, so without this a bad + // query on a client that is not signed in fails with the session error. + query.validate()?; + Ok(query) + } +} + +impl TryFrom<ffi::NamedPageQuery> for NamedPageQuery { + type Error = IggyError; + + fn try_from(query: ffi::NamedPageQuery) -> Result<Self, Self::Error> { + let query = Self { + page: PageQuery::try_from(query.page)?, + name: page_query_text(query.has_name, query.name)?, + }; + query.validate()?; + Ok(query) + } +} + +fn page_query_text(present: bool, bytes: Vec<u8>) -> Result<Option<String>, IggyError> { + present + .then(|| String::from_utf8(bytes).map_err(|_| IggyError::InvalidCommand)) + .transpose() +} + +// cxx has no generic shared structs, so each list has its own page struct. +macro_rules! page_into_ffi { + ($($item:ty => $ffi_page:ident),* $(,)?) => {$( + impl From<Page<$item>> for ffi::$ffi_page { + fn from(page: Page<$item>) -> Self { + ffi::$ffi_page { + items: page.items.into_iter().map(From::from).collect(), + has_next: page.next.is_some(), + next: page.next.map(|cursor| cursor.to_string()).unwrap_or_default(), + } + } + } + )*}; +} + +page_into_ffi! { + RustStream => StreamsPage, + RustTopic => TopicsPage, + RustPartition => PartitionsPage, + RustConsumerGroup => ConsumerGroupsPage, + RustUserInfo => UsersPage, +} + impl TryFrom<ffi::MetadataChangesQuery> for MetadataChangesQuery { type Error = IggyError;
diff --git a/foreign/cpp/src/type_conversions.cpp b/foreign/cpp/src/type_conversions.cpp index c178dc8..ae62187 100644 --- a/foreign/cpp/src/type_conversions.cpp +++ b/foreign/cpp/src/type_conversions.cpp
@@ -46,6 +46,16 @@ return result; } +// Bytes, not rust::String, so the bridge refuses text that is not UTF-8 with invalid_command. +rust::Vec<std::uint8_t> TextToFfiBytes(const std::string &text) { + rust::Vec<std::uint8_t> bytes; + bytes.reserve(text.size()); + for (const char character : text) { + bytes.push_back(static_cast<std::uint8_t>(character)); + } + return bytes; +} + } // namespace LoginInfo LoginInfo::FromFfi(ffi::LoginInfo login_info) { @@ -857,4 +867,76 @@ return result; } +ffi::PageQuery PageQuery::ToFfi() const { + ffi::PageQuery query{}; + query.order = static_cast<ffi::PageOrder>(order_); + query.descending = descending_; + query.limit = limit_; + query.has_cursor = cursor_.has_value(); + if (cursor_) { + query.cursor = TextToFfiBytes(*cursor_); + } + return query; +} + +ffi::NamedPageQuery NamedPageQuery::ToFfi() const { + ffi::NamedPageQuery query{}; + query.page = page_.ToFfi(); + query.has_name = name_.has_value(); + if (name_) { + query.name = TextToFfiBytes(*name_); + } + return query; +} + +StreamsPage StreamsPage::FromFfi(ffi::StreamsPage page) { + StreamsPage result; + result.items_.reserve(page.items.size()); + for (auto &stream : page.items) { + result.items_.push_back(Stream::FromFfi(std::move(stream))); + } + result.next_ = TextFromFfi(page.has_next, page.next); + return result; +} + +TopicsPage TopicsPage::FromFfi(ffi::TopicsPage page) { + TopicsPage result; + result.items_.reserve(page.items.size()); + for (auto &topic : page.items) { + result.items_.push_back(Topic::FromFfi(std::move(topic))); + } + result.next_ = TextFromFfi(page.has_next, page.next); + return result; +} + +PartitionsPage PartitionsPage::FromFfi(ffi::PartitionsPage page) { + PartitionsPage result; + result.items_.reserve(page.items.size()); + for (auto &partition : page.items) { + result.items_.push_back(Partition::FromFfi(std::move(partition))); + } + result.next_ = TextFromFfi(page.has_next, page.next); + return result; +} + +ConsumerGroupsPage ConsumerGroupsPage::FromFfi(ffi::ConsumerGroupsPage page) { + ConsumerGroupsPage result; + result.items_.reserve(page.items.size()); + for (auto &group : page.items) { + result.items_.push_back(ConsumerGroup::FromFfi(std::move(group))); + } + result.next_ = TextFromFfi(page.has_next, page.next); + return result; +} + +UsersPage UsersPage::FromFfi(ffi::UsersPage page) { + UsersPage result; + result.items_.reserve(page.items.size()); + for (auto &user : page.items) { + result.items_.push_back(UserInfo::FromFfi(std::move(user))); + } + result.next_ = TextFromFfi(page.has_next, page.next); + return result; +} + } // namespace iggy
diff --git a/foreign/cpp/tests/e2e/list_pages.cpp b/foreign/cpp/tests/e2e/list_pages.cpp new file mode 100644 index 0000000..955c34b --- /dev/null +++ b/foreign/cpp/tests/e2e/list_pages.cpp
@@ -0,0 +1,242 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include <algorithm> +#include <cstddef> +#include <cstdint> +#include <functional> +#include <string> +#include <type_traits> +#include <utility> +#include <vector> + +#include <gtest/gtest.h> + +#include "tests/e2e/test_helpers.hpp" + +namespace { + +constexpr std::uint32_t kInvalidCommand = 3; +constexpr std::uint32_t kPageLimit = 2; +constexpr std::size_t kEntriesPerList = 3; +constexpr std::uint32_t kPartitionsCount = 3; +constexpr int kMaxPages = 100; +constexpr std::size_t kTokenLength = 16; +// An id kind cursor, which the server refuses with order created on the streams. +constexpr char kIdCursor[] = "pg1_AQcAAAAAAAAA"; +constexpr char kPassword[] = "pages-secret"; + +::testing::AssertionResult ThrowsIggyError(const std::function<void()> &operation, + std::uint32_t code, + const std::string &kind) { + try { + operation(); + } catch (const iggy::IggyException &exception) { + if (exception.Code() == code && exception.Kind() == kind) { + return ::testing::AssertionSuccess(); + } + return ::testing::AssertionFailure() + << "expected " << kind << " (" << code << "), got '" << exception.what() << "' with code " + << exception.Code().value_or(0) << " and kind '" << exception.Kind() << "'"; + } + return ::testing::AssertionFailure() << "expected " << kind << " (" << code << "), nothing was thrown"; +} + +// Reads the pages of a query until one has no next cursor, and returns their items in reply order. +template <typename ReadPage> +auto Walk(const ReadPage &read_page, iggy::PageQuery query) { + using Item = typename std::decay_t<decltype(read_page(query).Items())>::value_type; + std::vector<Item> items; + for (int page_index = 0; page_index < kMaxPages; ++page_index) { + const auto page = read_page(query); + EXPECT_LE(page.Items().size(), query.Limit()); + items.insert(items.end(), page.Items().begin(), page.Items().end()); + if (!page.Next()) { + return items; + } + query.SetCursor(*page.Next()); + } + ADD_FAILURE() << "the walk did not end within " << kMaxPages << " pages"; + return items; +} + +template <typename Item> +std::vector<std::uint32_t> Ids(const std::vector<Item> &items) { + std::vector<std::uint32_t> ids; + ids.reserve(items.size()); + for (const auto &item : items) { + ids.push_back(item.Id()); + } + return ids; +} + +template <typename Item, typename Name> +std::vector<std::string> SortedNames(const std::vector<Item> &items, const Name &name) { + std::vector<std::string> names; + names.reserve(items.size()); + for (const auto &item : items) { + names.push_back(name(item)); + } + std::sort(names.begin(), names.end()); + return names; +} + +std::vector<std::uint32_t> Reversed(std::vector<std::uint32_t> ids) { + std::reverse(ids.begin(), ids.end()); + return ids; +} + +// Sorted, and each one holds the prefix. +std::vector<std::string> NamesWithPrefix(const std::string &prefix) { + std::vector<std::string> names; + for (std::size_t index = 0; index < kEntriesPerList; ++index) { + names.push_back(prefix + std::to_string(index)); + } + return names; +} + +iggy::PageQuery PageOfTwo() { + return iggy::PageQuery().SetLimit(kPageLimit); +} + +} // namespace + +class E2E_ListPages : public E2ETestFixture {}; + +TEST_F(E2E_ListPages, GivenThreeStreamsWhenWalkingPagesOfTwoShouldListThemInEachOrder) { + RecordProperty("description", + "Creates three streams under one name prefix and walks them in pages of two with the prefix as the " + "name filter, in id and creation order, each ascending and descending."); + auto client = GetLoggedInHighLevelClient(); + const auto prefix = "pages" + GetRandomName(kTokenLength); + std::vector<std::pair<std::uint64_t, std::uint32_t>> creation_keys; + for (const auto &name : NamesWithPrefix(prefix)) { + const auto stream = client.CreateStream(name); + TrackStream(name); + creation_keys.emplace_back(stream.CreatedAt(), stream.Id()); + } + // A deleted stream frees its id for a new one, so the creation order is (created_at, id), not the id order. + std::sort(creation_keys.begin(), creation_keys.end()); + std::vector<std::uint32_t> by_creation; + for (const auto &key : creation_keys) { + by_creation.push_back(key.second); + } + auto by_id = by_creation; + std::sort(by_id.begin(), by_id.end()); + + const auto read = [&client, &prefix](const iggy::PageQuery &page) { + return client.GetStreamsPage(iggy::NamedPageQuery(page).SetName(prefix)); + }; + const auto walk = [&read](iggy::PageOrder order, bool descending) { + return Ids(Walk(read, PageOfTwo().SetOrder(order).SetDescending(descending))); + }; + EXPECT_EQ(walk(iggy::PageOrder::Id, false), by_id); + EXPECT_EQ(walk(iggy::PageOrder::Id, true), Reversed(by_id)); + EXPECT_EQ(walk(iggy::PageOrder::Created, false), by_creation); + EXPECT_EQ(walk(iggy::PageOrder::Created, true), Reversed(by_creation)); +} + +TEST_F(E2E_ListPages, GivenTopicWithThreePartitionsWhenWalkingPagesOfTwoShouldListEachPartition) { + RecordProperty("description", + "Walks the partitions of a topic with three partitions in pages of two, ascending, descending and " + "in creation order, which is the id order for partitions."); + auto client = GetLoggedInHighLevelClient(); + const auto name = "pages" + GetRandomName(kTokenLength); + client.CreateStream(name); + TrackStream(name); + const auto stream_id = iggy::Identifier::String(name); + const auto topic = + client.CreateTopic(stream_id, "events", iggy::TopicCreateOptions().SetPartitionsCount(kPartitionsCount)); + auto ids = Ids(topic.Partitions()); + std::sort(ids.begin(), ids.end()); + ASSERT_EQ(ids.size(), kPartitionsCount); + + const auto topic_id = iggy::Identifier::Numeric(topic.Id()); + const auto read = [&client, &stream_id, &topic_id](const iggy::PageQuery &query) { + return client.GetPartitionsPage(stream_id, topic_id, query); + }; + EXPECT_EQ(Ids(Walk(read, PageOfTwo())), ids); + EXPECT_EQ(Ids(Walk(read, PageOfTwo().SetDescending(true))), Reversed(ids)); + EXPECT_EQ(Ids(Walk(read, PageOfTwo().SetOrder(iggy::PageOrder::Created))), ids); +} + +TEST_F(E2E_ListPages, GivenNameFilterWhenWalkingTopicsGroupsAndUsersShouldListOnlyTheMatchingNames) { + RecordProperty("description", + "Creates three matching topics, groups and users and one more of each that does not match, and " + "walks each list in pages of two with the name filter."); + auto client = GetLoggedInHighLevelClient(); + const auto token = GetRandomName(kTokenLength); + const auto prefix = "match" + token; + const auto expected = NamesWithPrefix(prefix); + auto created = expected; + created.push_back("other" + token); + + const auto stream_name = "pages" + token; + client.CreateStream(stream_name); + TrackStream(stream_name); + const auto stream = iggy::Identifier::String(stream_name); + const auto topic = iggy::Identifier::String(expected.front()); + for (const auto &name : created) { + client.CreateTopic(stream, name, iggy::TopicCreateOptions().SetPartitionsCount(1)); + } + for (const auto &name : created) { + client.CreateConsumerGroup(stream, topic, name); + CreateUser(client, name, kPassword, iggy::UserStatus::Active); + } + + const auto filter = [&prefix](const iggy::PageQuery &page) { return iggy::NamedPageQuery(page).SetName(prefix); }; + const auto topics = + Walk([&](const iggy::PageQuery &page) { return client.GetTopicsPage(stream, filter(page)); }, PageOfTwo()); + EXPECT_EQ(SortedNames(topics, [](const iggy::Topic &item) { return item.Name(); }), expected); + const auto groups = + Walk([&](const iggy::PageQuery &page) { return client.GetConsumerGroupsPage(stream, topic, filter(page)); }, + PageOfTwo()); + EXPECT_EQ(SortedNames(groups, [](const iggy::ConsumerGroup &item) { return item.Name(); }), expected); + const auto users = + Walk([&](const iggy::PageQuery &page) { return client.GetUsersPage(filter(page)); }, PageOfTwo()); + EXPECT_EQ(SortedNames(users, [](const iggy::UserInfo &item) { return item.Username(); }), expected); +} + +TEST_F(E2E_ListPages, GivenMissingStreamWhenReadingTopicsPageShouldReturnAnEmptyLastPage) { + RecordProperty("description", "A topics page of a stream that does not exist is empty and has no next cursor."); + auto client = GetLoggedInHighLevelClient(); + const auto page = + client.GetTopicsPage(iggy::Identifier::String("missing" + GetRandomName(kTokenLength)), iggy::NamedPageQuery()); + EXPECT_TRUE(page.Items().empty()); + EXPECT_FALSE(page.Next().has_value()); +} + +TEST_F(E2E_ListPages, GivenQueryTheServerRefusesWhenReadingShouldThrowInvalidCommandAndKeepTheSession) { + RecordProperty("description", + "The server refuses an id cursor with order created on the streams with invalid_command, and the " + "session keeps working after it."); + auto client = GetLoggedInHighLevelClient(); + const auto name = "pages" + GetRandomName(kTokenLength); + client.CreateStream(name); + TrackStream(name); + + const auto id_cursor_in_created_order = + iggy::NamedPageQuery(iggy::PageQuery().SetOrder(iggy::PageOrder::Created).SetCursor(kIdCursor)); + const auto named = iggy::NamedPageQuery().SetName(name); + EXPECT_TRUE(ThrowsIggyError([&] { client.GetStreamsPage(id_cursor_in_created_order); }, kInvalidCommand, + "invalid_command")); + + EXPECT_EQ(SortedNames(client.GetStreamsPage(named).Items(), [](const iggy::Stream &item) { return item.Name(); }), + std::vector<std::string>{name}); +}
diff --git a/foreign/cpp/tests/fixtures/list_pages.json b/foreign/cpp/tests/fixtures/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/cpp/tests/fixtures/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/cpp/tests/fixtures/resource_options.json b/foreign/cpp/tests/fixtures/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/cpp/tests/fixtures/resource_options.json +++ b/foreign/cpp/tests/fixtures/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/cpp/tests/unit/list_pages.cpp b/foreign/cpp/tests/unit/list_pages.cpp new file mode 100644 index 0000000..065aec4 --- /dev/null +++ b/foreign/cpp/tests/unit/list_pages.cpp
@@ -0,0 +1,251 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include <cstdint> +#include <fstream> +#include <functional> +#include <stdexcept> +#include <string> +#include <type_traits> +#include <utility> +#include <vector> + +#include <gtest/gtest.h> +#include <nlohmann/json.hpp> + +#include "iggy.hpp" + +// A partition has no name, so a named query must not pass where a PageQuery is expected. +static_assert(!std::is_convertible_v<iggy::NamedPageQuery, iggy::PageQuery>); + +namespace { + +constexpr char kFixturePath[] = "tests/fixtures/list_pages.json"; +constexpr std::uint32_t kInvalidCommand = 3; +constexpr std::uint32_t kDisconnected = 8; +constexpr std::uint8_t kUnknownOrder = 2; +constexpr std::uint32_t kAnyParentId = 1; +constexpr char kNotUtf8Cursor[] = "pg1_AQcAAAAAAAA\xff"; +constexpr char kNotUtf8Name[] = "ord\xff"; + +const nlohmann::json &Fixture() { + static const nlohmann::json fixture = [] { + std::ifstream file(kFixturePath); + if (!file) { + throw std::runtime_error(std::string("Cannot open ") + kFixturePath); + } + return nlohmann::json::parse(file); + }(); + return fixture; +} + +::testing::AssertionResult ThrowsIggyError(const std::function<void()> &operation, + std::uint32_t code, + const std::string &kind) { + try { + operation(); + } catch (const iggy::IggyException &exception) { + if (exception.Code() == code && exception.Kind() == kind) { + return ::testing::AssertionSuccess(); + } + return ::testing::AssertionFailure() << "expected " << kind << " (" << code << "), got '" << exception.what() + << "' with kind '" << exception.Kind() << "'"; + } + return ::testing::AssertionFailure() << "expected " << kind << " (" << code << "), nothing was thrown"; +} + +iggy::PageOrder OrderFrom(const nlohmann::json &name) { + return static_cast<iggy::PageOrder>( + Fixture().at("constants").at("orders").at(name.get<std::string>()).get<std::uint8_t>()); +} + +iggy::PageQuery QueryFrom(const nlohmann::json &input) { + iggy::PageQuery query; + query.SetOrder(OrderFrom(input.at("order"))) + .SetDescending(input.at("descending").get<bool>()) + .SetLimit(input.at("limit").get<std::uint32_t>()); + if (!input.at("cursor").is_null()) { + query.SetCursor(input.at("cursor").get<std::string>()); + } + return query; +} + +iggy::NamedPageQuery NamedQueryFrom(const nlohmann::json &input) { + iggy::NamedPageQuery query(QueryFrom(input)); + if (!input.at("name").is_null()) { + query.SetName(input.at("name").get<std::string>()); + } + return query; +} + +iggy::PageQuery QueryWithCursor(std::string cursor) { + iggy::PageQuery query; + query.SetCursor(std::move(cursor)); + return query; +} + +iggy::Identifier IdentifierFrom(const nlohmann::json &identifier) { + if (identifier.at("kind").get<std::string>() == "numeric") { + return iggy::Identifier::Numeric(identifier.at("value").get<std::uint32_t>()); + } + return iggy::Identifier::String(identifier.at("value").get<std::string>()); +} + +// Runs the page method a request vector names, with the parents and query of its input. +void ReadPage(iggy::IggyBlockingClient &client, const nlohmann::json &vector) { + const auto &input = vector.at("input"); + const auto query = NamedQueryFrom(input); + const auto &command = vector.at("command").get_ref<const std::string &>(); + if (command == "get_streams") { + client.GetStreamsPage(query); + } else if (command == "get_users") { + client.GetUsersPage(query); + } else if (command == "get_topics") { + client.GetTopicsPage(IdentifierFrom(input.at("stream_id")), query); + } else if (command == "get_partitions") { + EXPECT_FALSE(query.Name().has_value()) << "a partitions query has no name"; + client.GetPartitionsPage(IdentifierFrom(input.at("stream_id")), IdentifierFrom(input.at("topic_id")), + query.Page()); + } else if (command == "get_consumer_groups") { + client.GetConsumerGroupsPage(IdentifierFrom(input.at("stream_id")), IdentifierFrom(input.at("topic_id")), + query); + } else { + throw std::invalid_argument("Unknown command " + command); + } +} + +// The client never connects, so a query the bridge lets through fails on the session check +// with disconnected, and a refused one fails with invalid_command. Nothing is sent either way. +void ExpectEveryNamedPageMethodThrows(const iggy::NamedPageQuery &query, std::uint32_t code, const std::string &kind) { + auto client = iggy::IggyBlockingClient::Builder().Build(); + const auto parent = iggy::Identifier::Numeric(kAnyParentId); + const std::vector<std::pair<const char *, std::function<void()>>> calls{ + {"streams", [&] { client.GetStreamsPage(query); }}, + {"topics", [&] { client.GetTopicsPage(parent, query); }}, + {"consumer groups", [&] { client.GetConsumerGroupsPage(parent, parent, query); }}, + {"users", [&] { client.GetUsersPage(query); }}, + }; + for (const auto &[list, call] : calls) { + SCOPED_TRACE(list); + EXPECT_TRUE(ThrowsIggyError(call, code, kind)); + } +} + +// Runs the partitions page method with the query, and the other page methods with the query and no name. +void ExpectEveryPageMethodThrows(const iggy::PageQuery &query, std::uint32_t code, const std::string &kind) { + auto client = iggy::IggyBlockingClient::Builder().Build(); + const auto parent = iggy::Identifier::Numeric(kAnyParentId); + { + SCOPED_TRACE("partitions"); + EXPECT_TRUE(ThrowsIggyError([&] { client.GetPartitionsPage(parent, parent, query); }, code, kind)); + } + ExpectEveryNamedPageMethodThrows(iggy::NamedPageQuery(query), code, kind); +} + +} // namespace + +TEST(ListPagesFixtureTest, GivenFixtureConstantsWhenComparingShouldMatchThePublicValues) { + const auto &constants = Fixture().at("constants"); + EXPECT_EQ(iggy::PageQuery::kDefaultLimit, constants.at("default_limit").get<std::uint32_t>()); + EXPECT_EQ(iggy::PageQuery::kMaxLimit, constants.at("max_limit").get<std::uint32_t>()); + EXPECT_EQ(static_cast<std::uint8_t>(iggy::PageOrder::Id), constants.at("orders").at("id").get<std::uint8_t>()); + EXPECT_EQ(static_cast<std::uint8_t>(iggy::PageOrder::Created), + constants.at("orders").at("created").get<std::uint8_t>()); + + const iggy::PageQuery query; + EXPECT_EQ(query.Order(), iggy::PageOrder::Id); + EXPECT_FALSE(query.Descending()); + EXPECT_EQ(query.Limit(), iggy::PageQuery::kDefaultLimit); + EXPECT_FALSE(query.Cursor().has_value()); + const iggy::NamedPageQuery named; + EXPECT_EQ(named.Page().Limit(), iggy::PageQuery::kDefaultLimit); + EXPECT_FALSE(named.Name().has_value()); + + ExpectEveryPageMethodThrows(iggy::PageQuery().SetLimit(0), + constants.at("errors").at("invalid_command").get<std::uint32_t>(), "invalid_command"); +} + +TEST(ListPagesFixtureTest, GivenRequestVectorsWhenReadingAPageShouldPassTheChecksBeforeSending) { + auto client = iggy::IggyBlockingClient::Builder().Build(); + for (const auto &vector : Fixture().at("requests")) { + SCOPED_TRACE(vector.at("case").get<std::string>()); + EXPECT_TRUE(ThrowsIggyError([&client, &vector] { ReadPage(client, vector); }, kDisconnected, "disconnected")); + } +} + +TEST(ListPagesFixtureTest, GivenCursorVectorsWhenReadingAPageShouldAcceptTheirText) { + for (const auto &vector : Fixture().at("cursors")) { + SCOPED_TRACE(vector.at("case").get<std::string>()); + ExpectEveryPageMethodThrows(QueryWithCursor(vector.at("text").get<std::string>()), kDisconnected, + "disconnected"); + } +} + +TEST(ListPagesFixtureTest, GivenRefusedAndOpaqueCursorTextWhenReadingAPageShouldThrowInvalidCommand) { + for (const auto *cursors : {&Fixture().at("refused").at("cursors"), &Fixture().at("opaque_cursors")}) { + for (const auto &vector : *cursors) { + SCOPED_TRACE(vector.at("case").get<std::string>()); + ExpectEveryPageMethodThrows(QueryWithCursor(vector.at("text").get<std::string>()), kInvalidCommand, + "invalid_command"); + } + } +} + +TEST(ListPagesFixtureTest, GivenRefusedQueriesWhenReadingAPageShouldThrowInvalidCommand) { + for (const auto &vector : Fixture().at("refused").at("queries")) { + SCOPED_TRACE(vector.at("case").get<std::string>()); + const auto &input = vector.at("input"); + if (input.at("name").is_null()) { + ExpectEveryPageMethodThrows(QueryFrom(input), kInvalidCommand, "invalid_command"); + } else { + ExpectEveryNamedPageMethodThrows(NamedQueryFrom(input), kInvalidCommand, "invalid_command"); + } + } +} + +TEST(ListPagesFixtureTest, GivenTextThatIsNotUtf8OrAnUnknownOrderWhenReadingAPageShouldThrowInvalidCommand) { + const auto queries = { + QueryWithCursor(kNotUtf8Cursor), + iggy::PageQuery().SetOrder(static_cast<iggy::PageOrder>(kUnknownOrder)), + }; + for (const auto &query : queries) { + ExpectEveryPageMethodThrows(query, kInvalidCommand, "invalid_command"); + } + ExpectEveryNamedPageMethodThrows(iggy::NamedPageQuery().SetName(kNotUtf8Name), kInvalidCommand, "invalid_command"); +} + +TEST(ListPagesFixtureTest, GivenReadmeSampleWhenCompilingShouldMatchThePublicApi) { + using PrintFunction = std::function<void(const iggy::Stream &)>; + // Never invoked, it only has to compile, so the README sample cannot drift from the API. + const auto print_order_streams = [](iggy::IggyBlockingClient &client, const PrintFunction &Print) { + iggy::NamedPageQuery query(iggy::PageQuery().SetLimit(50)); + query.SetName("orders"); + while (true) { + const auto page = client.GetStreamsPage(query); + for (const auto &stream : page.Items()) { + Print(stream); + } + if (!page.Next()) { + break; + } + query.Page().SetCursor(*page.Next()); + } + }; + static_cast<void>(print_order_streams); +}
diff --git a/foreign/csharp/Iggy_SDK.Tests.Integration/ListPagesTests.cs b/foreign/csharp/Iggy_SDK.Tests.Integration/ListPagesTests.cs new file mode 100644 index 0000000..b4b7035 --- /dev/null +++ b/foreign/csharp/Iggy_SDK.Tests.Integration/ListPagesTests.cs
@@ -0,0 +1,211 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using Apache.Iggy.Contracts; +using Apache.Iggy.Contracts.Auth; +using Apache.Iggy.Enums; +using Apache.Iggy.Exceptions; +using Apache.Iggy.IggyClient; +using Apache.Iggy.Tests.Integrations.Fixtures; +using Shouldly; + +namespace Apache.Iggy.Tests.Integrations; + +/// <summary> +/// Page reads against a shared server. Other tests create entities at the same time, so each test filters by a name +/// of its own and never expects a page count: a page that holds the last match can still have a next. +/// </summary> +public class ListPagesTests +{ + private const int InvalidCommand = 3; + private const uint SmallPage = 2; + private const int StreamsCount = 3; + private const uint PartitionsCount = 3; + + /// <summary>A cursor of an unknown kind. The client reads only its text, so the server is the one to refuse it.</summary> + private const string UnknownKindCursor = "pg1_AwcAAAAAAAAA"; + + [ClassDataSource<IggyServerFixture>(Shared = SharedType.PerAssembly)] + public required IggyServerFixture Fixture { get; init; } + + [Test] + [MethodDataSource<IggyServerFixture>(nameof(IggyServerFixture.ProtocolData))] + public async Task given_three_streams_when_walking_pages_of_two_should_read_them_in_each_order(Protocol protocol) + { + var client = await Fixture.CreateAuthenticatedClient(protocol); + var name = $"pages-{Guid.NewGuid():N}"; + var created = new List<StreamResponse>(); + try + { + for (var index = 0; index < StreamsCount; index++) + { + created.Add((await client.CreateStreamAsync($"{name}-{index}")).ShouldNotBeNull()); + } + + List<uint> byId = [.. created.Select(stream => stream.Id).Order()]; + List<uint> byCreated = + [.. created.OrderBy(stream => stream.CreatedAt).ThenBy(stream => stream.Id).Select(stream => stream.Id)]; + + var query = new NamedPageQuery { Name = name, Page = new PageQuery { Limit = SmallPage } }; + + (await WalkStreams(client, query)).ShouldBe(byId); + (await WalkStreams(client, query with { Page = query.Page with { Descending = true } })) + .ShouldBe(byId.AsEnumerable().Reverse()); + (await WalkStreams(client, query with { Page = query.Page with { Order = PageOrder.Created } })) + .ShouldBe(byCreated); + } + finally + { + foreach (var stream in created) + { + await client.DeleteStreamAsync(Identifier.Numeric(stream.Id)); + } + } + } + + [Test] + [MethodDataSource<IggyServerFixture>(nameof(IggyServerFixture.ProtocolData))] + public async Task given_topic_with_three_partitions_when_reading_partition_pages_should_return_them_by_id( + Protocol protocol) + { + var client = await Fixture.CreateAuthenticatedClient(protocol); + var stream = (await client.CreateStreamAsync($"pages-partitions-{Guid.NewGuid():N}")).ShouldNotBeNull(); + var streamId = Identifier.Numeric(stream.Id); + try + { + var topic = (await client.CreateTopicAsync(streamId, "events", PartitionsCount)).ShouldNotBeNull(); + var topicId = Identifier.Numeric(topic.Id); + + var first = await client.GetPartitionsPageAsync(streamId, topicId, new PageQuery { Limit = SmallPage }); + var last = await client.GetPartitionsPageAsync(streamId, topicId, + new PageQuery { Limit = SmallPage, Cursor = first.Next.ShouldNotBeNull() }); + var descending = await client.GetPartitionsPageAsync(streamId, topicId, + new PageQuery { Descending = true }); + + first.Items.Select(partition => partition.Id).ShouldBe([0u, 1u]); + last.Items.Select(partition => partition.Id).ShouldBe([2u]); + last.Next.ShouldBeNull(); + descending.Items.Select(partition => partition.Id).ShouldBe([2u, 1u, 0u]); + descending.Next.ShouldBeNull(); + } + finally + { + await client.DeleteStreamAsync(streamId); + } + } + + [Test] + [MethodDataSource<IggyServerFixture>(nameof(IggyServerFixture.ProtocolData))] + public async Task given_a_name_filter_when_reading_topics_groups_and_users_should_keep_only_matching_names( + Protocol protocol) + { + var client = await Fixture.CreateAuthenticatedClient(protocol); + var name = $"pages-{Guid.NewGuid():N}"; + var stream = (await client.CreateStreamAsync($"{name}-stream")).ShouldNotBeNull(); + var streamId = Identifier.Numeric(stream.Id); + UserResponse? user = null; + try + { + var topic = (await client.CreateTopicAsync(streamId, $"{name}-topic", 1)).ShouldNotBeNull(); + await client.CreateTopicAsync(streamId, "other-topic", 1); + var topicId = Identifier.Numeric(topic.Id); + await client.CreateConsumerGroupAsync(streamId, topicId, $"{name}-group"); + await client.CreateConsumerGroupAsync(streamId, topicId, "other-group"); + user = (await client.CreateUserAsync(name, "test_password_1", UserStatus.Active)).ShouldNotBeNull(); + + var topics = await client.GetTopicsPageAsync(streamId, new NamedPageQuery { Name = name }); + var groups = await client.GetConsumerGroupsPageAsync(streamId, topicId, new NamedPageQuery { Name = name }); + var users = await client.GetUsersPageAsync(new NamedPageQuery { Name = name }); + + topics.Items.Select(item => item.Name).ShouldBe([$"{name}-topic"]); + groups.Items.Select(item => item.Name).ShouldBe([$"{name}-group"]); + users.Items.Select(item => item.Username).ShouldBe([name]); + } + finally + { + if (user is not null) + { + await client.DeleteUserAsync(Identifier.Numeric(user.Id)); + } + + await client.DeleteStreamAsync(streamId); + } + } + + /// <summary>The HTTP server decodes the query as a form, so each reserved character must arrive escaped.</summary> + [Test] + [MethodDataSource<IggyServerFixture>(nameof(IggyServerFixture.ProtocolData))] + public async Task given_a_name_with_reserved_characters_when_filtering_streams_should_match_it_exactly( + Protocol protocol) + { + var client = await Fixture.CreateAuthenticatedClient(protocol); + var name = $"pages-{Guid.NewGuid():N} a+b&c=d %e#f/?"; + var stream = (await client.CreateStreamAsync(name)).ShouldNotBeNull(); + try + { + var page = await client.GetStreamsPageAsync(new NamedPageQuery { Name = name }); + + page.Items.Select(item => item.Id).ShouldBe([stream.Id]); + } + finally + { + await client.DeleteStreamAsync(Identifier.Numeric(stream.Id)); + } + } + + [Test] + [MethodDataSource<IggyServerFixture>(nameof(IggyServerFixture.ProtocolData))] + public async Task given_a_cursor_the_server_cannot_use_when_reading_should_refuse_it_and_keep_working( + Protocol protocol) + { + var client = await Fixture.CreateAuthenticatedClient(protocol); + var stream = (await client.CreateStreamAsync($"pages-refused-{Guid.NewGuid():N}")).ShouldNotBeNull(); + try + { + var refusal = await Should.ThrowAsync<IggyInvalidStatusCodeException>(client.GetStreamsPageAsync( + new NamedPageQuery { Page = new PageQuery { Cursor = PageCursor.Parse(UnknownKindCursor) } })); + + refusal.StatusCode.ShouldBe(InvalidCommand); + refusal.FromServer.ShouldBeTrue(); + (await client.GetStreamsPageAsync(new NamedPageQuery { Name = stream.Name })).Items + .Select(item => item.Id).ShouldBe([stream.Id]); + } + finally + { + await client.DeleteStreamAsync(Identifier.Numeric(stream.Id)); + } + } + + /// <summary>Reads every page of a query and checks that the read took more than one page.</summary> + private static async Task<List<uint>> WalkStreams(IIggyClient client, NamedPageQuery query) + { + var ids = new List<uint>(); + var pages = 0; + Page<StreamResponse> page; + do + { + page = await client.GetStreamsPageAsync(query); + page.Items.Count.ShouldBeLessThanOrEqualTo((int)query.Page.Limit); + ids.AddRange(page.Items.Select(stream => stream.Id)); + query = query with { Page = query.Page with { Cursor = page.Next } }; + pages++; + } while (page.Next is not null); + + pages.ShouldBeGreaterThan(1); + return ids; + } +}
diff --git a/foreign/csharp/Iggy_SDK.Tests.Integration/MetadataChangesTests.cs b/foreign/csharp/Iggy_SDK.Tests.Integration/MetadataChangesTests.cs index 8582f87..4ebae6b 100644 --- a/foreign/csharp/Iggy_SDK.Tests.Integration/MetadataChangesTests.cs +++ b/foreign/csharp/Iggy_SDK.Tests.Integration/MetadataChangesTests.cs
@@ -113,6 +113,7 @@ } [Test] + [NotInParallel] [MethodDataSource<IggyServerFixture>(nameof(IggyServerFixture.ProtocolData))] public async Task given_limit_of_one_when_following_should_page_one_record_at_a_time(Protocol protocol) {
diff --git a/foreign/csharp/Iggy_SDK/Contracts/NamedPageQuery.cs b/foreign/csharp/Iggy_SDK/Contracts/NamedPageQuery.cs new file mode 100644 index 0000000..b699081 --- /dev/null +++ b/foreign/csharp/Iggy_SDK/Contracts/NamedPageQuery.cs
@@ -0,0 +1,82 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using System.Text; +using Apache.Iggy.Exceptions; +using Apache.Iggy.IggyClient; +using Apache.Iggy.Utils; + +namespace Apache.Iggy.Contracts; + +/// <summary> +/// One page read of a list with a name filter, such as <see cref="IIggyStream.GetStreamsPageAsync" />. To read the +/// next page, send the same query with the <see cref="Page{T}.Next" /> of the page: +/// <c>query with { Page = query.Page with { Cursor = page.Next } }</c>. +/// </summary> +public sealed record NamedPageQuery +{ + /// <summary>Most bytes of a name filter in UTF-8.</summary> + public const int MAX_NAME_SIZE = WireName.MAX_LENGTH; + + private const string NAME_KEY = "name"; + + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + /// <summary>The order, the page size and the cursor of the read.</summary> + public PageQuery Page { get; init; } = new(); + + /// <summary>Keeps only the entries whose name holds this text, case-sensitive. Null keeps every entry.</summary> + public string? Name { get; init; } + + /// <summary> + /// Applies the rules of <see cref="PageQuery.Validate" /> and a name of 1 to 255 bytes of UTF-8, so a refused + /// query is never sent. + /// </summary> + /// <exception cref="IggyInvalidStatusCodeException">Invalid command (code 3) naming the broken rule.</exception> + internal void Validate() + { + ArgumentNullException.ThrowIfNull(Page); + Page.Validate(); + if (Name is null) + { + return; + } + + int size; + try + { + size = StrictUtf8.GetByteCount(Name); + } + catch (EncoderFallbackException) + { + // A lone surrogate has no UTF-8 form, so the server would read another name. + throw PageQuery.Refused("The name must be valid Unicode text."); + } + + if (size is 0 or > MAX_NAME_SIZE) + { + throw PageQuery.Refused($"The name must be 1 to {MAX_NAME_SIZE} bytes of UTF-8, got {size}."); + } + } + + /// <summary>The query string of <see cref="PageQuery.ToHttpQuery" />, with the name when there is one.</summary> + internal string ToHttpQuery() + { + var query = Page.ToHttpQuery(); + return Name is null ? query : $"{query}&{PageQuery.Pair(NAME_KEY, Name)}"; + } +}
diff --git a/foreign/csharp/Iggy_SDK/Contracts/Page.cs b/foreign/csharp/Iggy_SDK/Contracts/Page.cs new file mode 100644 index 0000000..14cae48 --- /dev/null +++ b/foreign/csharp/Iggy_SDK/Contracts/Page.cs
@@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace Apache.Iggy.Contracts; + +/// <summary> +/// One page of a list. +/// </summary> +/// <remarks> +/// A page can be short or empty and still have a <see cref="Next" />. A read of a whole list ends at the first +/// page without one. +/// </remarks> +/// <typeparam name="T">The item type of the list.</typeparam> +public sealed class Page<T> +{ + /// <summary>The items of the page, in the order of the query.</summary> + public required IReadOnlyList<T> Items { get; init; } + + /// <summary>The cursor of the next page, null on the last page.</summary> + public PageCursor? Next { get; init; } +}
diff --git a/foreign/csharp/Iggy_SDK/Contracts/PageCursor.cs b/foreign/csharp/Iggy_SDK/Contracts/PageCursor.cs new file mode 100644 index 0000000..dced6a6 --- /dev/null +++ b/foreign/csharp/Iggy_SDK/Contracts/PageCursor.cs
@@ -0,0 +1,112 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using System.Diagnostics.CodeAnalysis; +using System.Text.Json.Serialization; +using Apache.Iggy.JsonConverters; +using Apache.Iggy.Utils; + +namespace Apache.Iggy.Contracts; + +/// <summary> +/// The position after the last entry that a list page read passed. Send the <see cref="Page{T}.Next" /> of a +/// page back as the <see cref="PageQuery.Cursor" /> of the same query to read the next page. +/// </summary> +/// <remarks> +/// The text form is <c>pg1_</c> followed by unpadded Base64url of 1 to 255 bytes. Only the server reads the +/// bytes, so the client keeps the bytes of every cursor as they came and the server refuses one it cannot use. +/// </remarks> +[JsonConverter(typeof(PageCursorConverter))] +public sealed class PageCursor : IEquatable<PageCursor> +{ + /// <summary>Text prefix of a page cursor.</summary> + public const string PREFIX = "pg1_"; + + /// <summary>The length of a cursor on the wire is one byte.</summary> + internal const int MAX_SIZE = byte.MaxValue; + + private const int MAX_TEXT_LENGTH = 4 + (MAX_SIZE + 2) / 3 * 4; + + private readonly byte[] _bytes; + + private PageCursor(byte[] bytes) + { + _bytes = bytes; + } + + internal ReadOnlySpan<byte> Bytes => _bytes; + + /// <summary> + /// Parses the <c>pg1_</c> text form. + /// </summary> + /// <exception cref="FormatException">The text is not a canonical page cursor.</exception> + public static PageCursor Parse(string text) + { + return TryParse(text, out var cursor) + ? cursor + : throw new FormatException("The text is not a canonical page cursor."); + } + + /// <summary> + /// Parses the <c>pg1_</c> text form, refusing a wrong prefix, padding, the standard Base64 alphabet, + /// non-canonical encodings, and a cursor of no bytes or of more than 255 bytes. + /// </summary> + public static bool TryParse([NotNullWhen(true)] string? text, [NotNullWhen(true)] out PageCursor? cursor) + { + cursor = null; + if (text is not { Length: <= MAX_TEXT_LENGTH } || !text.StartsWith(PREFIX, StringComparison.Ordinal) + || !Base64Url.TryDecode(text.AsSpan(PREFIX.Length), out var bytes) || bytes.Length is 0 or > MAX_SIZE) + { + return false; + } + + cursor = new PageCursor(bytes); + return true; + } + + /// <summary>The cursor of the next field of a reply, which holds 1 to 255 bytes.</summary> + internal static PageCursor FromBytes(ReadOnlySpan<byte> bytes) + { + return new PageCursor(bytes.ToArray()); + } + + /// <summary>The <c>pg1_</c> text form.</summary> + public override string ToString() + { + return PREFIX + Base64Url.Encode(_bytes); + } + + /// <inheritdoc /> + public bool Equals(PageCursor? other) + { + return other is not null && _bytes.AsSpan().SequenceEqual(other._bytes); + } + + /// <inheritdoc /> + public override bool Equals(object? obj) + { + return obj is PageCursor other && Equals(other); + } + + /// <inheritdoc /> + public override int GetHashCode() + { + var hash = new HashCode(); + hash.AddBytes(_bytes); + return hash.ToHashCode(); + } +}
diff --git a/foreign/csharp/Iggy_SDK/Contracts/PageQuery.cs b/foreign/csharp/Iggy_SDK/Contracts/PageQuery.cs new file mode 100644 index 0000000..a500d0c --- /dev/null +++ b/foreign/csharp/Iggy_SDK/Contracts/PageQuery.cs
@@ -0,0 +1,103 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using System.Globalization; +using Apache.Iggy.Enums; +using Apache.Iggy.Exceptions; +using Apache.Iggy.IggyClient; +using Apache.Iggy.Vsr; + +namespace Apache.Iggy.Contracts; + +/// <summary> +/// One page read of a list, such as <see cref="IIggyPartition.GetPartitionsPageAsync" />. To read the next page, +/// send the same query with the <see cref="Page{T}.Next" /> of the page: <c>query with { Cursor = page.Next }</c>. +/// A list with a name filter takes a <see cref="NamedPageQuery" />. +/// </summary> +public sealed record PageQuery +{ + /// <summary>Items per page when the caller does not say.</summary> + public const uint DEFAULT_LIMIT = 100; + + /// <summary>Most items one page returns.</summary> + public const uint MAX_LIMIT = 1000; + + private const string ORDER_KEY = "order"; + private const string DESCENDING_KEY = "descending"; + private const string LIMIT_KEY = "limit"; + private const string CURSOR_KEY = "cursor"; + + /// <summary>The order of the read.</summary> + public PageOrder Order { get; init; } = PageOrder.Id; + + /// <summary>Whether the read starts at the end of the order.</summary> + public bool Descending { get; init; } + + /// <summary>Items per page, 1 to 1000.</summary> + public uint Limit { get; init; } = DEFAULT_LIMIT; + + /// <summary>The next cursor of the previous page, null for the first page.</summary> + public PageCursor? Cursor { get; init; } + + /// <summary> + /// Applies the page rules of the server, so a refused query is never sent: a known order and a limit of 1 to + /// 1000. A <see cref="PageCursor" /> holds 1 to 255 bytes by construction. + /// </summary> + /// <exception cref="IggyInvalidStatusCodeException">Invalid command (code 3) naming the broken rule.</exception> + internal void Validate() + { + if (!Enum.IsDefined(Order)) + { + throw Refused($"The order {(byte)Order} is unknown."); + } + + if (Limit is 0 or > MAX_LIMIT) + { + throw Refused($"The limit must be 1 to {MAX_LIMIT}, got {Limit}."); + } + } + + /// <summary> + /// The query string of an HTTP list route. It always holds the limit, so the server answers one page and not + /// the whole list. The server decodes it as a form, so every value is escaped. + /// </summary> + internal string ToHttpQuery() + { + var pairs = new List<string> + { + Pair(ORDER_KEY, SnakeCaseNames<PageOrder>.Name(Order)), + Pair(DESCENDING_KEY, Descending ? "true" : "false"), + Pair(LIMIT_KEY, Limit.ToString(CultureInfo.InvariantCulture)) + }; + if (Cursor is not null) + { + pairs.Add(Pair(CURSOR_KEY, Cursor.ToString())); + } + + return string.Join('&', pairs); + } + + internal static string Pair(string key, string value) + { + return $"{key}={Uri.EscapeDataString(value)}"; + } + + internal static IggyInvalidStatusCodeException Refused(string message) + { + return VsrError.Exception(VsrError.INVALID_COMMAND, $"List page query refused: {message}"); + } +}
diff --git a/foreign/csharp/Iggy_SDK/Contracts/Tcp/TcpContracts.cs b/foreign/csharp/Iggy_SDK/Contracts/Tcp/TcpContracts.cs index 2ade361..0ebb165 100644 --- a/foreign/csharp/Iggy_SDK/Contracts/Tcp/TcpContracts.cs +++ b/foreign/csharp/Iggy_SDK/Contracts/Tcp/TcpContracts.cs
@@ -42,6 +42,9 @@ /// <summary>Offset mutations always request quorum acknowledgement.</summary> private const byte AckQuorum = 1; + /// <summary>The order, descending, limit, cursor length and name length fields of a page block.</summary> + private const int PAGE_BLOCK_FIXED_SIZE = 1 + 1 + 4 + 1 + 1; + /// <summary>The bytes a deferred poll (code 106) appends to the body of code 100.</summary> internal const int DEFERRED_POLL_TAIL_SIZE = sizeof(ulong) + sizeof(uint) + sizeof(uint) + sizeof(ulong); @@ -767,11 +770,39 @@ return bytes.ToArray(); } - internal static byte[] GetGroups(Identifier streamId, Identifier topicId) + /// <summary> + /// Encodes a validated list request: the identifiers of its parents, then the page block + /// <c>[order:u8][descending:u8][limit:u32][cursor_len:u8][cursor][name_len:u8][name]</c>. A length of 0 means + /// no cursor or no name. + /// </summary> + internal static byte[] GetPage(NamedPageQuery query, params Identifier[] parents) { - Span<byte> bytes = stackalloc byte[2 + streamId.Length + 2 + topicId.Length]; - bytes.WriteBytesFromStreamAndTopicIdentifiers(streamId, topicId); - return bytes.ToArray(); + var page = query.Page; + var cursor = page.Cursor is { } next ? next.Bytes : ReadOnlySpan<byte>.Empty; + var nameLength = query.Name is null ? 0 : Encoding.UTF8.GetByteCount(query.Name); + var bytes = new byte[parents.Sum(parent => 2 + parent.Length) + PAGE_BLOCK_FIXED_SIZE + cursor.Length + + nameLength]; + var position = 0; + foreach (var parent in parents) + { + bytes.AsSpan().WriteBytesFromIdentifier(parent, position); + position += 2 + parent.Length; + } + + bytes[position++] = (byte)page.Order; + bytes[position++] = page.Descending ? (byte)1 : (byte)0; + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(position, 4), page.Limit); + position += 4; + bytes[position++] = (byte)cursor.Length; + cursor.CopyTo(bytes.AsSpan(position)); + position += cursor.Length; + bytes[position++] = (byte)nameLength; + if (query.Name is not null) + { + Encoding.UTF8.GetBytes(query.Name, bytes.AsSpan(position)); + } + + return bytes; } internal static byte[] GetGroup(Identifier streamId, Identifier topicId, Identifier groupId)
diff --git a/foreign/csharp/Iggy_SDK/Enums/PageOrder.cs b/foreign/csharp/Iggy_SDK/Enums/PageOrder.cs new file mode 100644 index 0000000..da5c579 --- /dev/null +++ b/foreign/csharp/Iggy_SDK/Enums/PageOrder.cs
@@ -0,0 +1,33 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace Apache.Iggy.Enums; + +/// <summary> +/// The order of a list page read. The values are the wire codes. +/// </summary> +public enum PageOrder : byte +{ + /// <summary>The numeric id.</summary> + Id = 0, + + /// <summary> + /// The creation time, then the id. Partitions and consumer groups get their ids in creation order, so the + /// server reads them by id. + /// </summary> + Created = 1 +}
diff --git a/foreign/csharp/Iggy_SDK/IggyClient/IIggyConsumerGroup.cs b/foreign/csharp/Iggy_SDK/IggyClient/IIggyConsumerGroup.cs index 924f6e4..bdb04d0 100644 --- a/foreign/csharp/Iggy_SDK/IggyClient/IIggyConsumerGroup.cs +++ b/foreign/csharp/Iggy_SDK/IggyClient/IIggyConsumerGroup.cs
@@ -28,6 +28,12 @@ /// <summary> /// Retrieves information about all consumer groups for a specified topic. /// </summary> + /// <remarks> + /// Over TCP the client reads the list in pages of 1000 in id order, so the result is not one consistent read: + /// a group that someone creates or deletes during the read can be in it or not. Every page keeps the sign-in + /// and the call deadline that the read started with. Over HTTP the server returns the whole list in one reply, + /// but it builds that reply from pages of 1000, so it is not one consistent read either. + /// </remarks> /// <param name="streamId">The identifier of the stream containing the topic (numeric ID or name).</param> /// <param name="topicId">The identifier of the topic (numeric ID or name).</param> /// <param name="token">The cancellation token to cancel the operation.</param> @@ -35,10 +41,33 @@ /// A task that represents the asynchronous operation and returns a read-only collection of consumer group /// information. /// </returns> + /// <exception cref="Exceptions.MalformedResponseException"> + /// Over TCP, when the server answers a page with the same cursor that the client sent. + /// </exception> Task<IReadOnlyList<ConsumerGroupResponse>> GetConsumerGroupsAsync(Identifier streamId, Identifier topicId, CancellationToken token = default); /// <summary> + /// Reads one page of the consumer groups of a topic. + /// </summary> + /// <remarks> + /// The query is checked before anything is sent. To read the next page, send the same query with the + /// <see cref="Page{T}.Next" /> of this page as its cursor. Consumer groups get their ids in creation order, so + /// both orders read them by id. + /// </remarks> + /// <param name="streamId">The identifier of the stream containing the topic (numeric ID or name).</param> + /// <param name="topicId">The identifier of the topic (numeric ID or name).</param> + /// <param name="query">The order, the page size, the cursor and the name filter of the read.</param> + /// <param name="token">The cancellation token to cancel the operation.</param> + /// <returns>A task that represents the asynchronous operation and returns the page.</returns> + /// <exception cref="Exceptions.IggyInvalidStatusCodeException"> + /// Invalid command (code 3) for a query the page rules refuse, or for a cursor the server cannot use. The + /// stream or topic not found error when one of them does not exist. + /// </exception> + Task<Page<ConsumerGroupResponse>> GetConsumerGroupsPageAsync(Identifier streamId, Identifier topicId, + NamedPageQuery query, CancellationToken token = default); + + /// <summary> /// Retrieves detailed information about a specific consumer group. /// </summary> /// <param name="streamId">The identifier of the stream containing the topic (numeric ID or name).</param>
diff --git a/foreign/csharp/Iggy_SDK/IggyClient/IIggyPartition.cs b/foreign/csharp/Iggy_SDK/IggyClient/IIggyPartition.cs index 1d68733..00c7fe0 100644 --- a/foreign/csharp/Iggy_SDK/IggyClient/IIggyPartition.cs +++ b/foreign/csharp/Iggy_SDK/IggyClient/IIggyPartition.cs
@@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +using Apache.Iggy.Contracts; + namespace Apache.Iggy.IggyClient; /// <summary> @@ -44,4 +46,24 @@ /// <returns>A task representing the asynchronous operation.</returns> Task CreatePartitionsAsync(Identifier streamId, Identifier topicId, uint partitionsCount, CancellationToken token = default); + + /// <summary> + /// Reads one page of the partitions of a topic. + /// </summary> + /// <remarks> + /// The query is checked before anything is sent. To read the next page, send the same query with the + /// <see cref="Page{T}.Next" /> of this page as its cursor. Partitions get their ids in creation order, so both + /// orders read them by id. + /// </remarks> + /// <param name="streamId">The identifier of the stream containing the topic (numeric ID or name).</param> + /// <param name="topicId">The identifier of the topic (numeric ID or name).</param> + /// <param name="query">The order, the page size and the cursor of the read.</param> + /// <param name="token">The cancellation token to cancel the operation.</param> + /// <returns>A task that represents the asynchronous operation and returns the page.</returns> + /// <exception cref="Exceptions.IggyInvalidStatusCodeException"> + /// Invalid command (code 3) for a query the page rules refuse, or for a cursor the server cannot use. The + /// stream or topic not found error when one of them does not exist. + /// </exception> + Task<Page<PartitionResponse>> GetPartitionsPageAsync(Identifier streamId, Identifier topicId, PageQuery query, + CancellationToken token = default); }
diff --git a/foreign/csharp/Iggy_SDK/IggyClient/IIggyStream.cs b/foreign/csharp/Iggy_SDK/IggyClient/IIggyStream.cs index 5bbb01f..368712d 100644 --- a/foreign/csharp/Iggy_SDK/IggyClient/IIggyStream.cs +++ b/foreign/csharp/Iggy_SDK/IggyClient/IIggyStream.cs
@@ -67,11 +67,35 @@ /// <summary> /// Retrieves information about all streams. /// </summary> + /// <remarks> + /// Over TCP the client reads the list in pages of 1000 in id order, so the result is not one consistent read: + /// a stream that someone creates or deletes during the read can be in it or not. Every page keeps the sign-in + /// and the call deadline that the read started with. Over HTTP the server returns the whole list in one reply, + /// but it builds that reply from pages of 1000, so it is not one consistent read either. + /// </remarks> /// <param name="token">The cancellation token to cancel the operation.</param> /// <returns>A task that represents the asynchronous operation and returns a read-only collection of stream information.</returns> + /// <exception cref="Exceptions.MalformedResponseException"> + /// Over TCP, when the server answers a page with the same cursor that the client sent. + /// </exception> Task<IReadOnlyList<StreamResponse>> GetStreamsAsync(CancellationToken token = default); /// <summary> + /// Reads one page of streams. + /// </summary> + /// <remarks> + /// The query is checked before anything is sent. To read the next page, send the same query with the + /// <see cref="Page{T}.Next" /> of this page as its cursor. + /// </remarks> + /// <param name="query">The order, the page size, the cursor and the name filter of the read.</param> + /// <param name="token">The cancellation token to cancel the operation.</param> + /// <returns>A task that represents the asynchronous operation and returns the page.</returns> + /// <exception cref="Exceptions.IggyInvalidStatusCodeException"> + /// Invalid command (code 3) for a query the page rules refuse, or for a cursor the server cannot use. + /// </exception> + Task<Page<StreamResponse>> GetStreamsPageAsync(NamedPageQuery query, CancellationToken token = default); + + /// <summary> /// Deletes an existing stream and all its associated topics and messages. /// </summary> /// <param name="streamId">The identifier of the stream to delete (numeric ID or name).</param>
diff --git a/foreign/csharp/Iggy_SDK/IggyClient/IIggyTopic.cs b/foreign/csharp/Iggy_SDK/IggyClient/IIggyTopic.cs index 84ffa24..b367cf1 100644 --- a/foreign/csharp/Iggy_SDK/IggyClient/IIggyTopic.cs +++ b/foreign/csharp/Iggy_SDK/IggyClient/IIggyTopic.cs
@@ -28,12 +28,41 @@ /// <summary> /// Retrieves information about all topics in a specified stream. /// </summary> + /// <remarks> + /// Over TCP the client reads the list in pages of 1000 in id order, so the result is not one consistent read: + /// a topic that someone creates or deletes during the read can be in it or not. Every page keeps the sign-in + /// and the call deadline that the read started with. Over HTTP the server returns the whole list in one reply, + /// but it builds that reply from pages of 1000, so it is not one consistent read either. + /// </remarks> /// <param name="streamId">The identifier of the stream containing the topics (numeric ID or name).</param> /// <param name="token">The cancellation token to cancel the operation.</param> /// <returns>A task that represents the asynchronous operation and returns a read-only collection of topic information.</returns> + /// <exception cref="Exceptions.MalformedResponseException"> + /// Over TCP, when the server answers a page with the same cursor that the client sent. + /// </exception> Task<IReadOnlyList<TopicResponse>> GetTopicsAsync(Identifier streamId, CancellationToken token = default); /// <summary> + /// Reads one page of the topics of a stream. For a stream that does not exist, a read without a cursor returns + /// an empty last page. + /// </summary> + /// <remarks> + /// The query is checked before anything is sent. To read the next page, send the same query with the + /// <see cref="Page{T}.Next" /> of this page as its cursor. + /// </remarks> + /// <param name="streamId">The identifier of the stream containing the topics (numeric ID or name).</param> + /// <param name="query">The order, the page size, the cursor and the name filter of the read.</param> + /// <param name="token">The cancellation token to cancel the operation.</param> + /// <returns>A task that represents the asynchronous operation and returns the page.</returns> + /// <exception cref="Exceptions.IggyInvalidStatusCodeException"> + /// Invalid command (code 3) for a query the page rules refuse, or for a cursor the server cannot use. Stream + /// not found (code 1009) for a read with a cursor when the stream does not exist: the stream was deleted + /// during the walk. + /// </exception> + Task<Page<TopicResponse>> GetTopicsPageAsync(Identifier streamId, NamedPageQuery query, + CancellationToken token = default); + + /// <summary> /// Retrieves detailed information about a specific topic by its identifier. /// </summary> /// <param name="streamId">The identifier of the stream containing the topic (numeric ID or name).</param>
diff --git a/foreign/csharp/Iggy_SDK/IggyClient/IIggyUsers.cs b/foreign/csharp/Iggy_SDK/IggyClient/IIggyUsers.cs index 11e997d..764759b 100644 --- a/foreign/csharp/Iggy_SDK/IggyClient/IIggyUsers.cs +++ b/foreign/csharp/Iggy_SDK/IggyClient/IIggyUsers.cs
@@ -38,11 +38,35 @@ /// <summary> /// Retrieves information about all users in the system. /// </summary> + /// <remarks> + /// Over TCP the client reads the list in pages of 1000 in id order, so the result is not one consistent read: + /// a user that someone creates or deletes during the read can be in it or not. Every page keeps the sign-in and + /// the call deadline that the read started with. Over HTTP the server returns the whole list in one reply, but + /// it builds that reply from pages of 1000, so it is not one consistent read either. + /// </remarks> /// <param name="token">The cancellation token to cancel the operation.</param> /// <returns>A task that represents the asynchronous operation and returns a read-only collection of user information.</returns> + /// <exception cref="Exceptions.MalformedResponseException"> + /// Over TCP, when the server answers a page with the same cursor that the client sent. + /// </exception> Task<IReadOnlyList<UserResponse>> GetUsersAsync(CancellationToken token = default); /// <summary> + /// Reads one page of users. + /// </summary> + /// <remarks> + /// The query is checked before anything is sent. To read the next page, send the same query with the + /// <see cref="Page{T}.Next" /> of this page as its cursor. + /// </remarks> + /// <param name="query">The order, the page size, the cursor and the username filter of the read.</param> + /// <param name="token">The cancellation token to cancel the operation.</param> + /// <returns>A task that represents the asynchronous operation and returns the page.</returns> + /// <exception cref="Exceptions.IggyInvalidStatusCodeException"> + /// Invalid command (code 3) for a query the page rules refuse, or for a cursor the server cannot use. + /// </exception> + Task<Page<UserResponse>> GetUsersPageAsync(NamedPageQuery query, CancellationToken token = default); + + /// <summary> /// Creates a new user with the specified credentials and permissions. /// </summary> /// <param name="userName">The unique username for the new user.</param>
diff --git a/foreign/csharp/Iggy_SDK/IggyClient/Implementations/HttpMessageStream.cs b/foreign/csharp/Iggy_SDK/IggyClient/Implementations/HttpMessageStream.cs index b61a9dc..1b06e1a 100644 --- a/foreign/csharp/Iggy_SDK/IggyClient/Implementations/HttpMessageStream.cs +++ b/foreign/csharp/Iggy_SDK/IggyClient/Implementations/HttpMessageStream.cs
@@ -169,6 +169,12 @@ } /// <inheritdoc /> + public Task<Page<StreamResponse>> GetStreamsPageAsync(NamedPageQuery query, CancellationToken token = default) + { + return GetPageAsync<StreamResponse>("/streams", query, token); + } + + /// <inheritdoc /> public async Task<TopicResponse?> CreateTopicAsync(Identifier streamId, string name, uint partitionsCount, TopicOptions? options = null, CancellationToken token = default) { @@ -224,6 +230,13 @@ } /// <inheritdoc /> + public Task<Page<TopicResponse>> GetTopicsPageAsync(Identifier streamId, NamedPageQuery query, + CancellationToken token = default) + { + return GetPageAsync<TopicResponse>($"/streams/{streamId}/topics", query, token); + } + + /// <inheritdoc /> public async Task<TopicResponse?> GetTopicByIdAsync(Identifier streamId, Identifier topicId, CancellationToken token = default) { @@ -777,6 +790,14 @@ } /// <inheritdoc /> + public Task<Page<ConsumerGroupResponse>> GetConsumerGroupsPageAsync(Identifier streamId, Identifier topicId, + NamedPageQuery query, CancellationToken token = default) + { + return GetPageAsync<ConsumerGroupResponse>($"/streams/{streamId}/topics/{topicId}/consumer-groups", query, + token); + } + + /// <inheritdoc /> public async Task<ConsumerGroupResponse?> GetConsumerGroupByIdAsync(Identifier streamId, Identifier topicId, Identifier groupId, CancellationToken token = default) { @@ -1120,6 +1141,14 @@ } /// <inheritdoc /> + public Task<Page<PartitionResponse>> GetPartitionsPageAsync(Identifier streamId, Identifier topicId, + PageQuery query, CancellationToken token = default) + { + return GetPageAsync<PartitionResponse>($"/streams/{streamId}/topics/{topicId}/partitions", + new NamedPageQuery { Page = query }, token); + } + + /// <inheritdoc /> public async Task<UserResponse?> GetUserAsync(Identifier userId, CancellationToken token = default) { //TODO - this doesn't work prob needs a custom json serializer @@ -1148,6 +1177,12 @@ } /// <inheritdoc /> + public Task<Page<UserResponse>> GetUsersPageAsync(NamedPageQuery query, CancellationToken token = default) + { + return GetPageAsync<UserResponse>("/users", query, token); + } + + /// <inheritdoc /> public async Task<UserResponse?> CreateUserAsync(string userName, string password, UserStatus status, Permissions? permissions = null, UserOptions? options = null, CancellationToken token = default) { @@ -1514,6 +1549,25 @@ return plaintext; } + /// <summary> + /// Reads one page of a list route, <c>{"items": [...], "next": "pg1_..."}</c>. The query always holds the limit, + /// so the server answers one page and not the bare array of the whole list. + /// </summary> + private async Task<Page<T>> GetPageAsync<T>(string path, NamedPageQuery query, CancellationToken token) + { + ArgumentNullException.ThrowIfNull(query); + query.Validate(); + var response = await _httpClient.GetAsync($"{path}?{query.ToHttpQuery()}", token); + if (!response.IsSuccessStatusCode) + { + // A 404 is the not-found error of a missing stream or topic, which TCP raises too. It is not an empty page. + await HandleResponseAsync(response, shouldThrowOnGetNotFound: true); + } + + return await response.Content.ReadFromJsonAsync<Page<T>>(_jsonSerializerOptions, token) + ?? throw new InvalidResponseException("The list page answer is empty."); + } + private async Task HandleResponseAsync(HttpResponseMessage response, bool shouldThrowOnGetNotFound = false) { if (response.IsSuccessStatusCode)
diff --git a/foreign/csharp/Iggy_SDK/IggyClient/Implementations/TcpMessageStream.cs b/foreign/csharp/Iggy_SDK/IggyClient/Implementations/TcpMessageStream.cs index 2126cba..9f9261b 100644 --- a/foreign/csharp/Iggy_SDK/IggyClient/Implementations/TcpMessageStream.cs +++ b/foreign/csharp/Iggy_SDK/IggyClient/Implementations/TcpMessageStream.cs
@@ -65,6 +65,10 @@ CommandCodes.FETCH_MESSAGES_CODE ]; + /// <summary>The first page of a whole list read: ascending id order, in the largest pages.</summary> + private static readonly NamedPageQuery WholeListQuery + = new() { Page = new PageQuery { Limit = PageQuery.MAX_LIMIT } }; + private readonly IggyClientConfigurator _configuration; // The configurator stays settable after construction, so the endpoint the client was built for is pinned here: @@ -205,18 +209,15 @@ } /// <inheritdoc /> - public async Task<IReadOnlyList<StreamResponse>> GetStreamsAsync(CancellationToken token = default) + public Task<IReadOnlyList<StreamResponse>> GetStreamsAsync(CancellationToken token = default) { - var message = Array.Empty<byte>(); - using IMemoryOwner<byte> responseBuffer - = await SendWithResponseAsync(CommandCodes.GET_STREAMS_CODE, message, token: token); + return ReadWholeListAsync(CommandCodes.GET_STREAMS_CODE, [], BinaryMapper.MapToStream, token); + } - if (responseBuffer.Memory.Length == 0) - { - return []; - } - - return BinaryMapper.MapStreams(responseBuffer.Memory.Span); + /// <inheritdoc /> + public Task<Page<StreamResponse>> GetStreamsPageAsync(NamedPageQuery query, CancellationToken token = default) + { + return ReadPageAsync(CommandCodes.GET_STREAMS_CODE, [], query, BinaryMapper.MapToStream, token); } /// <inheritdoc /> @@ -236,19 +237,17 @@ } /// <inheritdoc /> - public async Task<IReadOnlyList<TopicResponse>> GetTopicsAsync(Identifier streamId, + public Task<IReadOnlyList<TopicResponse>> GetTopicsAsync(Identifier streamId, CancellationToken token = default) { - var message = TcpMessageStreamHelpers.GetBytesFromIdentifier(streamId); - using IMemoryOwner<byte> responseBuffer - = await SendWithResponseAsync(CommandCodes.GET_TOPICS_CODE, message, token: token); + return ReadWholeListAsync(CommandCodes.GET_TOPICS_CODE, [streamId], BinaryMapper.MapToTopic, token); + } - if (responseBuffer.Memory.Length == 0) - { - return []; - } - - return BinaryMapper.MapTopics(responseBuffer.Memory.Span); + /// <inheritdoc /> + public Task<Page<TopicResponse>> GetTopicsPageAsync(Identifier streamId, NamedPageQuery query, + CancellationToken token = default) + { + return ReadPageAsync(CommandCodes.GET_TOPICS_CODE, [streamId], query, BinaryMapper.MapToTopic, token); } /// <inheritdoc /> @@ -568,20 +567,20 @@ } /// <inheritdoc /> - public async Task<IReadOnlyList<ConsumerGroupResponse>> GetConsumerGroupsAsync(Identifier streamId, + public Task<IReadOnlyList<ConsumerGroupResponse>> GetConsumerGroupsAsync(Identifier streamId, Identifier topicId, CancellationToken token = default) { - var message = TcpContracts.GetGroups(streamId, topicId); - using IMemoryOwner<byte> responseBuffer - = await SendWithResponseAsync(CommandCodes.GET_CONSUMER_GROUPS_CODE, message, token: token); + return ReadWholeListAsync(CommandCodes.GET_CONSUMER_GROUPS_CODE, [streamId, topicId], + BinaryMapper.MapToConsumerGroup, token); + } - if (responseBuffer.Memory.Length == 0) - { - return []; - } - - return BinaryMapper.MapConsumerGroups(responseBuffer.Memory.Span); + /// <inheritdoc /> + public Task<Page<ConsumerGroupResponse>> GetConsumerGroupsPageAsync(Identifier streamId, Identifier topicId, + NamedPageQuery query, CancellationToken token = default) + { + return ReadPageAsync(CommandCodes.GET_CONSUMER_GROUPS_CODE, [streamId, topicId], query, + BinaryMapper.MapToConsumerGroup, token); } /// <inheritdoc /> @@ -665,6 +664,14 @@ } /// <inheritdoc /> + public Task<Page<PartitionResponse>> GetPartitionsPageAsync(Identifier streamId, Identifier topicId, + PageQuery query, CancellationToken token = default) + { + return ReadPageAsync(CommandCodes.GET_PARTITIONS_CODE, [streamId, topicId], + new NamedPageQuery { Page = query }, BinaryMapper.MapToPartition, token); + } + + /// <inheritdoc /> public async Task DeleteSegmentsAsync(Identifier streamId, Identifier topicId, uint partitionId, uint segmentsCount, CancellationToken token = default) { @@ -867,18 +874,15 @@ } /// <inheritdoc /> - public async Task<IReadOnlyList<UserResponse>> GetUsersAsync(CancellationToken token = default) + public Task<IReadOnlyList<UserResponse>> GetUsersAsync(CancellationToken token = default) { - var message = Array.Empty<byte>(); - using IMemoryOwner<byte> responseBuffer - = await SendWithResponseAsync(CommandCodes.GET_USERS_CODE, message, token: token); + return ReadWholeListAsync(CommandCodes.GET_USERS_CODE, [], BinaryMapper.MapToUserResponse, token); + } - if (responseBuffer.Memory.Length == 0) - { - return []; - } - - return BinaryMapper.MapUsers(responseBuffer.Memory.Span); + /// <inheritdoc /> + public Task<Page<UserResponse>> GetUsersPageAsync(NamedPageQuery query, CancellationToken token = default) + { + return ReadPageAsync(CommandCodes.GET_USERS_CODE, [], query, BinaryMapper.MapToUserResponse, token); } /// <inheritdoc /> @@ -1423,6 +1427,46 @@ using IMemoryOwner<byte> _ = await SendWithResponseAsync(code, body, token: token); } + private async Task<Page<T>> ReadPageAsync<T>(int code, Identifier[] parents, NamedPageQuery query, + PageItemReader<T> readItem, CancellationToken token, long? deadline = null, ulong? startedUnder = null) + { + ArgumentNullException.ThrowIfNull(query); + query.Validate(); + using IMemoryOwner<byte> responseBuffer = await SendWithResponseAsync(code, + TcpContracts.GetPage(query, parents), token: token, deadline: deadline, startedUnder: startedUnder); + + return BinaryMapper.MapPage(responseBuffer.Memory.Span, readItem); + } + + /// <summary> + /// Reads pages until one has no next cursor. The result is not one consistent read: an entity that someone + /// creates or deletes during the walk can be in it or not. The walk is one call, so every page keeps the + /// sign-in and the deadline that the walk started with. + /// </summary> + private async Task<IReadOnlyList<T>> ReadWholeListAsync<T>(int code, Identifier[] parents, + PageItemReader<T> readItem, CancellationToken token) + { + var deadline = Environment.TickCount64 + VsrRequestTimeoutMs; + var generation = _consensusSession.Generation; + var items = new List<T>(); + var query = WholeListQuery; + Page<T> page; + do + { + page = await ReadPageAsync(code, parents, query, readItem, token, deadline, generation); + if (page.Next is { } next && next.Equals(query.Page.Cursor)) + { + throw new MalformedResponseException( + "The server answered the page cursor it was sent, so the list walk would not end."); + } + + items.AddRange(page.Items); + query = query with { Page = query.Page with { Cursor = page.Next } }; + } while (page.Next is not null); + + return items; + } + internal async Task<IMemoryOwner<byte>> SendWithResponseAsync(int code, ReadOnlyMemory<byte> body, CancellationToken token = default, PartitionContext? capturedContext = null, long? deadline = null, ulong? startedUnder = null)
diff --git a/foreign/csharp/Iggy_SDK/Iggy_SDK.csproj b/foreign/csharp/Iggy_SDK/Iggy_SDK.csproj index 71adbd1..8e650e0 100644 --- a/foreign/csharp/Iggy_SDK/Iggy_SDK.csproj +++ b/foreign/csharp/Iggy_SDK/Iggy_SDK.csproj
@@ -26,7 +26,7 @@ <TargetFrameworks>net8.0;net10.0</TargetFrameworks> <AssemblyName>Apache.Iggy</AssemblyName> <RootNamespace>Apache.Iggy</RootNamespace> - <Version>0.10.0</Version> + <Version>0.10.1-edge.1</Version> <GenerateDocumentationFile>true</GenerateDocumentationFile> </PropertyGroup>
diff --git a/foreign/csharp/Iggy_SDK/JsonConverters/PageCursorConverter.cs b/foreign/csharp/Iggy_SDK/JsonConverters/PageCursorConverter.cs new file mode 100644 index 0000000..8958c07 --- /dev/null +++ b/foreign/csharp/Iggy_SDK/JsonConverters/PageCursorConverter.cs
@@ -0,0 +1,43 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using System.Text.Json; +using System.Text.Json.Serialization; +using Apache.Iggy.Contracts; + +namespace Apache.Iggy.JsonConverters; + +/// <summary>A <see cref="PageCursor" /> in JSON is its <c>pg1_</c> text.</summary> +internal sealed class PageCursorConverter : JsonConverter<PageCursor> +{ + public override PageCursor Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.String) + { + throw new JsonException("A page cursor must be a string."); + } + + return PageCursor.TryParse(reader.GetString(), out var cursor) + ? cursor + : throw new JsonException("The page cursor is not a canonical pg1_ cursor."); + } + + public override void Write(Utf8JsonWriter writer, PageCursor value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } +}
diff --git a/foreign/csharp/Iggy_SDK/Mappers/BinaryMapper.cs b/foreign/csharp/Iggy_SDK/Mappers/BinaryMapper.cs index ed280f0..a91cc58 100644 --- a/foreign/csharp/Iggy_SDK/Mappers/BinaryMapper.cs +++ b/foreign/csharp/Iggy_SDK/Mappers/BinaryMapper.cs
@@ -32,6 +32,9 @@ namespace Apache.Iggy.Mappers; +/// <summary>Reads one item of a list page at <paramref name="position" /> and returns the bytes it took.</summary> +internal delegate (T Item, int ReadBytes) PageItemReader<T>(ReadOnlySpan<byte> payload, int position); + internal static partial class BinaryMapper { private const int CONSUMER_GROUP_HEADER_SIZE = 13; @@ -88,26 +91,6 @@ }, readBytes); } - internal static IReadOnlyList<UserResponse> MapUsers(ReadOnlySpan<byte> payload) - { - if (payload.Length == 0) - { - return Array.Empty<UserResponse>(); - } - - var result = new List<UserResponse>(); - var length = payload.Length; - var position = 0; - while (position < length) - { - var (response, readBytes) = MapToUserResponse(payload, position); - result.Add(response); - position += readBytes; - } - - return result.AsReadOnly(); - } - internal static UserResponse MapUser(ReadOnlySpan<byte> payload) { var (response, position) = MapToUserResponse(payload, 0); @@ -141,7 +124,7 @@ }; } - private static (UserResponse response, int position) MapToUserResponse(ReadOnlySpan<byte> payload, int position) + internal static (UserResponse response, int position) MapToUserResponse(ReadOnlySpan<byte> payload, int position) { var id = BinaryPrimitives.ReadUInt32LittleEndian(payload[position..(position + 4)]); var createdAt = BinaryPrimitives.ReadUInt64LittleEndian(payload[(position + 4)..(position + 12)]); @@ -884,20 +867,54 @@ return bytes; } - internal static IReadOnlyList<StreamResponse> MapStreams(ReadOnlySpan<byte> payload) + /// <summary> + /// Maps the reply of a list command: <c>[next_len:u8][next][count:u32][item]*</c>. A body that is short of + /// its count of items, or that has bytes after them, is malformed. + /// </summary> + /// <remarks> + /// The item readers index the payload without bounds checks, so an argument or index fault inside an item is a + /// malformed reply. The next cursor keeps its bytes as they came, because only the server reads them. + /// </remarks> + internal static Page<T> MapPage<T>(ReadOnlySpan<byte> payload, PageItemReader<T> readItem) { - List<StreamResponse> streams = new(); - var length = payload.Length; - var position = 0; - - while (position < length) + if (payload.Length < 1 || payload.Length - 1 - payload[0] < sizeof(uint)) { - var (stream, readBytes) = MapToStream(payload, position); - streams.Add(stream); - position += readBytes; + throw new MalformedResponseException( + $"Malformed page: {payload.Length} bytes cannot hold its next cursor and item count."); } - return streams.AsReadOnly(); + var nextLength = payload[0]; + var position = 1 + nextLength; + var count = BinaryPrimitives.ReadUInt32LittleEndian(payload[position..]); + position += sizeof(uint); + + // A server never sends more than MAX_LIMIT items, so a larger count does not size the allocation. + var items = new List<T>((int)Math.Min(count, PageQuery.MAX_LIMIT)); + try + { + for (var index = 0u; index < count; index++) + { + var (item, readBytes) = readItem(payload, position); + items.Add(item); + position += readBytes; + } + } + catch (Exception error) when (error is ArgumentException or IndexOutOfRangeException) + { + throw new MalformedResponseException($"Malformed page: item {items.Count} of {count} does not decode."); + } + + if (position != payload.Length) + { + throw new MalformedResponseException( + $"Malformed page: its {count} items end at byte {position} of {payload.Length}."); + } + + return new Page<T> + { + Items = items, + Next = nextLength == 0 ? null : PageCursor.FromBytes(payload.Slice(1, nextLength)) + }; } /// <summary> @@ -968,7 +985,7 @@ }; } - private static (StreamResponse stream, int readBytes) MapToStream(ReadOnlySpan<byte> payload, int position) + internal static (StreamResponse stream, int readBytes) MapToStream(ReadOnlySpan<byte> payload, int position) { var id = BinaryPrimitives.ReadUInt32LittleEndian(payload[position..(position + 4)]); var createdAt = BinaryPrimitives.ReadUInt64LittleEndian(payload[(position + 4)..(position + 12)]); @@ -998,23 +1015,6 @@ }, readBytes); } - internal static IReadOnlyList<TopicResponse> MapTopics(ReadOnlySpan<byte> payload) - { - var topicsCount = BinaryPrimitives.ReadUInt32LittleEndian(payload[..4]); - var position = 4; - List<TopicResponse> topics = new(ValidatedCollectionSize(topicsCount, payload.Length - position, - MIN_TOPIC_SIZE, "Topics count")); - - for (var i = 0; i < topicsCount; i++) - { - var (topic, readBytes) = MapToTopic(payload, position); - topics.Add(topic); - position += readBytes; - } - - return topics.AsReadOnly(); - } - internal static TopicResponse MapTopic(ReadOnlySpan<byte> payload) { var (topic, position) = MapToTopic(payload, 0); @@ -1043,7 +1043,7 @@ }; } - private static (TopicResponse topic, int readBytes) MapToTopic(ReadOnlySpan<byte> payload, int position) + internal static (TopicResponse topic, int readBytes) MapToTopic(ReadOnlySpan<byte> payload, int position) { var id = BinaryPrimitives.ReadUInt32LittleEndian(payload[position..(position + 4)]); var createdAt = BinaryPrimitives.ReadUInt64LittleEndian(payload[(position + 4)..(position + 12)]); @@ -1072,7 +1072,7 @@ }, readBytes); } - private static (PartitionResponse partition, int readBytes) MapToPartition(ReadOnlySpan<byte> + internal static (PartitionResponse partition, int readBytes) MapToPartition(ReadOnlySpan<byte> payload, int position) { if (payload.Length - position < MIN_PARTITION_SIZE) @@ -1127,21 +1127,6 @@ return nodeIds; } - internal static List<ConsumerGroupResponse> MapConsumerGroups(ReadOnlySpan<byte> payload) - { - List<ConsumerGroupResponse> consumerGroups = new(); - var length = payload.Length; - var position = 0; - while (position < length) - { - var (consumerGroup, readBytes) = MapToConsumerGroup(payload, position); - consumerGroups.Add(consumerGroup); - position += readBytes; - } - - return consumerGroups; - } - internal static StatsResponse MapStats(ReadOnlySpan<byte> payload) { var processId = BinaryPrimitives.ReadUInt32LittleEndian(payload[..4]); @@ -1314,7 +1299,7 @@ (int)readBytes); } - private static (ConsumerGroupResponse consumerGroup, int readBytes) MapToConsumerGroup(ReadOnlySpan<byte> payload, + internal static (ConsumerGroupResponse consumerGroup, int readBytes) MapToConsumerGroup(ReadOnlySpan<byte> payload, int position) { if (position + CONSUMER_GROUP_HEADER_SIZE > payload.Length)
diff --git a/foreign/csharp/Iggy_SDK/Utils/CommandCodes.cs b/foreign/csharp/Iggy_SDK/Utils/CommandCodes.cs index 9f9f796..3018870 100644 --- a/foreign/csharp/Iggy_SDK/Utils/CommandCodes.cs +++ b/foreign/csharp/Iggy_SDK/Utils/CommandCodes.cs
@@ -68,6 +68,7 @@ // 304 was UpdateTopic and must never be reused. internal const int CREATE_PARTITIONS_CODE = 402; internal const int DELETE_PARTITIONS_CODE = 403; + internal const int GET_PARTITIONS_CODE = 404; internal const int DELETE_SEGMENTS_CODE = 503; internal const int GET_CONSUMER_GROUP_CODE = 600; internal const int GET_CONSUMER_GROUPS_CODE = 601;
diff --git a/foreign/csharp/Iggy_SDK/Vsr/LoginRegister.cs b/foreign/csharp/Iggy_SDK/Vsr/LoginRegister.cs index 587fafc..6592214 100644 --- a/foreign/csharp/Iggy_SDK/Vsr/LoginRegister.cs +++ b/foreign/csharp/Iggy_SDK/Vsr/LoginRegister.cs
@@ -35,7 +35,7 @@ internal const int PROTOCOL_VERSION_MAJOR = 0; internal const int PROTOCOL_VERSION_MINOR = 12; - internal const int PROTOCOL_VERSION_PATCH = 2; + internal const int PROTOCOL_VERSION_PATCH = 3; /// <summary>Packed protocol version: <c>major << 20 | minor << 10 | patch</c>, 10 bits each.</summary> internal const uint PROTOCOL_VERSION =
diff --git a/foreign/csharp/Iggy_SDK/Vsr/VsrError.cs b/foreign/csharp/Iggy_SDK/Vsr/VsrError.cs index 3b0484e..fdf6040 100644 --- a/foreign/csharp/Iggy_SDK/Vsr/VsrError.cs +++ b/foreign/csharp/Iggy_SDK/Vsr/VsrError.cs
@@ -52,6 +52,7 @@ internal const int NOT_PRIMARY = 89; internal const int DEFERRED_POLL_CAPACITY_EXCEEDED = 90; internal const int TIERED_READ_FAILED = 96; + internal const int REPLY_TOO_LARGE = 97; internal const int EMPTY_RESPONSE = 304; internal const int STREAM_ID_NOT_FOUND = 1009; internal const int STREAM_NAME_NOT_FOUND = 1010;
diff --git a/foreign/csharp/Iggy_SDK/Vsr/VsrOperation.cs b/foreign/csharp/Iggy_SDK/Vsr/VsrOperation.cs index f1bc5bd..752b204 100644 --- a/foreign/csharp/Iggy_SDK/Vsr/VsrOperation.cs +++ b/foreign/csharp/Iggy_SDK/Vsr/VsrOperation.cs
@@ -102,6 +102,7 @@ CommandCodes.GET_STREAMS_CODE, CommandCodes.GET_TOPIC_CODE, CommandCodes.GET_TOPICS_CODE, + CommandCodes.GET_PARTITIONS_CODE, CommandCodes.GET_CONSUMER_GROUP_CODE, CommandCodes.GET_CONSUMER_GROUPS_CODE, CommandCodes.SYNC_CONSUMER_GROUP_CODE,
diff --git a/foreign/csharp/Iggy_SDK_Tests/ClientTests/HttpListPagesTests.cs b/foreign/csharp/Iggy_SDK_Tests/ClientTests/HttpListPagesTests.cs new file mode 100644 index 0000000..7e37594 --- /dev/null +++ b/foreign/csharp/Iggy_SDK_Tests/ClientTests/HttpListPagesTests.cs
@@ -0,0 +1,189 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using System.Net; +using System.Text.Json; +using Apache.Iggy.Contracts; +using Apache.Iggy.Exceptions; +using Apache.Iggy.IggyClient.Implementations; +using Apache.Iggy.Vsr; +using static Apache.Iggy.Tests.ClientTests.HttpTopicOptionsTests; +using static Apache.Iggy.Tests.ContractsTests.ListPagesFixtureTests; + +namespace Apache.Iggy.Tests.ClientTests; + +public sealed class HttpListPagesTests +{ + private const string LastPageJson = """{"items":[]}"""; + + private const string StreamsPageJson = """ + {"items":[ + {"id":1,"created_at":1750000000000000,"name":"orders","size":"0 B", + "messages_count":0,"topics_count":0}, + {"id":4,"created_at":1750000000000001,"name":"payments-eu","size":"0 B", + "messages_count":0,"topics_count":0}], + "next":"pg1_AQQAAAAAAAAA"} + """; + + private static readonly Identifier StreamId = Identifier.Numeric(7); + private static readonly Identifier TopicId = Identifier.Numeric(3); + + public static TheoryData<string> Requests => + [.. Fixture.GetProperty("requests").EnumerateArray().Select(vector => vector.GetProperty("case").GetString()!)]; + + [Theory] + [MemberData(nameof(Requests))] + public async Task given_a_request_vector_when_reading_a_page_over_http_should_send_its_route_and_query(string name) + { + var vector = Case(Fixture, "requests", name); + var input = vector.GetProperty("input"); + var command = vector.GetProperty("command").GetString()!; + var parents = Parents(input); + var handler = new StubHandler(LastPageJson); + using var client = Client(handler); + + var next = await ReadPage(client, command, parents, input); + + Assert.Null(next); + Assert.Equal(Route(command, parents), handler.RequestPath); + Assert.Equal( + vector.GetProperty("http_query").EnumerateObject().ToDictionary(key => key.Name, + key => key.Value.GetString()!), + FormDecode(handler.RequestQuery.TrimStart('?'))); + } + + /// <summary>The server decodes the query as a form, so a raw plus would arrive as a space.</summary> + [Fact] + public async Task given_a_name_with_reserved_characters_when_reading_a_page_over_http_should_send_it_escaped() + { + const string name = "a+b&c=d %e#f/?"; + var handler = new StubHandler(LastPageJson); + using var client = Client(handler); + + await client.GetStreamsPageAsync(new NamedPageQuery { Name = name }, TestContext.Current.CancellationToken); + + Assert.Equal("/streams", handler.RequestPath); + Assert.Equal(name, FormDecode(handler.RequestQuery.TrimStart('?'))["name"]); + } + + [Fact] + public async Task given_a_page_with_and_without_next_when_reading_over_http_should_keep_next_only_when_sent() + { + var token = TestContext.Current.CancellationToken; + using var withNext = Client(new StubHandler(StreamsPageJson)); + using var withoutNext = Client(new StubHandler(LastPageJson)); + using var nullNext = Client(new StubHandler("""{"items":[],"next":null}""")); + + var page = await withNext.GetStreamsPageAsync(new NamedPageQuery(), token); + + Assert.Equal([(1u, "orders"), (4u, "payments-eu")], page.Items.Select(stream => (stream.Id, stream.Name))); + Assert.Equal("pg1_AQQAAAAAAAAA", page.Next?.ToString()); + Assert.Null((await withoutNext.GetStreamsPageAsync(new NamedPageQuery(), token)).Next); + Assert.Null((await nullNext.GetStreamsPageAsync(new NamedPageQuery(), token)).Next); + } + + [Theory] + [InlineData("""{"items":[],"next":"pg1_AQcAAAAAAAA*"}""")] + [InlineData("""{"items":[],"next":7}""")] + public async Task given_a_next_that_is_not_a_cursor_when_reading_over_http_should_raise_a_json_error(string json) + { + using var client = Client(new StubHandler(json)); + + await Assert.ThrowsAsync<JsonException>(() => + client.GetStreamsPageAsync(new NamedPageQuery(), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task given_a_broken_query_when_reading_a_page_over_http_should_refuse_it_before_sending() + { + var token = TestContext.Current.CancellationToken; + var broken = new PageQuery { Limit = 0 }; + var brokenNamed = new NamedPageQuery { Page = broken }; + var handler = new StubHandler(LastPageJson); + using var client = Client(handler); + + Task[] refused = + [ + client.GetStreamsPageAsync(brokenNamed, token), + client.GetStreamsPageAsync(new NamedPageQuery { Name = string.Empty }, token), + client.GetTopicsPageAsync(StreamId, brokenNamed, token), + client.GetPartitionsPageAsync(StreamId, TopicId, broken, token), + client.GetConsumerGroupsPageAsync(StreamId, TopicId, brokenNamed, token), + client.GetUsersPageAsync(brokenNamed, token) + ]; + foreach (var page in refused) + { + var refusal = await Assert.ThrowsAsync<IggyInvalidStatusCodeException>(() => page); + Assert.Equal(VsrError.INVALID_COMMAND, refusal.StatusCode); + Assert.False(refusal.FromServer); + } + + Assert.Empty(handler.RequestPath); + } + + /// <summary>A 404 for a topic that does not exist fails the read, as over TCP. It is not an empty page.</summary> + [Fact] + public async Task given_a_missing_topic_when_reading_a_page_over_http_should_raise_the_server_error() + { + var handler = new StubHandler( + $$"""{"id":{{VsrError.TOPIC_ID_NOT_FOUND}},"code":"topic_id_not_found","reason":"Topic not found."}""") + { + StatusCode = HttpStatusCode.NotFound + }; + using var client = Client(handler); + + var error = await Assert.ThrowsAsync<IggyInvalidStatusCodeException>(() => + client.GetPartitionsPageAsync(StreamId, TopicId, new PageQuery(), TestContext.Current.CancellationToken)); + + Assert.Equal(VsrError.TOPIC_ID_NOT_FOUND, error.StatusCode); + Assert.True(error.FromServer); + } + + private static async Task<PageCursor?> ReadPage(HttpMessageStream client, string command, Identifier[] parents, + JsonElement input) + { + var token = TestContext.Current.CancellationToken; + return command switch + { + "get_streams" => (await client.GetStreamsPageAsync(NamedQuery(input), token)).Next, + "get_topics" => (await client.GetTopicsPageAsync(parents[0], NamedQuery(input), token)).Next, + "get_partitions" => (await client.GetPartitionsPageAsync(parents[0], parents[1], Query(input), token)).Next, + "get_consumer_groups" => + (await client.GetConsumerGroupsPageAsync(parents[0], parents[1], NamedQuery(input), token)).Next, + "get_users" => (await client.GetUsersPageAsync(NamedQuery(input), token)).Next, + _ => throw new ArgumentOutOfRangeException(nameof(command), command, "The fixture names an unknown list.") + }; + } + + private static string Route(string command, Identifier[] parents) + { + return command switch + { + "get_streams" => "/streams", + "get_topics" => $"/streams/{parents[0]}/topics", + "get_partitions" => $"/streams/{parents[0]}/topics/{parents[1]}/partitions", + "get_consumer_groups" => $"/streams/{parents[0]}/topics/{parents[1]}/consumer-groups", + "get_users" => "/users", + _ => throw new ArgumentOutOfRangeException(nameof(command), command, "The fixture names an unknown list.") + }; + } + + private static HttpMessageStream Client(StubHandler handler) + { + return new HttpMessageStream(new HttpClient(handler) { BaseAddress = new Uri("http://localhost") }); + } +}
diff --git a/foreign/csharp/Iggy_SDK_Tests/ClientTests/HttpTopicOptionsTests.cs b/foreign/csharp/Iggy_SDK_Tests/ClientTests/HttpTopicOptionsTests.cs index 394aacb..3baf343 100644 --- a/foreign/csharp/Iggy_SDK_Tests/ClientTests/HttpTopicOptionsTests.cs +++ b/foreign/csharp/Iggy_SDK_Tests/ClientTests/HttpTopicOptionsTests.cs
@@ -220,10 +220,13 @@ internal string RequestPath { get; private set; } = string.Empty; + internal string RequestQuery { get; private set; } = string.Empty; + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct) { RequestPath = request.RequestUri?.AbsolutePath ?? string.Empty; + RequestQuery = request.RequestUri?.Query ?? string.Empty; if (request.Content is not null) { RequestBody = await request.Content.ReadAsStringAsync(ct);
diff --git a/foreign/csharp/Iggy_SDK_Tests/ContractsTests/ListPagesFixtureTests.cs b/foreign/csharp/Iggy_SDK_Tests/ContractsTests/ListPagesFixtureTests.cs new file mode 100644 index 0000000..d491f2e --- /dev/null +++ b/foreign/csharp/Iggy_SDK_Tests/ContractsTests/ListPagesFixtureTests.cs
@@ -0,0 +1,344 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using System.Net; +using System.Text.Json; +using Apache.Iggy.Contracts; +using Apache.Iggy.Contracts.Tcp; +using Apache.Iggy.Enums; +using Apache.Iggy.Exceptions; +using Apache.Iggy.Mappers; +using Apache.Iggy.Utils; +using Apache.Iggy.Vsr; + +namespace Apache.Iggy.Tests.ContractsTests; + +/// <summary> +/// The list page vectors that the Rust encoder generates for every SDK: each request encodes to the same bytes and +/// HTTP query, each reply decodes to the same items and next cursor, and each refused vector is refused. +/// </summary> +public sealed class ListPagesFixtureTests +{ + /// <summary>Order id, ascending and the default limit: the page block before its cursor.</summary> + private const string DefaultQueryHex = "000064000000"; + + private const string NoNameHex = "00"; + + internal static readonly JsonElement Fixture = JsonDocument + .Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "list_pages.json"))) + .RootElement; + + private static readonly JsonElement Refused = Fixture.GetProperty("refused"); + + public static TheoryData<string, string> Cursors => Cases(Fixture, "cursors", "opaque_cursors"); + + public static TheoryData<string, string> Requests => Cases(Fixture, "requests"); + + public static TheoryData<string, string> Responses => Cases(Fixture, "responses", "opaque_responses"); + + public static TheoryData<string, string> OpaqueCursors => Cases(Fixture, "opaque_cursors"); + + public static TheoryData<string, string> OpaqueResponses => Cases(Fixture, "opaque_responses"); + + public static TheoryData<string, string> RefusedCursors => Cases(Refused, "cursors"); + + public static TheoryData<string, string> RefusedQueries => Cases(Refused, "queries"); + + public static TheoryData<string, string> RefusedResponses => Cases(Refused, "responses"); + + [Fact] + public void given_the_fixture_constants_when_compared_should_match_the_client() + { + var constants = Fixture.GetProperty("constants"); + var codes = constants.GetProperty("codes"); + var errors = constants.GetProperty("errors"); + + Assert.Equal( + (CommandCodes.GET_STREAMS_CODE, CommandCodes.GET_TOPICS_CODE, CommandCodes.GET_PARTITIONS_CODE, + CommandCodes.GET_CONSUMER_GROUPS_CODE, CommandCodes.GET_USERS_CODE), + (codes.GetProperty("get_streams").GetInt32(), codes.GetProperty("get_topics").GetInt32(), + codes.GetProperty("get_partitions").GetInt32(), codes.GetProperty("get_consumer_groups").GetInt32(), + codes.GetProperty("get_users").GetInt32())); + foreach (var code in codes.EnumerateObject()) + { + Assert.Equal(VsrOperation.NonReplicated, VsrOperations.ForCode(code.Value.GetInt32())); + Assert.True(VsrOperations.IsReplaySafeRead(code.Value.GetInt32(), TcpContracts.GetPage(new NamedPageQuery())), + $"{code.Name} is not a read that is safe to send again after a lost connection."); + } + + Assert.Equal((byte)PageOrder.Id, constants.GetProperty("orders").GetProperty("id").GetByte()); + Assert.Equal((byte)PageOrder.Created, constants.GetProperty("orders").GetProperty("created").GetByte()); + Assert.Equal(PageCursor.PREFIX, constants.GetProperty("cursor_prefix").GetString()); + Assert.Equal(PageCursor.MAX_SIZE, constants.GetProperty("max_cursor_bytes").GetInt32()); + Assert.Equal(PageQuery.DEFAULT_LIMIT, constants.GetProperty("default_limit").GetUInt32()); + Assert.Equal(PageQuery.DEFAULT_LIMIT, new PageQuery().Limit); + Assert.Equal(PageQuery.MAX_LIMIT, constants.GetProperty("max_limit").GetUInt32()); + Assert.Equal(NamedPageQuery.MAX_NAME_SIZE, constants.GetProperty("max_name_bytes").GetInt32()); + Assert.Equal(VsrError.INVALID_COMMAND, errors.GetProperty("invalid_command").GetInt32()); + Assert.Equal(VsrError.REPLY_TOO_LARGE, errors.GetProperty("reply_too_large").GetInt32()); + } + + [Theory] + [MemberData(nameof(Cursors))] + public void given_a_cursor_vector_when_parsed_should_round_trip_its_text_and_bytes(string group, string name) + { + var vector = Case(Fixture, group, name); + var text = vector.GetProperty("text").GetString()!; + var bytes = Convert.FromHexString(vector.GetProperty("hex").GetString()!); + + var cursor = PageCursor.Parse(text); + + Assert.Equal(text, cursor.ToString()); + Assert.Equal(bytes, cursor.Bytes.ToArray()); + Assert.Equal(cursor, PageCursor.FromBytes(bytes)); + Assert.Equal(cursor, JsonSerializer.Deserialize<PageCursor>(JsonSerializer.Serialize(text))); + Assert.Equal(JsonSerializer.Serialize(text), JsonSerializer.Serialize(cursor)); + } + + [Theory] + [MemberData(nameof(Requests))] + public void given_a_request_vector_when_encoded_should_match_the_rust_encoder_and_http_query(string group, + string name) + { + var vector = Case(Fixture, group, name); + var input = vector.GetProperty("input"); + var query = vector.GetProperty("command").GetString() == "get_partitions" + ? new NamedPageQuery { Page = Query(input) } + : NamedQuery(input); + + query.Validate(); + + Assert.Equal(vector.GetProperty("request_hex").GetString(), + Convert.ToHexString(TcpContracts.GetPage(query, Parents(input))).ToLowerInvariant()); + Assert.Equal( + vector.GetProperty("http_query").EnumerateObject().ToDictionary(key => key.Name, + key => key.Value.GetString()!), + FormDecode(query.ToHttpQuery())); + } + + [Theory] + [MemberData(nameof(Responses))] + public void given_a_response_vector_when_decoded_should_keep_its_items_and_next_cursor(string group, string name) + { + var vector = Case(Fixture, group, name); + var next = vector.GetProperty("next"); + + var (items, cursor) = Decode(vector.GetProperty("command").GetString()!, + Convert.FromHexString(vector.GetProperty("response_hex").GetString()!)); + + Assert.Equal( + vector.GetProperty("items").EnumerateArray() + .Select(item => (item.GetProperty("id").GetUInt32(), item.GetProperty("name").GetString())), + items); + Assert.Equal(next.ValueKind == JsonValueKind.Null ? null : next.GetString(), cursor?.ToString()); + } + + /// <summary> + /// The client reads only the text of a cursor, so it sends back the bytes of a cursor that the server refuses. + /// </summary> + [Theory] + [MemberData(nameof(OpaqueCursors))] + public void given_an_opaque_cursor_when_sent_back_should_keep_its_bytes(string group, string name) + { + var vector = Case(Fixture, group, name); + + AssertSentBack(PageCursor.Parse(vector.GetProperty("text").GetString()!), vector.GetProperty("hex").GetString()!); + } + + [Theory] + [MemberData(nameof(OpaqueResponses))] + public void given_an_opaque_next_when_sent_back_should_keep_its_bytes(string group, string name) + { + var vector = Case(Fixture, group, name); + var reply = Convert.FromHexString(vector.GetProperty("response_hex").GetString()!); + + var (_, next) = Decode(vector.GetProperty("command").GetString()!, reply); + + AssertSentBack(next!, Convert.ToHexString(reply, 1, reply[0]).ToLowerInvariant()); + } + + [Theory] + [MemberData(nameof(RefusedCursors))] + public void given_a_refused_cursor_vector_when_parsed_should_refuse_it(string group, string name) + { + var text = Case(Refused, group, name).GetProperty("text").GetString()!; + + Assert.False(PageCursor.TryParse(text, out _)); + Assert.Throws<FormatException>(() => PageCursor.Parse(text)); + Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<PageCursor>(JsonSerializer.Serialize(text))); + } + + [Theory] + [MemberData(nameof(RefusedQueries))] + public void given_a_refused_query_vector_when_validated_should_refuse_it_before_sending(string group, string name) + { + var input = Case(Refused, group, name).GetProperty("input"); + + AssertRefused(NamedQuery(input).Validate); + if (input.GetProperty("name").ValueKind == JsonValueKind.Null) + { + AssertRefused(Query(input).Validate); + } + } + + [Fact] + public void given_a_query_the_vectors_cannot_hold_when_validated_should_refuse_it_before_sending() + { + AssertRefused(new NamedPageQuery { Name = "\uD800" }.Validate); + AssertRefused(new PageQuery { Order = (PageOrder)2 }.Validate); + Assert.Throws<ArgumentNullException>(new NamedPageQuery { Page = null! }.Validate); + } + + [Theory] + [MemberData(nameof(RefusedResponses))] + public void given_a_refused_response_vector_when_decoded_should_refuse_it_as_malformed(string group, string name) + { + var vector = Case(Refused, group, name); + + Assert.Throws<MalformedResponseException>(() => Decode(vector.GetProperty("command").GetString()!, + Convert.FromHexString(vector.GetProperty("response_hex").GetString()!))); + } + + /// <summary>A page that ends early never decodes into fewer items, and never fails with an index error.</summary> + [Theory] + [MemberData(nameof(Responses))] + public void given_a_response_vector_cut_at_any_length_when_decoded_should_refuse_it_as_malformed(string group, + string name) + { + var vector = Case(Fixture, group, name); + var reply = Convert.FromHexString(vector.GetProperty("response_hex").GetString()!); + + for (var length = 0; length < reply.Length; length++) + { + var cut = reply[..length]; + Assert.Throws<MalformedResponseException>(() => Decode(vector.GetProperty("command").GetString()!, cut)); + } + } + + /// <summary>The query of a vector input without its name, with the order from the fixture constants.</summary> + internal static PageQuery Query(JsonElement input) + { + var cursor = input.GetProperty("cursor"); + + return new PageQuery + { + Order = (PageOrder)Fixture.GetProperty("constants").GetProperty("orders") + .GetProperty(input.GetProperty("order").GetString()!).GetByte(), + Descending = input.GetProperty("descending").GetBoolean(), + Limit = input.GetProperty("limit").GetUInt32(), + Cursor = cursor.ValueKind == JsonValueKind.Null ? null : PageCursor.Parse(cursor.GetString()!) + }; + } + + /// <summary>The query of a vector input of a list with a name filter.</summary> + internal static NamedPageQuery NamedQuery(JsonElement input) + { + var name = input.GetProperty("name"); + + return new NamedPageQuery + { + Page = Query(input), + Name = name.ValueKind == JsonValueKind.Null ? null : name.GetString() + }; + } + + internal static Identifier[] Parents(JsonElement input) + { + return + [ + .. new[] { input.GetProperty("stream_id"), input.GetProperty("topic_id") } + .Where(identifier => identifier.ValueKind != JsonValueKind.Null) + .Select(identifier => identifier.GetProperty("kind").GetString() == "numeric" + ? Identifier.Numeric(identifier.GetProperty("value").GetUInt32()) + : Identifier.String(identifier.GetProperty("value").GetString()!)) + ]; + } + + /// <summary>Reads a query string the way the server reads a form: a plus is a space, then percent decoding.</summary> + internal static Dictionary<string, string> FormDecode(string query) + { + var pairs = new Dictionary<string, string>(); + foreach (var pair in query.Split('&')) + { + var separator = pair.IndexOf('='); + pairs.Add(WebUtility.UrlDecode(pair[..separator]), WebUtility.UrlDecode(pair[(separator + 1)..])); + } + + return pairs; + } + + internal static JsonElement Case(JsonElement parent, string group, string name) + { + return parent.GetProperty(group).EnumerateArray() + .Single(vector => vector.GetProperty("case").GetString() == name); + } + + private static (List<(uint Id, string? Name)> Items, PageCursor? Next) Decode(string command, byte[] reply) + { + return command switch + { + "get_streams" => Items(BinaryMapper.MapPage(reply, BinaryMapper.MapToStream), + stream => (stream.Id, stream.Name)), + "get_topics" => Items(BinaryMapper.MapPage(reply, BinaryMapper.MapToTopic), + topic => (topic.Id, topic.Name)), + "get_partitions" => Items(BinaryMapper.MapPage(reply, BinaryMapper.MapToPartition), + partition => (partition.Id, null)), + "get_consumer_groups" => Items(BinaryMapper.MapPage(reply, BinaryMapper.MapToConsumerGroup), + group => (group.Id, group.Name)), + "get_users" => Items(BinaryMapper.MapPage(reply, BinaryMapper.MapToUserResponse), + user => (user.Id, user.Username)), + _ => throw new ArgumentOutOfRangeException(nameof(command), command, "The fixture names an unknown list.") + }; + } + + private static (List<(uint Id, string? Name)> Items, PageCursor? Next) Items<T>(Page<T> page, + Func<T, (uint Id, string? Name)> item) + { + return ([.. page.Items.Select(item)], page.Next); + } + + private static void AssertSentBack(PageCursor cursor, string cursorHex) + { + var query = new NamedPageQuery { Page = new PageQuery { Cursor = cursor } }; + + query.Validate(); + + Assert.Equal($"{DefaultQueryHex}{cursorHex.Length / 2:x2}{cursorHex}{NoNameHex}", + Convert.ToHexString(TcpContracts.GetPage(query)).ToLowerInvariant()); + } + + private static void AssertRefused(Action validate) + { + var refusal = Assert.Throws<IggyInvalidStatusCodeException>(validate); + Assert.Equal(VsrError.INVALID_COMMAND, refusal.StatusCode); + Assert.False(refusal.FromServer); + } + + private static TheoryData<string, string> Cases(JsonElement parent, params string[] groups) + { + var cases = new TheoryData<string, string>(); + foreach (var group in groups) + { + foreach (var vector in parent.GetProperty(group).EnumerateArray()) + { + cases.Add(group, vector.GetProperty("case").GetString()!); + } + } + + return cases; + } +}
diff --git a/foreign/csharp/Iggy_SDK_Tests/Fixtures/list_pages.json b/foreign/csharp/Iggy_SDK_Tests/Fixtures/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/csharp/Iggy_SDK_Tests/Fixtures/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/csharp/Iggy_SDK_Tests/Fixtures/resource_options.json b/foreign/csharp/Iggy_SDK_Tests/Fixtures/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/csharp/Iggy_SDK_Tests/Fixtures/resource_options.json +++ b/foreign/csharp/Iggy_SDK_Tests/Fixtures/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/csharp/Iggy_SDK_Tests/Iggy_SDK_Tests.csproj b/foreign/csharp/Iggy_SDK_Tests/Iggy_SDK_Tests.csproj index 1ccfec9..9bce262 100644 --- a/foreign/csharp/Iggy_SDK_Tests/Iggy_SDK_Tests.csproj +++ b/foreign/csharp/Iggy_SDK_Tests/Iggy_SDK_Tests.csproj
@@ -58,6 +58,9 @@ <None Include="Fixtures/deferred_polling.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> + <None Include="Fixtures/list_pages.json"> + <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> + </None> </ItemGroup> </Project>
diff --git a/foreign/csharp/Iggy_SDK_Tests/MapperTests/BinaryMapper.cs b/foreign/csharp/Iggy_SDK_Tests/MapperTests/BinaryMapper.cs index 736eb19..01aa540 100644 --- a/foreign/csharp/Iggy_SDK_Tests/MapperTests/BinaryMapper.cs +++ b/foreign/csharp/Iggy_SDK_Tests/MapperTests/BinaryMapper.cs
@@ -148,7 +148,7 @@ } [Fact] - public void MapStreams_ReturnsValidStreamsResponses() + public void MapPage_OfStreams_ReturnsValidStreamsResponses() { // Arrange var (id1, topicsCount1, sizeBytes, messagesCount, name1, createdAt) @@ -159,15 +159,14 @@ var payload2 = BinaryFactory.CreateStreamPayload(id2, topicsCount2, name2, sizeBytes2, messagesCount2, createdAt2); - var combinedPayload = new byte[payload1.Length + payload2.Length]; - payload1.CopyTo(combinedPayload.AsSpan()); - payload2.CopyTo(combinedPayload.AsSpan(payload1.Length)); + var combinedPayload = BinaryFactory.CreatePagePayload([], payload1, payload2); // Act - IEnumerable<StreamResponse> responses = Mappers.BinaryMapper.MapStreams(combinedPayload).ToList(); + var page = Mappers.BinaryMapper.MapPage(combinedPayload, Mappers.BinaryMapper.MapToStream); + IEnumerable<StreamResponse> responses = page.Items; // Assert - Assert.NotNull(responses); + Assert.Null(page.Next); Assert.Equal(2, responses.Count()); var response1 = responses.ElementAt(0); @@ -232,7 +231,7 @@ } [Fact] - public void MapTopics_ReturnsValidTopicsResponses() + public void MapPage_OfTopics_ReturnsValidTopicsResponses() { // Arrange var (id1, partitionsCount1, name1, _, sizeBytesTopic1, messagesCountTopic1, createdAt, _) = @@ -245,17 +244,14 @@ sizeBytesTopic2, messagesCountTopic2, createdAt2, BinaryFactory.CreateOptionEntry(2, "compression_algorithm", 2, "gzip"u8.ToArray())); - // GetTopics replies start with the topics count. - var combinedPayload = new byte[4 + payload1.Length + payload2.Length]; - BinaryPrimitives.WriteUInt32LittleEndian(combinedPayload.AsSpan(0, 4), 2); - payload1.CopyTo(combinedPayload.AsSpan(4)); - payload2.CopyTo(combinedPayload.AsSpan(4 + payload1.Length)); + var combinedPayload = BinaryFactory.CreatePagePayload([], payload1, payload2); // Act - IReadOnlyList<TopicResponse> responses = Mappers.BinaryMapper.MapTopics(combinedPayload); + var page = Mappers.BinaryMapper.MapPage(combinedPayload, Mappers.BinaryMapper.MapToTopic); + IReadOnlyList<TopicResponse> responses = page.Items; // Assert - Assert.NotNull(responses); + Assert.Null(page.Next); Assert.Equal(2, responses.Count()); var response1 = responses.ElementAt(0); @@ -533,7 +529,7 @@ } [Fact] - public void MapConsumerGroups_ReturnsValidConsumerGroupsResponses() + public void MapPage_OfConsumerGroups_ReturnsValidConsumerGroupsResponses() { // Arrange var (id1, membersCount1, partitionsCount1, name) = ConsumerGroupFactory.CreateConsumerGroupResponseFields(); @@ -541,15 +537,14 @@ var (id2, membersCount2, partitionsCount2, name2) = ConsumerGroupFactory.CreateConsumerGroupResponseFields(); var payload2 = BinaryFactory.CreateGroupPayload(id2, membersCount2, partitionsCount2, name2); - var combinedPayload = new byte[payload1.Length + payload2.Length]; - payload1.CopyTo(combinedPayload.AsSpan()); - payload2.CopyTo(combinedPayload.AsSpan(payload1.Length)); + var combinedPayload = BinaryFactory.CreatePagePayload([], payload1, payload2); // Act - List<ConsumerGroupResponse> responses = Mappers.BinaryMapper.MapConsumerGroups(combinedPayload); + var page = Mappers.BinaryMapper.MapPage(combinedPayload, Mappers.BinaryMapper.MapToConsumerGroup); + IReadOnlyList<ConsumerGroupResponse> responses = page.Items; // Assert - Assert.NotNull(responses); + Assert.Null(page.Next); Assert.Equal(2, responses.Count); var response1 = responses[0]; @@ -627,15 +622,13 @@ } [Fact] - public void MapConsumerGroups_MultiByteName_KeepsWalkAligned() + public void MapPage_OfConsumerGroupsWithAMultiByteName_KeepsWalkAligned() { var first = BinaryFactory.CreateGroupPayload(1, 2, 3, "grüppe"); var second = BinaryFactory.CreateGroupPayload(2, 4, 5, "other"); - var combined = new byte[first.Length + second.Length]; - first.CopyTo(combined, 0); - second.CopyTo(combined, first.Length); + var combined = BinaryFactory.CreatePagePayload([], first, second); - var responses = Mappers.BinaryMapper.MapConsumerGroups(combined); + var responses = Mappers.BinaryMapper.MapPage(combined, Mappers.BinaryMapper.MapToConsumerGroup).Items; Assert.Equal(2, responses.Count); Assert.Equal("grüppe", responses[0].Name); @@ -1080,12 +1073,13 @@ } [Fact] - public void MapTopics_OversizedTopicsCount_Throws() + public void MapPage_OversizedTopicsCount_Throws() { - var payload = new byte[4]; - BinaryPrimitives.WriteUInt32LittleEndian(payload, uint.MaxValue); + var payload = BinaryFactory.CreatePagePayload([]); + BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(1), uint.MaxValue); - Assert.Throws<MalformedResponseException>(() => Mappers.BinaryMapper.MapTopics(payload)); + Assert.Throws<MalformedResponseException>(() => + Mappers.BinaryMapper.MapPage(payload, Mappers.BinaryMapper.MapToTopic)); } [Fact]
diff --git a/foreign/csharp/Iggy_SDK_Tests/Utils/BinaryFactory.cs b/foreign/csharp/Iggy_SDK_Tests/Utils/BinaryFactory.cs index 83611f5..6c82440 100644 --- a/foreign/csharp/Iggy_SDK_Tests/Utils/BinaryFactory.cs +++ b/foreign/csharp/Iggy_SDK_Tests/Utils/BinaryFactory.cs
@@ -178,6 +178,23 @@ return entry; } + /// <summary>A list reply: <c>[next_len:u8][next][count:u32][item]*</c>, with a count of the given items.</summary> + internal static byte[] CreatePagePayload(byte[] next, params byte[][] items) + { + var payload = new byte[1 + next.Length + 4 + items.Sum(item => item.Length)]; + payload[0] = (byte)next.Length; + next.CopyTo(payload.AsSpan(1)); + BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(1 + next.Length), (uint)items.Length); + var position = 1 + next.Length + 4; + foreach (var item in items) + { + item.CopyTo(payload.AsSpan(position)); + position += item.Length; + } + + return payload; + } + internal static byte[] CreateGroupPayload(uint id, uint membersCount, uint partitionsCount, string name, List<uint>? partitionsOnMember = null) {
diff --git a/foreign/csharp/Iggy_SDK_Tests/VsrTests/ListPagesWalkTests.cs b/foreign/csharp/Iggy_SDK_Tests/VsrTests/ListPagesWalkTests.cs new file mode 100644 index 0000000..690ba83 --- /dev/null +++ b/foreign/csharp/Iggy_SDK_Tests/VsrTests/ListPagesWalkTests.cs
@@ -0,0 +1,258 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +using System.Collections.Concurrent; +using System.Text.Json; +using Apache.Iggy.Configuration; +using Apache.Iggy.Contracts; +using Apache.Iggy.Contracts.Tcp; +using Apache.Iggy.Enums; +using Apache.Iggy.Exceptions; +using Apache.Iggy.IggyClient.Implementations; +using Apache.Iggy.Utils; +using Apache.Iggy.Vsr; +using Microsoft.Extensions.Logging.Abstractions; +using static Apache.Iggy.Tests.ContractsTests.ListPagesFixtureTests; +using static Apache.Iggy.Tests.VsrTests.MockFrames; + +namespace Apache.Iggy.Tests.VsrTests; + +/// <summary>The page walk of the whole-list methods and the refusal of a broken query, against one mock node.</summary> +public sealed class ListPagesWalkTests +{ + /// <summary>The first page and the second page of the walk both answer the same next cursor.</summary> + private const int PagesWithTheSameNext = 2; + + private static readonly Identifier Stream = Identifier.Numeric(7); + private static readonly Identifier Topic = Identifier.Numeric(3); + private static readonly NamedPageQuery WholeList = new() { Page = new PageQuery { Limit = PageQuery.MAX_LIMIT } }; + + /// <summary> + /// The first page of each list, from the shared vectors. Each has two items and a next cursor. The second page + /// holds the same two items without the cursor, so a walk that drops a page fails. + /// </summary> + private static readonly Dictionary<int, string> FirstPages = new() + { + [CommandCodes.GET_STREAMS_CODE] = "streams_with_next", + [CommandCodes.GET_TOPICS_CODE] = "topics_created_descending_with_next", + [CommandCodes.GET_CONSUMER_GROUPS_CODE] = "consumer_groups_with_next", + [CommandCodes.GET_USERS_CODE] = "users_with_next" + }; + + [Fact] + public async Task given_two_pages_when_reading_whole_lists_should_send_the_next_cursor_and_join_the_pages() + { + var token = TestContext.Current.CancellationToken; + Assert.Equal(Vector("requests", "streams_whole_list_walk").GetProperty("request_hex").GetString(), + Hex(TcpContracts.GetPage(WholeList))); + var lists = new ConcurrentQueue<MockRequest>(); + using var node = new MockNode(); + node.Serve(request => + { + if (!FirstPages.TryGetValue(request.Code, out var firstPage)) + { + return Other(node, request); + } + + var first = lists.All(seen => seen.Code != request.Code); + lists.Enqueue(request); + return Reply(OPERATION_NON_REPLICATED, first ? Response(firstPage) : LastPage(firstPage)); + }); + using var client = await ConnectAsync(node); + + Assert.Equal([1u, 4u, 1u, 4u], (await client.GetStreamsAsync(token)).Select(stream => stream.Id)); + Assert.Equal([3u, 1u, 3u, 1u], (await client.GetTopicsAsync(Stream, token)).Select(topic => topic.Id)); + Assert.Equal([1u, 3u, 1u, 3u], + (await client.GetConsumerGroupsAsync(Stream, Topic, token)).Select(group => group.Id)); + Assert.Equal([1u, 2u, 1u, 2u], (await client.GetUsersAsync(token)).Select(user => user.Id)); + + Assert.All(lists, request => Assert.Equal(OPERATION_NON_REPLICATED, request.Operation)); + Assert.Equal( + [ + Hex(TcpContracts.GetPage(WholeList)), + SecondPage(CommandCodes.GET_STREAMS_CODE), + Hex(TcpContracts.GetPage(WholeList, Stream)), + SecondPage(CommandCodes.GET_TOPICS_CODE, Stream), + Hex(TcpContracts.GetPage(WholeList, Stream, Topic)), + SecondPage(CommandCodes.GET_CONSUMER_GROUPS_CODE, Stream, Topic), + Hex(TcpContracts.GetPage(WholeList)), + SecondPage(CommandCodes.GET_USERS_CODE) + ], lists.Select(request => Hex(request.Body))); + } + + /// <summary> + /// A walk compares the next cursor of a page with the cursor that it sent. A one-page list sends no cursor and + /// gets no next, so it still reads. + /// </summary> + [Fact] + public async Task given_a_page_that_repeats_the_sent_cursor_when_reading_a_whole_list_should_fail_as_malformed() + { + var token = TestContext.Current.CancellationToken; + using var node = new MockNode(); + node.Serve(request => request.Code switch + { + // The page after the repeat is a last page, so a walk that misses the repeat ends and fails the test. + CommandCodes.GET_STREAMS_CODE => Reply(OPERATION_NON_REPLICATED, + node.Requests(CommandCodes.GET_STREAMS_CODE) <= PagesWithTheSameNext + ? Response("streams_with_next") + : LastPage("streams_with_next")), + CommandCodes.GET_USERS_CODE => Reply(OPERATION_NON_REPLICATED, LastPage("users_with_next")), + _ => Other(node, request) + }); + using var client = await ConnectAsync(node); + + Assert.Equal([1u, 2u], (await client.GetUsersAsync(token)).Select(user => user.Id)); + await Assert.ThrowsAsync<MalformedResponseException>(() => client.GetStreamsAsync(token)); + Assert.Equal(PagesWithTheSameNext, node.Requests(CommandCodes.GET_STREAMS_CODE)); + } + + [Fact] + public async Task given_a_caller_sign_in_during_a_walk_when_reading_the_next_page_should_fail_as_unauthenticated() + { + var token = TestContext.Current.CancellationToken; + using var node = new MockNode(); + node.Serve(request => request.Code == CommandCodes.GET_STREAMS_CODE + ? Reply(OPERATION_NON_REPLICATED, node.Requests(CommandCodes.GET_STREAMS_CODE) == 1 + ? Response("streams_with_next") + : LastPage("streams_with_next")) + : Other(node, request)); + using var client = await ConnectAsync(node); + var continuations = new NativeRecoveryTests.HeldContinuations(); + + var walk = continuations.Run(() => client.GetStreamsAsync(token)); + await continuations.Posted.WaitAsync(token); + Assert.Equal(1, node.Requests(CommandCodes.GET_STREAMS_CODE)); + await client.LoginUserAsync("other", "secret", token); + + var failure = await Assert.ThrowsAsync<IggyInvalidStatusCodeException>(() => + continuations.FinishAsync(walk, token).WaitAsync(TimeSpan.FromSeconds(10), token)); + Assert.Equal(VsrError.UNAUTHENTICATED, failure.StatusCode); + Assert.False(failure.FromServer); + Assert.Equal(1, node.Requests(CommandCodes.GET_STREAMS_CODE)); + } + + [Fact] + public async Task given_a_broken_query_when_reading_a_page_should_refuse_it_before_sending() + { + var token = TestContext.Current.CancellationToken; + var broken = new PageQuery { Limit = 0 }; + var brokenNamed = new NamedPageQuery { Page = broken }; + var partitionsRequest = Vector("requests", "partitions_numeric_ids_first_page"); + var lists = new ConcurrentQueue<MockRequest>(); + using var node = new MockNode(); + node.Serve(request => + { + if (request.Code != CommandCodes.GET_PARTITIONS_CODE && !FirstPages.ContainsKey(request.Code)) + { + return Other(node, request); + } + + lists.Enqueue(request); + return Reply(OPERATION_NON_REPLICATED, Response("partitions_with_next")); + }); + using var client = await ConnectAsync(node); + + Task[] refused = + [ + client.GetStreamsPageAsync(brokenNamed, token), + client.GetStreamsPageAsync(new NamedPageQuery { Name = string.Empty }, token), + client.GetTopicsPageAsync(Stream, brokenNamed, token), + client.GetPartitionsPageAsync(Stream, Topic, broken, token), + client.GetConsumerGroupsPageAsync(Stream, Topic, brokenNamed, token), + client.GetUsersPageAsync(brokenNamed, token) + ]; + foreach (var page in refused) + { + var refusal = await Assert.ThrowsAsync<IggyInvalidStatusCodeException>(() => page); + Assert.Equal(VsrError.INVALID_COMMAND, refusal.StatusCode); + Assert.False(refusal.FromServer); + } + + var partitions = await client.GetPartitionsPageAsync(Stream, Topic, Query(partitionsRequest.GetProperty("input")), + token); + + Assert.Equal([0u, 1u], partitions.Items.Select(partition => partition.Id)); + Assert.Equal("pg1_AQEAAAAAAAAA", partitions.Next?.ToString()); + var sent = Assert.Single(lists); + Assert.Equal(CommandCodes.GET_PARTITIONS_CODE, sent.Code); + Assert.Equal(OPERATION_NON_REPLICATED, sent.Operation); + Assert.Equal(partitionsRequest.GetProperty("request_hex").GetString(), Hex(sent.Body)); + } + + /// <summary>A server of this version always sends the next cursor length and the count, even for no items.</summary> + [Fact] + public async Task given_an_empty_reply_when_reading_a_page_should_refuse_it_as_malformed() + { + using var node = new MockNode(); + var emptyBody = Case(Fixture.GetProperty("refused"), "responses", "empty_body"); + node.Serve(request => request.Code == CommandCodes.GET_STREAMS_CODE + ? Reply(OPERATION_NON_REPLICATED, + Convert.FromHexString(emptyBody.GetProperty("response_hex").GetString()!)) + : Other(node, request)); + using var client = await ConnectAsync(node); + + await Assert.ThrowsAsync<MalformedResponseException>(() => + client.GetStreamsAsync(TestContext.Current.CancellationToken)); + } + + private static byte[] Other(MockNode node, MockRequest request) + { + return request.Code == GET_CLUSTER_METADATA_CODE ? StandaloneRoster(node.Port) : Answer(request); + } + + private static JsonElement Vector(string group, string name) + { + return Case(Fixture, group, name); + } + + private static byte[] Response(string name) + { + return Convert.FromHexString(Vector("responses", name).GetProperty("response_hex").GetString()!); + } + + /// <summary>The reply of a vector with its next cursor cut out: the same items on the last page.</summary> + private static byte[] LastPage(string name) + { + var page = Response(name); + return [0, .. page.AsSpan(1 + page[0])]; + } + + /// <summary>The second request of a walk carries the next cursor of the first page of the list.</summary> + private static string SecondPage(int code, params Identifier[] parents) + { + var next = PageCursor.Parse(Vector("responses", FirstPages[code]).GetProperty("next").GetString()!); + return Hex(TcpContracts.GetPage(WholeList with { Page = WholeList.Page with { Cursor = next } }, parents)); + } + + private static string Hex(byte[] bytes) + { + return Convert.ToHexString(bytes).ToLowerInvariant(); + } + + private static async Task<TcpMessageStream> ConnectAsync(MockNode node) + { + var client = new TcpMessageStream(new IggyClientConfigurator + { + BaseAddress = $"127.0.0.1:{node.Port}", + Protocol = Protocol.Tcp + }, NullLoggerFactory.Instance); + await client.ConnectAsync(TestContext.Current.CancellationToken); + await client.LoginUserAsync("user", "secret", TestContext.Current.CancellationToken); + + return client; + } +}
diff --git a/foreign/csharp/Iggy_SDK_Tests/VsrTests/NativeRecoveryTests.SignIn.cs b/foreign/csharp/Iggy_SDK_Tests/VsrTests/NativeRecoveryTests.SignIn.cs index 0563212..1973527 100644 --- a/foreign/csharp/Iggy_SDK_Tests/VsrTests/NativeRecoveryTests.SignIn.cs +++ b/foreign/csharp/Iggy_SDK_Tests/VsrTests/NativeRecoveryTests.SignIn.cs
@@ -662,7 +662,7 @@ return release.Task; } - private sealed class HeldContinuations : SynchronizationContext + internal sealed class HeldContinuations : SynchronizationContext { private readonly ConcurrentQueue<(SendOrPostCallback Callback, object? State)> _pending = new(); internal SemaphoreSlim Posted { get; } = new(0);
diff --git a/foreign/csharp/README.md b/foreign/csharp/README.md index 48f89ba..8d25615 100644 --- a/foreign/csharp/README.md +++ b/foreign/csharp/README.md
@@ -28,7 +28,7 @@ from the same checkout. The SDK targets .NET 8 and .NET 10. Repository examples require .NET 10. `0.9.0` includes the independent message and consumer-offset durability options. -This checkout uses binary protocol 0.12.2. Servers and applicable SDKs must deploy together. Mixed versions and +This checkout uses binary protocol 0.12.3. Servers and applicable SDKs must deploy together. Mixed versions and rolling upgrades are unsupported. This checkout requires fresh storage and refuses older data directories without modification. `--fresh` deletes existing data in the configured directory. See the [server recovery guide](../../core/server/README.md#upgrade-recovery). @@ -1021,6 +1021,37 @@ Available snapshot types: `FilesystemOverview`, `ProcessList`, `ResourceUsage`, `Test`, `ServerLogs`, `ServerConfig`, `All`. +### List Pages + +`GetStreamsAsync`, `GetTopicsAsync`, `GetConsumerGroupsAsync` and `GetUsersAsync` return a whole list. Over TCP, each of them reads the list in pages of at most 1,000 items, so the result is not one consistent read. An entity that someone creates or deletes during the walk can appear or not appear. Every page keeps the sign-in and the call deadline that the walk started with. If the server answers a page with the same cursor that the client sent, the walk fails with a `MalformedResponseException`. + +Over HTTP, they read the whole list in one reply. The server builds that reply from pages of 1,000 items, so it is not one consistent read either. + +`GetStreamsPageAsync`, `GetTopicsPageAsync`, `GetPartitionsPageAsync`, `GetConsumerGroupsPageAsync` and `GetUsersPageAsync` return one page. To read the next page, send the same query with the `Next` of the page as its cursor. A page can be empty and still have a `Next`. + +```c# +var query = new NamedPageQuery(); +while (true) +{ + var page = await client.GetStreamsPageAsync(query); + foreach (var stream in page.Items) + { + Console.WriteLine($"{stream.Id} {stream.Name}"); + } + + if (page.Next is null) + { + break; + } + + query = query with { Page = query.Page with { Cursor = page.Next } }; +} +``` + +A `PageQuery` holds `Order`, `Descending`, `Limit` and `Cursor`. `Order` selects `PageOrder.Id` or `PageOrder.Created`, and `Descending` reverses it. The stream, topic, consumer group and user page methods take a `NamedPageQuery`, which holds a `PageQuery` as `Page` and an optional `Name`. `Name` keeps the entries whose name holds the text, case-sensitive. `GetPartitionsPageAsync` takes a `PageQuery`, which has no name. + +The client refuses a query that breaks the page rules with an `IggyInvalidStatusCodeException` for invalid command (code 3), before it sends anything. Examples are a limit outside 1 to 1000 and a name that is empty or longer than 255 bytes. A `PageCursor` prints and parses as the `pg1_` text form that the HTTP API and the CLI use. The client does not read the bytes of a cursor. The server refuses a cursor that it cannot use, also with invalid command. + ### Metadata Changes `GetMetadataChangesAsync` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `Next` cursor. The call needs root or the global `ManageServers` permission and works over TCP and HTTP.
diff --git a/foreign/go/README.md b/foreign/go/README.md index 67db553..92cd30d 100644 --- a/foreign/go/README.md +++ b/foreign/go/README.md
@@ -96,6 +96,35 @@ The server stores the key wrapped under its own key and never returns it. Reads report only its source and fingerprints. Without a key, a server with encryption enabled generates one for the stream, and a server without it keeps the stream plaintext and refuses a client key. +## List pages + +`GetStreams`, `GetTopics`, `GetConsumerGroups` and `GetUsers` return a whole list. Each of them reads the list in pages of at most 1,000 items, so the result is not one consistent read. Every page keeps the sign-in and the deadline that the call started with. An entity that someone creates or deletes during the walk can appear or not appear. If the `Next` of a page is the cursor that its request sent, the call fails with `ierror.ErrInvalidFormat`. + +`GetStreamsPage`, `GetTopicsPage`, `GetPartitionsPage`, `GetConsumerGroupsPage` and `GetUsersPage` return one page. To read the next page, send the same query with the `Next` of the page as its `Cursor`. A page can be empty and still have a `Next`. + +```go +func printStreams(ctx context.Context, cli iggcon.Client) error { + query := iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()} + for { + page, err := cli.GetStreamsPage(ctx, query) + if err != nil { + return err + } + for _, stream := range page.Items { + log.Printf("%d %s", stream.Id, stream.Name) + } + if page.Next == nil { + return nil + } + query.Cursor = page.Next + } +} +``` + +`Order` selects `PageOrderID` or `PageOrderCreated`, and `Descending` reverses it. The page methods of streams, topics, consumer groups and users take a `NamedPageQuery`: a `PageQuery` with a `Name`. `Name` keeps the entries whose name holds the text, case-sensitive. `GetPartitionsPage` takes a `PageQuery`, which has no name. + +The client refuses a query that breaks the page rules with `ierror.ErrInvalidCommand`, before it sends anything. Examples are a limit outside 1 to 1000 and a name that is empty or longer than 255 bytes. A cursor prints and parses as the `pg1_` text form that the HTTP API and the CLI use. The client does not read the bytes of a cursor. The server refuses a cursor that it cannot use, also with `ierror.ErrInvalidCommand`. + ## Metadata changes `GetMetadataChanges` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `Next` cursor. The call needs root or the global `manage_servers` permission.
diff --git a/foreign/go/binary_serialization/binary_response_deserializer.go b/foreign/go/binary_serialization/binary_response_deserializer.go index fade92c..1132e1c 100644 --- a/foreign/go/binary_serialization/binary_response_deserializer.go +++ b/foreign/go/binary_serialization/binary_response_deserializer.go
@@ -84,22 +84,6 @@ }, nil } -func DeserializeStreams(payload []byte) ([]iggcon.Stream, error) { - streams := make([]iggcon.Stream, 0) - position := 0 - - for position < len(payload) { - stream, readBytes, err := DeserializeToStream(payload, position) - if err != nil { - return nil, fmt.Errorf("failed to deserialize stream at offset %d: %w", position, err) - } - streams = append(streams, stream) - position += readBytes - } - - return streams, nil -} - const streamFixedSize = 4 + 8 + 4 + 8 + 8 + 1 // 33 bytes: id + created_at + topics_count + size_bytes + messages_count + name_len func DeserializeToStream(payload []byte, position int) (iggcon.Stream, int, error) { @@ -467,29 +451,6 @@ return payload[position : position+length], 4 + length, nil } -func DeserializeTopics(payload []byte) ([]iggcon.Topic, error) { - if len(payload) < 4 { - return nil, fmt.Errorf( - "not enough data to read topics count: need 4 bytes, got %d", len(payload)) - } - topicsCount := binary.LittleEndian.Uint32(payload[0:4]) - position := 4 - - // The declared count is server-controlled; the allocation hint is capped - // by what the body could possibly hold. - topics := make([]iggcon.Topic, 0, boundedCapacity(topicsCount, len(payload)-position, topicMinimumSize)) - for i := uint32(0); i < topicsCount; i++ { - topic, readBytes, err := DeserializeToTopic(payload, position) - if err != nil { - return nil, err - } - topics = append(topics, topic) - position += readBytes - } - - return topics, nil -} - func DeserializeTopic(payload []byte) (*iggcon.TopicDetails, error) { topic, position, err := DeserializeToTopic(payload, 0) if err != nil { @@ -688,42 +649,37 @@ return bytes.Clone(payload[start : start+count]), start + count, nil } -func DeserializeConsumerGroups(payload []byte) []iggcon.ConsumerGroup { - var consumerGroups []iggcon.ConsumerGroup - length := len(payload) - position := 0 +// consumerGroupFixedSize covers the fields before the name: +// id + partitions_count + members_count + name_len. +const consumerGroupFixedSize = 4 + 4 + 4 + 1 - for position < length { - // use slices - consumerGroup, readBytes := DeserializeToConsumerGroup(payload, position) - consumerGroups = append(consumerGroups, *consumerGroup) - position += readBytes +func DeserializeToConsumerGroup(payload []byte, position int) (iggcon.ConsumerGroup, int, error) { + remaining := len(payload) - position + if remaining < consumerGroupFixedSize { + return iggcon.ConsumerGroup{}, 0, fmt.Errorf( + "not enough data to read consumer group header: need %d bytes, got %d", + consumerGroupFixedSize, remaining) + } + readBytes := consumerGroupFixedSize + int(payload[position+12]) + if remaining < readBytes { + return iggcon.ConsumerGroup{}, 0, fmt.Errorf( + "not enough data to read consumer group name: need %d bytes, got %d", + readBytes, remaining) } - return consumerGroups + return iggcon.ConsumerGroup{ + Id: binary.LittleEndian.Uint32(payload[position : position+4]), + PartitionsCount: binary.LittleEndian.Uint32(payload[position+4 : position+8]), + MembersCount: binary.LittleEndian.Uint32(payload[position+8 : position+12]), + Name: string(payload[position+consumerGroupFixedSize : position+readBytes]), + }, readBytes, nil } -func DeserializeToConsumerGroup(payload []byte, position int) (*iggcon.ConsumerGroup, int) { - id := binary.LittleEndian.Uint32(payload[position : position+4]) - partitionsCount := binary.LittleEndian.Uint32(payload[position+4 : position+8]) - membersCount := binary.LittleEndian.Uint32(payload[position+8 : position+12]) - nameLength := int(payload[position+12]) - name := string(payload[position+13 : position+13+nameLength]) - - readBytes := 12 + 1 + nameLength - - consumerGroup := iggcon.ConsumerGroup{ - Id: id, - MembersCount: membersCount, - PartitionsCount: partitionsCount, - Name: name, +func DeserializeConsumerGroup(payload []byte) (*iggcon.ConsumerGroupDetails, error) { + consumerGroup, pos, err := DeserializeToConsumerGroup(payload, 0) + if err != nil { + return nil, err } - - return &consumerGroup, readBytes -} - -func DeserializeConsumerGroup(payload []byte) *iggcon.ConsumerGroupDetails { - consumerGroup, pos := DeserializeToConsumerGroup(payload, 0) members := make([]iggcon.ConsumerGroupMember, 0) for pos < len(payload) { m, readBytes := DeserializeToConsumerGroupMember(payload, pos) @@ -734,9 +690,9 @@ return members[i].ID < members[j].ID }) return &iggcon.ConsumerGroupDetails{ - ConsumerGroup: *consumerGroup, + ConsumerGroup: consumerGroup, Members: members, - } + }, nil } func DeserializeToConsumerGroupMember(payload []byte, position int) (iggcon.ConsumerGroupMember, int) { @@ -755,27 +711,6 @@ }, readBytes } -func DeserializeUsers(payload []byte) ([]iggcon.UserInfo, error) { - if len(payload) == 0 { - return nil, errors.New("empty payload") - } - - var result []iggcon.UserInfo - length := len(payload) - position := 0 - - for position < length { - response, readBytes, err := deserializeToUser(payload, position) - if err != nil { - return nil, err - } - result = append(result, *response) - position += readBytes - } - - return result, nil -} - func DeserializeUser(payload []byte) (*iggcon.UserInfoDetails, error) { response, position, err := deserializeToUser(payload, 0) if err != nil {
diff --git a/foreign/go/binary_serialization/binary_response_deserializer_test.go b/foreign/go/binary_serialization/binary_response_deserializer_test.go index ee3e13b..2e78966 100644 --- a/foreign/go/binary_serialization/binary_response_deserializer_test.go +++ b/foreign/go/binary_serialization/binary_response_deserializer_test.go
@@ -19,12 +19,14 @@ import ( "encoding/binary" + "errors" "fmt" "strings" "testing" "time" iggcon "github.com/apache/iggy/foreign/go/contracts" + ierror "github.com/apache/iggy/foreign/go/errors" ) func buildFetchPayload(payloadBody []byte) []byte { @@ -233,26 +235,28 @@ } } -func TestDeserializeStreams_Empty(t *testing.T) { - streams, err := DeserializeStreams([]byte{}) +func TestDeserializeStreamsPage_Empty(t *testing.T) { + page, err := DeserializeStreamsPage(streamsPage()) if err != nil { t.Fatalf("unexpected error: %v", err) } - if len(streams) != 0 { - t.Fatalf("expected 0 streams, got %d", len(streams)) + if len(page.Items) != 0 || page.Next != nil { + t.Fatalf("expected an empty last page, got %d streams and next %v", len(page.Items), page.Next) } } -func TestDeserializeStreams_MultipleStreams(t *testing.T) { - var payload []byte - payload = append(payload, encodeStream(1, 100, 2, 512, 50, "stream-one")...) - payload = append(payload, encodeStream(2, 200, 0, 0, 0, "s2")...) - payload = append(payload, encodeStream(3, 300, 1, 1024, 10, "third")...) +func TestDeserializeStreamsPage_MultipleStreams(t *testing.T) { + payload := streamsPage( + encodeStream(1, 100, 2, 512, 50, "stream-one"), + encodeStream(2, 200, 0, 0, 0, "s2"), + encodeStream(3, 300, 1, 1024, 10, "third"), + ) - streams, err := DeserializeStreams(payload) + page, err := DeserializeStreamsPage(payload) if err != nil { t.Fatalf("unexpected error: %v", err) } + streams := page.Items if len(streams) != 3 { t.Fatalf("expected 3 streams, got %d", len(streams)) } @@ -262,39 +266,43 @@ assertStream(t, "stream[2]", streams[2], 3, 300, 1, 1024, 10, "third") } -func TestDeserializeStreams_CorruptedPayload(t *testing.T) { +func TestDeserializeStreamsPage_CorruptedPayload(t *testing.T) { good := encodeStream(1, 100, 0, 0, 0, "ok") truncated := make([]byte, streamFixedSize-5) - payload := append(good, truncated...) - _, err := DeserializeStreams(payload) - if err == nil { - t.Fatal("expected error for corrupted payload, got nil") + _, err := DeserializeStreamsPage(streamsPage(good, truncated)) + if !errors.Is(err, ierror.ErrInvalidFormat) { + t.Fatalf("expected ErrInvalidFormat for corrupted payload, got %v", err) } } // Regression test for issue #3130: payloads > 64KB produced corrupted // stream lists because no bounds checking was performed. -func TestDeserializeStreams_LargePayloadOver64KB(t *testing.T) { +func TestDeserializeStreamsPage_LargePayloadOver64KB(t *testing.T) { const targetSize = 70_000 - var payload []byte + var encoded [][]byte + var size int var id uint32 - for len(payload) < targetSize { + for size < targetSize { id++ name := fmt.Sprintf("stream-with-a-longer-name-for-padding-%d", id) - payload = append(payload, encodeStream(id, uint64(id)*1000, id%10, uint64(id)*512, uint64(id)*5, name)...) + stream := encodeStream(id, uint64(id)*1000, id%10, uint64(id)*512, uint64(id)*5, name) + encoded = append(encoded, stream) + size += len(stream) } + payload := streamsPage(encoded...) if len(payload) <= 1<<16 { t.Fatalf("payload size %d is not > 64KB; increase stream count or name length", len(payload)) } - streams, err := DeserializeStreams(payload) + page, err := DeserializeStreamsPage(payload) if err != nil { t.Fatalf("unexpected error deserializing %d-byte payload: %v", len(payload), err) } + streams := page.Items if uint32(len(streams)) != id { t.Fatalf("expected %d streams, got %d", id, len(streams)) } @@ -308,17 +316,18 @@ } } -func TestDeserializeStreams_MaxLengthName(t *testing.T) { +func TestDeserializeStreamsPage_MaxLengthName(t *testing.T) { name := make([]byte, 255) for i := range name { name[i] = 'a' + byte(i%26) } - payload := encodeStream(1, 999, 3, 4096, 200, string(name)) + payload := streamsPage(encodeStream(1, 999, 3, 4096, 200, string(name))) - streams, err := DeserializeStreams(payload) + page, err := DeserializeStreamsPage(payload) if err != nil { t.Fatalf("unexpected error: %v", err) } + streams := page.Items if len(streams) != 1 { t.Fatalf("expected 1 stream, got %d", len(streams)) } @@ -327,6 +336,16 @@ } } +// streamsPage frames encoded streams as the last page of a GetStreams reply: +// no next cursor, then the count. +func streamsPage(streams ...[]byte) []byte { + payload := binary.LittleEndian.AppendUint32([]byte{0}, uint32(len(streams))) + for _, stream := range streams { + payload = append(payload, stream...) + } + return payload +} + func TestBoundedCapacity_CapsDeclaredCount(t *testing.T) { tests := []struct { name string
diff --git a/foreign/go/binary_serialization/page_deserializer.go b/foreign/go/binary_serialization/page_deserializer.go new file mode 100644 index 0000000..c3dcaae --- /dev/null +++ b/foreign/go/binary_serialization/page_deserializer.go
@@ -0,0 +1,90 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package binaryserialization + +import ( + "fmt" + + iggcon "github.com/apache/iggy/foreign/go/contracts" + ierror "github.com/apache/iggy/foreign/go/errors" +) + +// DeserializeStreamsPage reads a GetStreams reply. +func DeserializeStreamsPage(payload []byte) (*iggcon.Page[iggcon.Stream], error) { + return deserializePage(payload, DeserializeToStream) +} + +// DeserializeTopicsPage reads a GetTopics reply. +func DeserializeTopicsPage(payload []byte) (*iggcon.Page[iggcon.Topic], error) { + return deserializePage(payload, DeserializeToTopic) +} + +// DeserializePartitionsPage reads a GetPartitions reply. +func DeserializePartitionsPage(payload []byte) (*iggcon.Page[iggcon.PartitionContract], error) { + return deserializePage(payload, DeserializePartition) +} + +// DeserializeConsumerGroupsPage reads a GetConsumerGroups reply. +func DeserializeConsumerGroupsPage(payload []byte) (*iggcon.Page[iggcon.ConsumerGroup], error) { + return deserializePage(payload, DeserializeToConsumerGroup) +} + +// DeserializeUsersPage reads a GetUsers reply. +func DeserializeUsersPage(payload []byte) (*iggcon.Page[iggcon.UserInfo], error) { + return deserializePage(payload, func(payload []byte, position int) (iggcon.UserInfo, int, error) { + user, size, err := deserializeToUser(payload, position) + if err != nil { + return iggcon.UserInfo{}, 0, err + } + return *user, size, nil + }) +} + +// deserializePage reads the reply of a list command: +// [next_len:u8][next][count:u32][item]*. A body short of count items, or with +// bytes after them, is refused with ierror.ErrInvalidFormat. The next cursor +// keeps its bytes as they came, because only the server reads them. +func deserializePage[T any](payload []byte, readItem func([]byte, int) (T, int, error)) (*iggcon.Page[T], error) { + reader := &changeReader{data: payload} + next := reader.take(int(reader.readUint8())) + count := reader.readUint32() + if reader.err != nil { + return nil, reader.err + } + // A server never sends more than MaxPageLimit items, so a larger count + // does not size the allocation. + page := &iggcon.Page[T]{Items: make([]T, 0, min(count, iggcon.MaxPageLimit))} + if len(next) > 0 { + page.Next = &iggcon.PageCursor{} + if err := page.Next.UnmarshalBinary(next); err != nil { + return nil, err + } + } + for index := range count { + item, size, err := readItem(payload, reader.position) + if err != nil { + return nil, fmt.Errorf("%w: item %d of %d of a page: %w", ierror.ErrInvalidFormat, index, count, err) + } + page.Items = append(page.Items, item) + reader.position += size + } + if trailing := reader.remaining(); trailing != 0 { + return nil, fmt.Errorf("%w: %d trailing bytes after a page", ierror.ErrInvalidFormat, trailing) + } + return page, nil +}
diff --git a/foreign/go/client/tcp/tcp_consumer_group_management.go b/foreign/go/client/tcp/tcp_consumer_group_management.go index 8f9be0e..aec3821 100644 --- a/foreign/go/client/tcp/tcp_consumer_group_management.go +++ b/foreign/go/client/tcp/tcp_consumer_group_management.go
@@ -29,15 +29,25 @@ ) func (c *IggyTcpClient) GetConsumerGroups(ctx context.Context, streamId, topicId iggcon.Identifier) ([]iggcon.ConsumerGroup, error) { + return readWholeList(ctx, c, func(ctx context.Context, query iggcon.PageQuery) (*iggcon.Page[iggcon.ConsumerGroup], error) { + return c.GetConsumerGroupsPage(ctx, streamId, topicId, iggcon.NamedPageQuery{PageQuery: query}) + }) +} + +func (c *IggyTcpClient) GetConsumerGroupsPage( + ctx context.Context, + streamId, topicId iggcon.Identifier, + query iggcon.NamedPageQuery, +) (*iggcon.Page[iggcon.ConsumerGroup], error) { buffer, err := c.do(ctx, &command.GetConsumerGroups{ StreamId: streamId, TopicId: topicId, + Query: query, }) if err != nil { return nil, err } - - return binaryserialization.DeserializeConsumerGroups(buffer), err + return binaryserialization.DeserializeConsumerGroupsPage(buffer) } func (c *IggyTcpClient) GetConsumerGroup(ctx context.Context, streamId, topicId, groupId iggcon.Identifier) (*iggcon.ConsumerGroupDetails, error) { @@ -55,8 +65,7 @@ return nil, ierror.ErrConsumerGroupIdNotFound } - consumerGroupDetails := binaryserialization.DeserializeConsumerGroup(buffer) - return consumerGroupDetails, err + return binaryserialization.DeserializeConsumerGroup(buffer) } func (c *IggyTcpClient) CreateConsumerGroup(ctx context.Context, streamId iggcon.Identifier, topicId iggcon.Identifier, name string) (*iggcon.ConsumerGroupDetails, error) { @@ -73,8 +82,7 @@ if err != nil { return nil, err } - consumerGroup := binaryserialization.DeserializeConsumerGroup(buffer) - return consumerGroup, err + return binaryserialization.DeserializeConsumerGroup(buffer) } func (c *IggyTcpClient) DeleteConsumerGroup(ctx context.Context, streamId iggcon.Identifier, topicId iggcon.Identifier, groupId iggcon.Identifier) error {
diff --git a/foreign/go/client/tcp/tcp_consumer_group_management_test.go b/foreign/go/client/tcp/tcp_consumer_group_management_test.go index 84bc487..0558221 100644 --- a/foreign/go/client/tcp/tcp_consumer_group_management_test.go +++ b/foreign/go/client/tcp/tcp_consumer_group_management_test.go
@@ -44,9 +44,9 @@ func TestGetConsumerGroups_DecodesTheRoster(t *testing.T) { client, serverConn := newPipeClient(t) - body := append( + body := pageBody(nil, consumerGroupBody(1, 3, 2, "billing"), - consumerGroupBody(2, 1, 0, "audit")...) + consumerGroupBody(2, 1, 0, "audit")) serve(serverConn, func(_ int, _ request) []byte { return replyFrame(vsr.OperationNonReplicated, body) })
diff --git a/foreign/go/client/tcp/tcp_pages.go b/foreign/go/client/tcp/tcp_pages.go new file mode 100644 index 0000000..9b28786 --- /dev/null +++ b/foreign/go/client/tcp/tcp_pages.go
@@ -0,0 +1,61 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package tcp + +import ( + "context" + "fmt" + + iggcon "github.com/apache/iggy/foreign/go/contracts" + ierror "github.com/apache/iggy/foreign/go/errors" +) + +// readWholeList reads a list one page at a time, in ascending id order and in +// pages of iggcon.MaxPageLimit, until a page has no next cursor. The walk is +// one call, so every page keeps the sign-in and the deadline that it started +// with. The result is not one consistent read: an entity that someone creates +// or deletes during the walk can appear or not appear. A page whose next +// cursor is the cursor of its request fails the walk with +// ierror.ErrInvalidFormat, so a faulty server cannot make the walk loop forever. +func readWholeList[T any]( + ctx context.Context, + c *IggyTcpClient, + readPage func(context.Context, iggcon.PageQuery) (*iggcon.Page[T], error), +) ([]T, error) { + if ctx == nil { + return nil, ierror.ErrNilContext + } + ctx, cancel := c.operationContext(ctx) + defer cancel() + query := iggcon.PageQuery{Order: iggcon.PageOrderID, Limit: iggcon.MaxPageLimit} + items := []T{} + for { + page, err := readPage(ctx, query) + if err != nil { + return nil, err + } + items = append(items, page.Items...) + if page.Next == nil { + return items, nil + } + if query.Cursor != nil && *page.Next == *query.Cursor { + return nil, fmt.Errorf("%w: the server answered the page cursor it was sent", ierror.ErrInvalidFormat) + } + query.Cursor = page.Next + } +}
diff --git a/foreign/go/client/tcp/tcp_partition_management.go b/foreign/go/client/tcp/tcp_partition_management.go index 2e85a50..70410d4 100644 --- a/foreign/go/client/tcp/tcp_partition_management.go +++ b/foreign/go/client/tcp/tcp_partition_management.go
@@ -20,10 +20,27 @@ import ( "context" + binaryserialization "github.com/apache/iggy/foreign/go/binary_serialization" iggcon "github.com/apache/iggy/foreign/go/contracts" "github.com/apache/iggy/foreign/go/internal/command" ) +func (c *IggyTcpClient) GetPartitionsPage( + ctx context.Context, + streamId, topicId iggcon.Identifier, + query iggcon.PageQuery, +) (*iggcon.Page[iggcon.PartitionContract], error) { + buffer, err := c.do(ctx, &command.GetPartitions{ + StreamId: streamId, + TopicId: topicId, + Query: query, + }) + if err != nil { + return nil, err + } + return binaryserialization.DeserializePartitionsPage(buffer) +} + func (c *IggyTcpClient) CreatePartitions(ctx context.Context, streamId iggcon.Identifier, topicId iggcon.Identifier, partitionsCount uint32) error { _, err := c.do(ctx, &command.CreatePartitions{ StreamId: streamId,
diff --git a/foreign/go/client/tcp/tcp_replicas_test.go b/foreign/go/client/tcp/tcp_replicas_test.go index 386525d..927bbae 100644 --- a/foreign/go/client/tcp/tcp_replicas_test.go +++ b/foreign/go/client/tcp/tcp_replicas_test.go
@@ -311,7 +311,7 @@ requests := []command.Command{ rawRequest{code: command.SendMessagesCode, payload: rawSendPayload(t, stream, topic, iggcon.PartitionId(0))}, &command.PollMessages{StreamId: stream, TopicId: topic, Consumer: iggcon.NewSingleConsumer(group.Id), Strategy: iggcon.NextPollingStrategy(), Count: 1}, - &command.GetStreams{}, + &command.GetStreams{Query: iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()}}, } for _, request := range requests { time.Sleep(2 * managedLinkHeartbeat)
diff --git a/foreign/go/client/tcp/tcp_stream_management.go b/foreign/go/client/tcp/tcp_stream_management.go index 89a7295..152a60f 100644 --- a/foreign/go/client/tcp/tcp_stream_management.go +++ b/foreign/go/client/tcp/tcp_stream_management.go
@@ -27,12 +27,17 @@ ) func (c *IggyTcpClient) GetStreams(ctx context.Context) ([]iggcon.Stream, error) { - buffer, err := c.do(ctx, &command.GetStreams{}) + return readWholeList(ctx, c, func(ctx context.Context, query iggcon.PageQuery) (*iggcon.Page[iggcon.Stream], error) { + return c.GetStreamsPage(ctx, iggcon.NamedPageQuery{PageQuery: query}) + }) +} + +func (c *IggyTcpClient) GetStreamsPage(ctx context.Context, query iggcon.NamedPageQuery) (*iggcon.Page[iggcon.Stream], error) { + buffer, err := c.do(ctx, &command.GetStreams{Query: query}) if err != nil { return nil, err } - - return binaryserialization.DeserializeStreams(buffer) + return binaryserialization.DeserializeStreamsPage(buffer) } func (c *IggyTcpClient) GetStream(ctx context.Context, streamId iggcon.Identifier) (*iggcon.StreamDetails, error) {
diff --git a/foreign/go/client/tcp/tcp_stream_management_test.go b/foreign/go/client/tcp/tcp_stream_management_test.go index c21442b..245efad 100644 --- a/foreign/go/client/tcp/tcp_stream_management_test.go +++ b/foreign/go/client/tcp/tcp_stream_management_test.go
@@ -21,10 +21,12 @@ "context" "encoding/binary" "strings" + "sync/atomic" "testing" iggcon "github.com/apache/iggy/foreign/go/contracts" ierror "github.com/apache/iggy/foreign/go/errors" + "github.com/apache/iggy/foreign/go/internal/command" "github.com/apache/iggy/foreign/go/internal/vsr" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -96,18 +98,113 @@ assert.ErrorIs(t, err, ierror.ErrStreamIdNotFound) } -func TestGetStreams_DecodesTheRoster(t *testing.T) { +// pageBody builds a list reply: [next_len u8][next][count u32][items]. A nil +// next marks the last page. +func pageBody(next []byte, items ...[]byte) []byte { + body := append([]byte{byte(len(next))}, next...) + body = binary.LittleEndian.AppendUint32(body, uint32(len(items))) + for _, item := range items { + body = append(body, item...) + } + return body +} + +func TestGetStreams_WalksEveryPage(t *testing.T) { client, serverConn := newPipeClient(t) - body := append(streamDetailsBody(1, "orders"), streamDetailsBody(2, "billing")...) - serve(serverConn, func(_ int, _ request) []byte { - return replyFrame(vsr.OperationNonReplicated, body) + cursorBytes := []byte{1, 2, 0, 0, 0, 0, 0, 0, 0} + pages := [][]byte{ + pageBody(cursorBytes, streamDetailsBody(1, "orders"), streamDetailsBody(2, "billing")), + pageBody(nil, streamDetailsBody(3, "audit")), + } + server := serve(serverConn, func(index int, _ request) []byte { + return replyFrame(vsr.OperationNonReplicated, pages[index]) }) streams, err := client.GetStreams(context.Background()) require.NoError(t, err) - require.Len(t, streams, 2) - assert.Equal(t, "orders", streams[0].Name) - assert.Equal(t, "billing", streams[1].Name) + names := make([]string, 0, len(streams)) + for _, stream := range streams { + names = append(names, stream.Name) + } + assert.Equal(t, []string{"orders", "billing", "audit"}, names) + + query := iggcon.PageQuery{Order: iggcon.PageOrderID, Limit: iggcon.MaxPageLimit} + firstPage, err := query.AppendBinary(nil) + require.NoError(t, err) + var cursor iggcon.PageCursor + require.NoError(t, cursor.UnmarshalBinary(cursorBytes)) + query.Cursor = &cursor + secondPage, err := query.AppendBinary(nil) + require.NoError(t, err) + requests := server.recorded() + require.Len(t, requests, len(pages)) + assert.Equal(t, firstPage, requests[0].payload) + assert.Equal(t, secondPage, requests[1].payload, "the second request carries the next of the first page") +} + +func TestGetStreams_FailsWhenTheServerRepeatsTheCursor(t *testing.T) { + client, serverConn := newPipeClient(t) + cursorBytes := []byte{1, 2, 0, 0, 0, 0, 0, 0, 0} + server := serve(serverConn, func(index int, _ request) []byte { + // A last page ends the walk of a broken guard, so the test fails and + // does not hang. + if index >= 2 { + return replyFrame(vsr.OperationNonReplicated, pageBody(nil)) + } + return replyFrame(vsr.OperationNonReplicated, pageBody(cursorBytes, streamDetailsBody(1, "orders"))) + }) + + _, err := client.GetStreams(context.Background()) + assert.ErrorIs(t, err, ierror.ErrInvalidFormat) + assert.Len(t, server.recorded(), 2, "the walk stops at the page that repeats the cursor it was sent") +} + +// A walk is one call, so a caller sign-in between two pages ends it with 40. +// The test drives the walk helper, because only its page callback can sign in +// exactly between two pages. +func TestReadWholeList_ACallerSignInBetweenPagesEndsTheWalk(t *testing.T) { + cursorBytes := []byte{1, 2, 0, 0, 0, 0, 0, 0, 0} + var listed atomic.Int32 + var server *testListener + node := singleNodeHandler(t, func() string { return server.address() }) + server = listenVSR(t, nil, func(connection, index int, read request) []byte { + if read.code() != uint32(command.GetStreamsCode) { + return node(connection, index, read) + } + if listed.Add(1) == 1 { + return replyFrame(vsr.OperationNonReplicated, pageBody(cursorBytes, streamDetailsBody(1, "orders"))) + } + return replyFrame(vsr.OperationNonReplicated, pageBody(nil, streamDetailsBody(2, "billing"))) + }) + client := newDialingClient(t, server.address(), WithAutoLogin(NewUsernamePasswordCredentials("iggy", "iggy"))) + ctx, cancel := context.WithTimeout(context.Background(), managedLinkTestBudget) + defer cancel() + require.NoError(t, client.Connect(ctx)) + + streams, err := readWholeList(ctx, client, func(walk context.Context, query iggcon.PageQuery) (*iggcon.Page[iggcon.Stream], error) { + if query.Cursor != nil { + _, err := client.LoginUser(ctx, "other", "password") + require.NoError(t, err) + } + return client.GetStreamsPage(walk, iggcon.NamedPageQuery{PageQuery: query}) + }) + require.ErrorIs(t, err, ierror.ErrUnauthenticated) + assert.Nil(t, streams, "the walk returns no partial list") + assert.Equal(t, 1, requestCount(server.recorded(), command.GetStreamsCode), "no page went out under the new sign-in") + + _, err = client.GetStreamsPage(ctx, iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()}) + require.NoError(t, err, "a page call after the sign-in is a call of the new sign-in") +} + +func TestGetStreamsPage_RefusesAnInvalidQueryWithoutWriting(t *testing.T) { + client, serverConn := newPipeClient(t) + server := serve(serverConn, func(_ int, _ request) []byte { + return replyFrame(vsr.OperationNonReplicated, pageBody(nil)) + }) + + _, err := client.GetStreamsPage(context.Background(), iggcon.NamedPageQuery{}) + assert.ErrorIs(t, err, ierror.ErrInvalidCommand) + assert.Empty(t, server.recorded()) } func TestUpdateStream_RejectsAnInvalidNameWithoutWriting(t *testing.T) {
diff --git a/foreign/go/client/tcp/tcp_topic_management.go b/foreign/go/client/tcp/tcp_topic_management.go index f4b3c95..a655d83 100644 --- a/foreign/go/client/tcp/tcp_topic_management.go +++ b/foreign/go/client/tcp/tcp_topic_management.go
@@ -27,12 +27,17 @@ ) func (c *IggyTcpClient) GetTopics(ctx context.Context, streamId iggcon.Identifier) ([]iggcon.Topic, error) { - buffer, err := c.do(ctx, &command.GetTopics{StreamId: streamId}) + return readWholeList(ctx, c, func(ctx context.Context, query iggcon.PageQuery) (*iggcon.Page[iggcon.Topic], error) { + return c.GetTopicsPage(ctx, streamId, iggcon.NamedPageQuery{PageQuery: query}) + }) +} + +func (c *IggyTcpClient) GetTopicsPage(ctx context.Context, streamId iggcon.Identifier, query iggcon.NamedPageQuery) (*iggcon.Page[iggcon.Topic], error) { + buffer, err := c.do(ctx, &command.GetTopics{StreamId: streamId, Query: query}) if err != nil { return nil, err } - - return binaryserialization.DeserializeTopics(buffer) + return binaryserialization.DeserializeTopicsPage(buffer) } func (c *IggyTcpClient) GetTopic(ctx context.Context, streamId iggcon.Identifier, topicId iggcon.Identifier) (*iggcon.TopicDetails, error) {
diff --git a/foreign/go/client/tcp/tcp_topic_management_test.go b/foreign/go/client/tcp/tcp_topic_management_test.go index 43faab5..72ea02a 100644 --- a/foreign/go/client/tcp/tcp_topic_management_test.go +++ b/foreign/go/client/tcp/tcp_topic_management_test.go
@@ -19,7 +19,6 @@ import ( "context" - "encoding/binary" "strings" "testing" @@ -133,9 +132,7 @@ func TestGetTopics_DecodesTheRoster(t *testing.T) { client, serverConn := newPipeClient(t) - body := binary.LittleEndian.AppendUint32(nil, 2) - body = append(body, topicDetailsBody(t, 3)...) - body = append(body, topicDetailsBody(t, 5)...) + body := pageBody(nil, topicDetailsBody(t, 3), topicDetailsBody(t, 5)) serve(serverConn, func(_ int, _ request) []byte { return replyFrame(vsr.OperationNonReplicated, body) })
diff --git a/foreign/go/client/tcp/tcp_user_management.go b/foreign/go/client/tcp/tcp_user_management.go index 0afcc09..bdaec8b 100644 --- a/foreign/go/client/tcp/tcp_user_management.go +++ b/foreign/go/client/tcp/tcp_user_management.go
@@ -39,12 +39,17 @@ } func (c *IggyTcpClient) GetUsers(ctx context.Context) ([]iggcon.UserInfo, error) { - buffer, err := c.do(ctx, &command.GetUsers{}) + return readWholeList(ctx, c, func(ctx context.Context, query iggcon.PageQuery) (*iggcon.Page[iggcon.UserInfo], error) { + return c.GetUsersPage(ctx, iggcon.NamedPageQuery{PageQuery: query}) + }) +} + +func (c *IggyTcpClient) GetUsersPage(ctx context.Context, query iggcon.NamedPageQuery) (*iggcon.Page[iggcon.UserInfo], error) { + buffer, err := c.do(ctx, &command.GetUsers{Query: query}) if err != nil { return nil, err } - - return binaryserialization.DeserializeUsers(buffer) + return binaryserialization.DeserializeUsersPage(buffer) } func (c *IggyTcpClient) CreateUser(
diff --git a/foreign/go/contracts/client.go b/foreign/go/contracts/client.go index 14e5567..f5bd9fe 100644 --- a/foreign/go/contracts/client.go +++ b/foreign/go/contracts/client.go
@@ -52,10 +52,21 @@ // Authentication is required, and the permission to read the streams. GetStream(ctx context.Context, streamId Identifier) (*StreamDetails, error) - // GetStreams get the info about all the streams. + // GetStreams get the info about all the streams. It reads every page of + // the list, so the result is not one consistent read. Every page keeps the + // sign-in and the deadline that the call started with. If the Next of a + // page is the cursor that its request sent, the call fails with + // ierror.ErrInvalidFormat. // Authentication is required, and the permission to read the streams. GetStreams(ctx context.Context) ([]Stream, error) + // GetStreamsPage get one page of the streams. Send the Next of the page + // as the Cursor of the next query, with the same other fields, until Next + // is nil. A query that breaks the page rules is refused with + // ierror.ErrInvalidCommand before anything is sent. + // Authentication is required, and the permission to read the streams. + GetStreamsPage(ctx context.Context, query NamedPageQuery) (*Page[Stream], error) + // CreateStream create a new stream. Nil options select the defaults. // Authentication is required, and the permission to manage the streams. // @@ -78,10 +89,22 @@ // Authentication is required, and the permission to read the topics. GetTopic(ctx context.Context, streamId, topicId Identifier) (*TopicDetails, error) - // GetTopics get the info about all the topics. + // GetTopics get the info about all the topics. It reads every page of the + // list, so the result is not one consistent read. Every page keeps the + // sign-in and the deadline that the call started with. If the Next of a + // page is the cursor that its request sent, the call fails with + // ierror.ErrInvalidFormat. // Authentication is required, and the permission to read the topics. GetTopics(ctx context.Context, streamId Identifier) ([]Topic, error) + // GetTopicsPage get one page of the topics of a stream, as GetStreamsPage + // does for the streams. If the stream does not exist, a query without a + // Cursor gets an empty last page. A query with a Cursor fails with + // ierror.ErrStreamIdNotFound, because the stream was deleted during the + // walk. + // Authentication is required, and the permission to read the topics. + GetTopicsPage(ctx context.Context, streamId Identifier, query NamedPageQuery) (*Page[Topic], error) + // DescribeOptions get the option catalog for a resource scope: every key, // with its kind, default and bounds, and whether an update may set or // reset it. @@ -224,9 +247,17 @@ ) (*ConsumerOffsetInfo, error) // GetConsumerGroups get the info about all the consumer groups for the given stream and topic by unique IDs or names. + // It reads every page of the list, so the result is not one consistent read. + // Every page keeps the sign-in and the deadline that the call started with. + // If the Next of a page is the cursor that its request sent, the call fails with ierror.ErrInvalidFormat. // Authentication is required, and the permission to read the streams or topics. GetConsumerGroups(ctx context.Context, streamId Identifier, topicId Identifier) ([]ConsumerGroup, error) + // GetConsumerGroupsPage get one page of the consumer groups of a topic, + // as GetStreamsPage does for the streams. + // Authentication is required, and the permission to read the streams or topics. + GetConsumerGroupsPage(ctx context.Context, streamId, topicId Identifier, query NamedPageQuery) (*Page[ConsumerGroup], error) + // DeleteConsumerOffset delete the consumer offset for a specific consumer or consumer group for the given stream and topic by unique IDs or names. // Authentication is required, and the permission to poll the messages. // @@ -306,6 +337,11 @@ groupId Identifier, ) (*ConsumerGroupAssignment, error) + // GetPartitionsPage get one page of the partitions of a topic, as + // GetStreamsPage does for the streams. + // Authentication is required, and the permission to read the topics. + GetPartitionsPage(ctx context.Context, streamId, topicId Identifier, query PageQuery) (*Page[PartitionContract], error) + // CreatePartitions create new N partitions for a topic by unique ID or name. // For example, given a topic with 3 partitions, if you create 2 partitions, the topic will have 5 partitions (from 0 to 4). // Authentication is required, and the permission to manage the partitions. @@ -340,10 +376,19 @@ // Authentication is required, and the permission to read the users, unless the provided user ID is the same as the authenticated user. GetUser(ctx context.Context, identifier Identifier) (*UserInfoDetails, error) - // GetUsers get the info about all the users. + // GetUsers get the info about all the users. It reads every page of the + // list, so the result is not one consistent read. Every page keeps the + // sign-in and the deadline that the call started with. If the Next of a + // page is the cursor that its request sent, the call fails with + // ierror.ErrInvalidFormat. // Authentication is required, and the permission to read the users. GetUsers(ctx context.Context) ([]UserInfo, error) + // GetUsersPage get one page of the users, as GetStreamsPage does for the + // streams. + // Authentication is required, and the permission to read the users. + GetUsersPage(ctx context.Context, query NamedPageQuery) (*Page[UserInfo], error) + // CreateUser create a new user. Nil options select the defaults. // Authentication is required, and the permission to manage the users. CreateUser(
diff --git a/foreign/go/contracts/list_pages_test.go b/foreign/go/contracts/list_pages_test.go new file mode 100644 index 0000000..4e6b2dd --- /dev/null +++ b/foreign/go/contracts/list_pages_test.go
@@ -0,0 +1,428 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package iggcon_test + +import ( + "encoding/binary" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "testing" + + binaryserialization "github.com/apache/iggy/foreign/go/binary_serialization" + iggcon "github.com/apache/iggy/foreign/go/contracts" + ierror "github.com/apache/iggy/foreign/go/errors" + "github.com/apache/iggy/foreign/go/internal/command" + "github.com/apache/iggy/foreign/go/internal/vsr" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var listPageOrders = map[string]iggcon.PageOrder{ + "id": iggcon.PageOrderID, + "created": iggcon.PageOrderCreated, +} + +type listPagesFixture struct { + SchemaVersion int `json:"schema_version"` + Constants listPagesConstants `json:"constants"` + Cursors []listPageCursor `json:"cursors"` + OpaqueCursors []listPageCursor `json:"opaque_cursors"` + Requests []listPageRequest `json:"requests"` + Responses []listPageResponse `json:"responses"` + OpaqueResponses []listPageResponse `json:"opaque_responses"` + Refused listPagesRefused `json:"refused"` +} + +type listPagesConstants struct { + Codes map[string]uint32 `json:"codes"` + Orders map[string]uint8 `json:"orders"` + CursorPrefix string `json:"cursor_prefix"` + MaxCursorBytes int `json:"max_cursor_bytes"` + DefaultLimit uint32 `json:"default_limit"` + MaxLimit uint32 `json:"max_limit"` + MaxNameBytes int `json:"max_name_bytes"` + Errors map[string]uint32 `json:"errors"` +} + +type listPageCursor struct { + Case string `json:"case"` + Text string `json:"text"` + Hex string `json:"hex"` +} + +type listPageIdentifier struct { + Kind string `json:"kind"` + Value json.RawMessage `json:"value"` +} + +type listPageInput struct { + StreamID *listPageIdentifier `json:"stream_id"` + TopicID *listPageIdentifier `json:"topic_id"` + Order string `json:"order"` + Descending bool `json:"descending"` + Limit uint32 `json:"limit"` + Cursor *string `json:"cursor"` + Name *string `json:"name"` +} + +type listPageRequest struct { + Case string `json:"case"` + Command string `json:"command"` + Input listPageInput `json:"input"` + RequestHex string `json:"request_hex"` +} + +type listPageItem struct { + ID uint32 `json:"id"` + Name *string `json:"name"` +} + +type listPageResponse struct { + Case string `json:"case"` + Command string `json:"command"` + ResponseHex string `json:"response_hex"` + Next *string `json:"next"` + Items []listPageItem `json:"items"` +} + +type listPagesRefused struct { + Cursors []struct { + Case string `json:"case"` + Text string `json:"text"` + } `json:"cursors"` + Queries []struct { + Case string `json:"case"` + Input listPageInput `json:"input"` + } `json:"queries"` + Responses []struct { + Case string `json:"case"` + Command string `json:"command"` + ResponseHex string `json:"response_hex"` + } `json:"responses"` +} + +// listPageView is what a reply vector pins: the next text and the id and +// name of each item. +type listPageView struct { + Next *string + Items []listPageItem +} + +func TestListPages_SharedVectors(t *testing.T) { + fixture := loadListPagesFixture(t) + + t.Run("given_shared_vectors_when_encoding_and_decoding_should_match_server_contract", func(t *testing.T) { + t.Run("constants", func(t *testing.T) { checkListPagesConstants(t, fixture.Constants) }) + + // The cursor check reads only the text, so the opaque cursors that + // the server refuses pass it too. + for _, vector := range append(fixture.Cursors, fixture.OpaqueCursors...) { + t.Run("cursors/"+vector.Case, func(t *testing.T) { + parsed, err := iggcon.ParsePageCursor(vector.Text) + require.NoError(t, err) + assert.Equal(t, vector.Text, parsed.String()) + var fromBytes iggcon.PageCursor + require.NoError(t, fromBytes.UnmarshalBinary(decodeHex(t, vector.Hex))) + assert.Equal(t, parsed, fromBytes) + }) + } + // The Go SDK has no HTTP transport, so http_query has no encoder to + // check. + for _, vector := range fixture.Requests { + t.Run("requests/"+vector.Case, func(t *testing.T) { + body, err := encodeListPageRequest(t, vector.Command, vector.Input) + require.NoError(t, err) + assert.Equal(t, vector.RequestHex, hex.EncodeToString(body)) + }) + } + for _, vector := range append(fixture.Responses, fixture.OpaqueResponses...) { + t.Run("responses/"+vector.Case, func(t *testing.T) { + view, err := decodeListPage(t, vector.Command, decodeHex(t, vector.ResponseHex)) + require.NoError(t, err) + assert.Equal(t, listPageView{Next: vector.Next, Items: vector.Items}, view) + }) + } + }) + + t.Run("given_an_opaque_next_when_sending_it_back_should_keep_its_bytes", func(t *testing.T) { + for _, vector := range fixture.OpaqueResponses { + t.Run(vector.Case, func(t *testing.T) { + reply := decodeHex(t, vector.ResponseHex) + page, err := binaryserialization.DeserializeStreamsPage(reply) + require.NoError(t, err) + require.NotNil(t, page.Next) + + query := iggcon.NamedPageQuery{PageQuery: iggcon.PageQuery{Limit: iggcon.DefaultPageLimit, Cursor: page.Next}} + body, err := (&command.GetStreams{Query: query}).MarshalBinary() + require.NoError(t, err) + // [order][descending][limit:u32][cursor_len][cursor][name_len], + // with the next of the reply, [next_len][next], as the cursor. + next := reply[:1+int(reply[0])] + want := append([]byte{byte(iggcon.PageOrderID), 0}, binary.LittleEndian.AppendUint32(nil, iggcon.DefaultPageLimit)...) + want = append(want, next...) + assert.Equal(t, append(want, 0), body) + }) + } + }) + + t.Run("given_refused_vectors_when_parsing_validating_or_decoding_should_refuse", func(t *testing.T) { + for _, vector := range fixture.Refused.Cursors { + t.Run("cursors/"+vector.Case, func(t *testing.T) { + _, err := iggcon.ParsePageCursor(vector.Text) + assert.ErrorIs(t, err, ierror.ErrInvalidCommand) + }) + } + parentID, err := iggcon.NewIdentifier(uint32(1)) + require.NoError(t, err) + for _, vector := range fixture.Refused.Queries { + t.Run("queries/"+vector.Case, func(t *testing.T) { + named := namedListPageQuery(t, vector.Input) + assert.ErrorIs(t, named.Validate(), ierror.ErrInvalidCommand) + body, err := (&command.GetStreams{Query: named}).MarshalBinary() + assert.ErrorIs(t, err, ierror.ErrInvalidCommand) + assert.Empty(t, body) + if vector.Input.Name == nil { + query := listPageQuery(t, vector.Input) + assert.ErrorIs(t, query.Validate(), ierror.ErrInvalidCommand) + body, err = (&command.GetPartitions{StreamId: parentID, TopicId: parentID, Query: query}).MarshalBinary() + assert.ErrorIs(t, err, ierror.ErrInvalidCommand) + assert.Empty(t, body) + } + }) + } + for _, vector := range fixture.Refused.Responses { + t.Run("responses/"+vector.Case, func(t *testing.T) { + _, err := decodeListPage(t, vector.Command, decodeHex(t, vector.ResponseHex)) + assert.ErrorIs(t, err, ierror.ErrInvalidFormat) + }) + } + }) +} + +func TestPageQuery_RefusesValuesTheFixtureCannotHold(t *testing.T) { + t.Run("given_an_unknown_order_an_empty_cursor_or_a_name_that_is_not_utf8_when_validating_should_refuse", func(t *testing.T) { + notUTF8 := string([]byte{0xff}) + refused := map[string]error{ + "unknown_order": iggcon.PageQuery{Order: iggcon.PageOrderCreated + 1, Limit: 1}.Validate(), + "cursor_of_no_bytes": iggcon.PageQuery{Limit: 1, Cursor: &iggcon.PageCursor{}}.Validate(), + "name_not_utf8": iggcon.NamedPageQuery{PageQuery: iggcon.PageQuery{Limit: 1}, Name: ¬UTF8}.Validate(), + } + for name, err := range refused { + assert.ErrorIs(t, err, ierror.ErrInvalidCommand, name) + } + }) +} + +func TestPageCursor_JSON(t *testing.T) { + fixture := loadListPagesFixture(t) + text := fixture.Cursors[0].Text + + t.Run("given_a_page_and_a_query_with_a_cursor_when_round_tripping_through_json_should_keep_its_text_form", func(t *testing.T) { + cursor, err := iggcon.ParsePageCursor(text) + require.NoError(t, err) + page := iggcon.Page[uint32]{Items: []uint32{7}, Next: &cursor} + query := iggcon.PageQuery{Limit: 1, Cursor: &cursor} + + encodedPage, err := json.Marshal(page) + require.NoError(t, err) + assert.Contains(t, string(encodedPage), `"Next":"`+text+`"`) + encodedQuery, err := json.Marshal(query) + require.NoError(t, err) + assert.Contains(t, string(encodedQuery), `"Cursor":"`+text+`"`) + + var decodedPage iggcon.Page[uint32] + require.NoError(t, json.Unmarshal(encodedPage, &decodedPage)) + assert.Equal(t, page, decodedPage) + var decodedQuery iggcon.PageQuery + require.NoError(t, json.Unmarshal(encodedQuery, &decodedQuery)) + assert.Equal(t, query, decodedQuery) + }) + + t.Run("given_a_last_page_when_round_tripping_through_json_should_keep_no_next", func(t *testing.T) { + encoded, err := json.Marshal(iggcon.Page[uint32]{Items: []uint32{}}) + require.NoError(t, err) + assert.Contains(t, string(encoded), `"Next":null`) + var decoded iggcon.Page[uint32] + require.NoError(t, json.Unmarshal(encoded, &decoded)) + assert.Nil(t, decoded.Next) + }) + + t.Run("given_non_canonical_cursor_text_when_unmarshaling_json_should_refuse", func(t *testing.T) { + var cursor iggcon.PageCursor + err := json.Unmarshal([]byte(`"`+text+`="`), &cursor) + assert.ErrorIs(t, err, ierror.ErrInvalidCommand) + }) +} + +func loadListPagesFixture(t *testing.T) listPagesFixture { + t.Helper() + content, err := os.ReadFile(filepath.Join("testdata", "list_pages.json")) + require.NoError(t, err) + var fixture listPagesFixture + require.NoError(t, json.Unmarshal(content, &fixture)) + require.Equal(t, 1, fixture.SchemaVersion) + return fixture +} + +func checkListPagesConstants(t *testing.T, constants listPagesConstants) { + assert.Equal(t, map[string]uint32{ + "get_users": uint32(command.GetUsersCode), + "get_streams": uint32(command.GetStreamsCode), + "get_topics": uint32(command.GetTopicsCode), + "get_partitions": uint32(command.GetPartitionsCode), + "get_consumer_groups": uint32(command.GetGroupsCode), + }, constants.Codes) + for name, code := range constants.Codes { + assert.Equal(t, vsr.OperationNonReplicated, vsr.OperationForCode(code), name) + } + orders := make(map[string]uint8, len(listPageOrders)) + for name, order := range listPageOrders { + orders[name] = uint8(order) + } + assert.Equal(t, orders, constants.Orders) + assert.Equal(t, iggcon.PageCursorPrefix, constants.CursorPrefix) + assert.Equal(t, iggcon.MaxPageCursorSize, constants.MaxCursorBytes) + assert.Equal(t, iggcon.DefaultPageLimit, constants.DefaultLimit) + assert.Equal(t, iggcon.NewPageQuery().Limit, constants.DefaultLimit) + assert.Equal(t, iggcon.MaxPageLimit, constants.MaxLimit) + assert.Equal(t, iggcon.MaxPageNameSize, constants.MaxNameBytes) + assert.Equal(t, map[string]uint32{ + "invalid_command": uint32(ierror.InvalidCommandCode), + "reply_too_large": uint32(ierror.ReplyTooLargeCode), + }, constants.Errors) +} + +func listPageQuery(t *testing.T, input listPageInput) iggcon.PageQuery { + t.Helper() + order, known := listPageOrders[input.Order] + require.True(t, known, "order %q", input.Order) + query := iggcon.PageQuery{Order: order, Descending: input.Descending, Limit: input.Limit} + if input.Cursor != nil { + cursor, err := iggcon.ParsePageCursor(*input.Cursor) + require.NoError(t, err) + query.Cursor = &cursor + } + return query +} + +func namedListPageQuery(t *testing.T, input listPageInput) iggcon.NamedPageQuery { + t.Helper() + return iggcon.NamedPageQuery{PageQuery: listPageQuery(t, input), Name: input.Name} +} + +func listPageParent(t *testing.T, id *listPageIdentifier) iggcon.Identifier { + t.Helper() + require.NotNil(t, id, "the command needs this parent id") + var identifier iggcon.Identifier + var err error + switch id.Kind { + case "numeric": + var value uint32 + require.NoError(t, json.Unmarshal(id.Value, &value)) + identifier, err = iggcon.NewIdentifier(value) + case "named": + var value string + require.NoError(t, json.Unmarshal(id.Value, &value)) + identifier, err = iggcon.NewIdentifier(value) + default: + require.FailNow(t, "unknown identifier kind", id.Kind) + } + require.NoError(t, err) + return identifier +} + +func encodeListPageRequest(t *testing.T, name string, input listPageInput) ([]byte, error) { + t.Helper() + switch name { + case "get_users": + return (&command.GetUsers{Query: namedListPageQuery(t, input)}).MarshalBinary() + case "get_streams": + return (&command.GetStreams{Query: namedListPageQuery(t, input)}).MarshalBinary() + case "get_topics": + return (&command.GetTopics{StreamId: listPageParent(t, input.StreamID), Query: namedListPageQuery(t, input)}).MarshalBinary() + case "get_partitions": + require.Nil(t, input.Name, "a partitions query has no name") + return (&command.GetPartitions{ + StreamId: listPageParent(t, input.StreamID), + TopicId: listPageParent(t, input.TopicID), + Query: listPageQuery(t, input), + }).MarshalBinary() + case "get_consumer_groups": + return (&command.GetConsumerGroups{ + StreamId: listPageParent(t, input.StreamID), + TopicId: listPageParent(t, input.TopicID), + Query: namedListPageQuery(t, input), + }).MarshalBinary() + } + require.FailNow(t, "unknown list command", name) + return nil, nil +} + +func decodeListPage(t *testing.T, name string, payload []byte) (listPageView, error) { + t.Helper() + switch name { + case "get_users": + page, err := binaryserialization.DeserializeUsersPage(payload) + return viewListPage(page, err, func(user iggcon.UserInfo) listPageItem { + return namedListPageItem(user.Id, user.Username) + }) + case "get_streams": + page, err := binaryserialization.DeserializeStreamsPage(payload) + return viewListPage(page, err, func(stream iggcon.Stream) listPageItem { + return namedListPageItem(stream.Id, stream.Name) + }) + case "get_topics": + page, err := binaryserialization.DeserializeTopicsPage(payload) + return viewListPage(page, err, func(topic iggcon.Topic) listPageItem { + return namedListPageItem(topic.Id, topic.Name) + }) + case "get_partitions": + page, err := binaryserialization.DeserializePartitionsPage(payload) + return viewListPage(page, err, func(partition iggcon.PartitionContract) listPageItem { + return listPageItem{ID: partition.Id} + }) + case "get_consumer_groups": + page, err := binaryserialization.DeserializeConsumerGroupsPage(payload) + return viewListPage(page, err, func(group iggcon.ConsumerGroup) listPageItem { + return namedListPageItem(group.Id, group.Name) + }) + } + require.FailNow(t, "unknown list command", name) + return listPageView{}, nil +} + +func viewListPage[T any](page *iggcon.Page[T], err error, item func(T) listPageItem) (listPageView, error) { + if err != nil { + return listPageView{}, err + } + view := listPageView{Items: make([]listPageItem, 0, len(page.Items))} + if page.Next != nil { + next := page.Next.String() + view.Next = &next + } + for _, entry := range page.Items { + view.Items = append(view.Items, item(entry)) + } + return view, nil +} + +func namedListPageItem(id uint32, name string) listPageItem { + return listPageItem{ID: id, Name: &name} +}
diff --git a/foreign/go/contracts/page.go b/foreign/go/contracts/page.go new file mode 100644 index 0000000..b46e873 --- /dev/null +++ b/foreign/go/contracts/page.go
@@ -0,0 +1,211 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package iggcon + +import ( + "encoding/base64" + "encoding/binary" + "fmt" + "unicode/utf8" + + ierror "github.com/apache/iggy/foreign/go/errors" +) + +const ( + // PageCursorPrefix starts the text form of a page cursor. + PageCursorPrefix = "pg1_" + // DefaultPageLimit is the page size NewPageQuery sets. + DefaultPageLimit uint32 = 100 + // MaxPageLimit is the most items one page returns. + MaxPageLimit uint32 = 1000 + // MaxPageCursorSize is the most bytes of a cursor: its length on the + // wire is one byte. + MaxPageCursorSize = 255 + // MaxPageNameSize is the most bytes of a name filter. + MaxPageNameSize = 255 +) + +const maxPageCursorTextLength = len(PageCursorPrefix) + (MaxPageCursorSize*4+2)/3 + +// PageOrder is the order of a list page. +type PageOrder uint8 + +const ( + // PageOrderID walks the numeric ids. + PageOrderID PageOrder = 0 + // PageOrderCreated walks the creation order. Entities created at the same + // time keep the order of their ids. Partitions and consumer groups walk by + // id in this order too, because their ids follow creation. + PageOrderCreated PageOrder = 1 +) + +// PageCursor is the position after which the next page of a list starts. +// Send it back as you got it, with the query that returned it: it holds no +// order, direction, filter or parent. Only the server reads its bytes. +// +// Its text form is PageCursorPrefix followed by unpadded Base64url of its +// bytes. +type PageCursor struct { + // payload is a string, so no copy of the cursor can change its bytes. + payload string +} + +// PageQuery is one page request of a list command. NewPageQuery fills the +// default limit: a zero Limit is refused. +type PageQuery struct { + Order PageOrder + Descending bool + // Limit caps the items of the page, 1 to MaxPageLimit. + Limit uint32 + // Cursor is the Next of the previous page, nil for the first page. + Cursor *PageCursor +} + +// NamedPageQuery is a PageQuery with a name filter, for the lists whose +// entries have a name: streams, topics, consumer groups and users. +type NamedPageQuery struct { + PageQuery + // Name keeps only the entries whose name holds this text, case-sensitive. + // Nil keeps every entry. + Name *string +} + +// Page is one page of a list. A page can be short or empty and still have a +// Next. +type Page[T any] struct { + Items []T + // Next is the cursor of the next page, nil on the last page. + Next *PageCursor +} + +// NewPageQuery builds the query of a first page in ascending id order with +// the default limit. +func NewPageQuery() PageQuery { + return PageQuery{Order: PageOrderID, Limit: DefaultPageLimit} +} + +// ParsePageCursor reads the text form of a cursor. Anything but the prefix +// and canonical unpadded Base64url of 1 to MaxPageCursorSize bytes is +// ierror.ErrInvalidCommand. The bytes themselves are not checked. +func ParsePageCursor(text string) (PageCursor, error) { + if len(text) > maxPageCursorTextLength { + return PageCursor{}, ierror.ErrInvalidCommand + } + payload, err := decodeCanonicalBase64(text, PageCursorPrefix) + if err != nil { + return PageCursor{}, err + } + var cursor PageCursor + if err := cursor.UnmarshalBinary(payload); err != nil { + return PageCursor{}, ierror.ErrInvalidCommand + } + return cursor, nil +} + +func (c PageCursor) String() string { + return PageCursorPrefix + base64.RawURLEncoding.EncodeToString([]byte(c.payload)) +} + +// MarshalText renders the cursor's text form, so text encoders such as +// encoding/json keep the position. +func (c PageCursor) MarshalText() ([]byte, error) { + return []byte(c.String()), nil +} + +// UnmarshalText reads the text form with the checks of ParsePageCursor. +func (c *PageCursor) UnmarshalText(text []byte) error { + cursor, err := ParsePageCursor(string(text)) + if err != nil { + return err + } + *c = cursor + return nil +} + +// UnmarshalBinary keeps a copy of 1 to MaxPageCursorSize cursor bytes. +func (c *PageCursor) UnmarshalBinary(data []byte) error { + if len(data) == 0 || len(data) > MaxPageCursorSize { + return fmt.Errorf("%w: page cursor of %d bytes", ierror.ErrInvalidFormat, len(data)) + } + c.payload = string(data) + return nil +} + +// Validate applies the page rules the server enforces, so a query that breaks +// one is refused with ierror.ErrInvalidCommand before anything is sent: a +// limit outside 1 to MaxPageLimit, an unknown order and a cursor without +// bytes. +func (q PageQuery) Validate() error { + if q.Limit < 1 || q.Limit > MaxPageLimit || q.Order > PageOrderCreated { + return ierror.ErrInvalidCommand + } + if q.Cursor != nil && q.Cursor.payload == "" { + return ierror.ErrInvalidCommand + } + return nil +} + +// Validate applies the rules of PageQuery.Validate. It also refuses a name +// that is empty, longer than MaxPageNameSize bytes or not UTF-8, with +// ierror.ErrInvalidCommand. +func (q NamedPageQuery) Validate() error { + if err := q.PageQuery.Validate(); err != nil { + return err + } + if q.Name != nil && (*q.Name == "" || len(*q.Name) > MaxPageNameSize || !utf8.ValidString(*q.Name)) { + return ierror.ErrInvalidCommand + } + return nil +} + +// AppendBinary validates the query, then appends the page block that ends +// every list request: [order:u8][descending:u8][limit:u32][cursor_len:u8] +// [cursor][name_len:u8][name]. A length of 0 means no cursor or no name. A +// PageQuery has no name, so its name length is always 0. +func (q PageQuery) AppendBinary(b []byte) ([]byte, error) { + if err := q.Validate(); err != nil { + return nil, err + } + return q.appendBlock(b, ""), nil +} + +// AppendBinary validates the query, then appends the page block of +// PageQuery.AppendBinary with the name. +func (q NamedPageQuery) AppendBinary(b []byte) ([]byte, error) { + if err := q.Validate(); err != nil { + return nil, err + } + var name string + if q.Name != nil { + name = *q.Name + } + return q.appendBlock(b, name), nil +} + +func (q PageQuery) appendBlock(b []byte, name string) []byte { + var cursor string + if q.Cursor != nil { + cursor = q.Cursor.payload + } + b = append(b, byte(q.Order), boolToByte(q.Descending)) + b = binary.LittleEndian.AppendUint32(b, q.Limit) + b = append(b, byte(len(cursor))) + b = append(b, cursor...) + b = append(b, byte(len(name))) + return append(b, name...) +}
diff --git a/foreign/go/contracts/resource_options_test.go b/foreign/go/contracts/resource_options_test.go index 0bac4a0..53d9093 100644 --- a/foreign/go/contracts/resource_options_test.go +++ b/foreign/go/contracts/resource_options_test.go
@@ -679,10 +679,11 @@ response := decodeHex(t, vector.ResponseHex) details, err := binaryserialization.DeserializeStream(response) require.NoError(t, err) - streams, err := binaryserialization.DeserializeStreams(response) + // A last page of this one stream: no next cursor, then a count of 1. + page, err := binaryserialization.DeserializeStreamsPage(append([]byte{0, 1, 0, 0, 0}, response...)) require.NoError(t, err) - require.Len(t, streams, 1) - assert.Equal(t, details.Stream, streams[0]) + require.Len(t, page.Items, 1) + assert.Equal(t, details.Stream, page.Items[0]) stream := details.Stream expected := vector.Expected
diff --git a/foreign/go/contracts/testdata/list_pages.json b/foreign/go/contracts/testdata/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/go/contracts/testdata/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/go/contracts/testdata/resource_options.json b/foreign/go/contracts/testdata/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/go/contracts/testdata/resource_options.json +++ b/foreign/go/contracts/testdata/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/go/contracts/version.go b/foreign/go/contracts/version.go index f71c7e7..93c2c06 100644 --- a/foreign/go/contracts/version.go +++ b/foreign/go/contracts/version.go
@@ -17,4 +17,4 @@ package iggcon -const Version = "0.10.0" +const Version = "0.10.1-edge.1"
diff --git a/foreign/go/errors/errors.yaml b/foreign/go/errors/errors.yaml index 3d0b343..0dc4801 100644 --- a/foreign/go/errors/errors.yaml +++ b/foreign/go/errors/errors.yaml
@@ -359,6 +359,10 @@ code: 96 format: "tiered data cannot be read from the object store; a retry does not help" fields: [] +- name: ReplyTooLarge + code: 97 + format: "the reply is larger than the reply size limit" + fields: [] - name: ClientNotFound code: 100 format: "client with id: %d was not found."
diff --git a/foreign/go/errors/errors_gen.go b/foreign/go/errors/errors_gen.go index 228939e..ceea001 100644 --- a/foreign/go/errors/errors_gen.go +++ b/foreign/go/errors/errors_gen.go
@@ -786,6 +786,15 @@ return ok } +type ReplyTooLarge struct{} + +func (e ReplyTooLarge) Error() string { return "the reply is larger than the reply size limit" } +func (e ReplyTooLarge) Code() Code { return 97 } +func (e ReplyTooLarge) Is(target error) bool { + _, ok := target.(ReplyTooLarge) + return ok +} + type ClientNotFound struct { ID uint32 } @@ -2995,6 +3004,7 @@ ErrNotPrimary = NotPrimary{} ErrDeferredPollCapacityExceeded = DeferredPollCapacityExceeded{} ErrTieredReadFailed = TieredReadFailed{} + ErrReplyTooLarge = ReplyTooLarge{} ErrClientNotFound = ClientNotFound{} ErrInvalidClientId = InvalidClientId{} ErrConnectionClosed = ConnectionClosed{} @@ -3262,6 +3272,7 @@ NotPrimaryCode Code = 89 DeferredPollCapacityExceededCode Code = 90 TieredReadFailedCode Code = 96 + ReplyTooLargeCode Code = 97 ClientNotFoundCode Code = 100 InvalidClientIdCode Code = 101 ConnectionClosedCode Code = 206 @@ -3602,6 +3613,8 @@ return "DeferredPollCapacityExceeded" case TieredReadFailedCode: return "TieredReadFailed" + case ReplyTooLargeCode: + return "ReplyTooLarge" case ClientNotFoundCode: return "ClientNotFound" case InvalidClientIdCode: @@ -4133,6 +4146,8 @@ return ErrDeferredPollCapacityExceeded case TieredReadFailedCode: return ErrTieredReadFailed + case ReplyTooLargeCode: + return ErrReplyTooLarge case ClientNotFoundCode: return ErrClientNotFound case InvalidClientIdCode:
diff --git a/foreign/go/errors/errors_test.go b/foreign/go/errors/errors_test.go index 9cfd246..f1dffde 100644 --- a/foreign/go/errors/errors_test.go +++ b/foreign/go/errors/errors_test.go
@@ -148,6 +148,22 @@ } } +func TestIggyError_ReplyTooLarge(t *testing.T) { + err := ReplyTooLarge{} + if err.Code() != Code(97) || ReplyTooLargeCode != Code(97) { + t.Errorf("Code() = %v, ReplyTooLargeCode = %v, want 97", err.Code(), ReplyTooLargeCode) + } + if err.Error() != "the reply is larger than the reply size limit" { + t.Errorf("Error() = %q", err.Error()) + } + if ReplyTooLargeCode.String() != "ReplyTooLarge" { + t.Errorf("String() = %q", ReplyTooLargeCode.String()) + } + if resolved := FromCode(Code(97)); !errors.Is(resolved, ErrReplyTooLarge) { + t.Errorf("FromCode(97) = %v, want ErrReplyTooLarge", resolved) + } +} + func TestFromCode_FallsBackToTheGenericError(t *testing.T) { if resolved := FromCode(Code(0xFFFFFF)); !errors.Is(resolved, ErrError) { t.Errorf("FromCode(unknown) = %v, want ErrError", resolved)
diff --git a/foreign/go/internal/command/code.go b/foreign/go/internal/command/code.go index e4d2ca0..3572168 100644 --- a/foreign/go/internal/command/code.go +++ b/foreign/go/internal/command/code.go
@@ -65,6 +65,7 @@ DeleteTopicCode Code = 303 CreatePartitionsCode Code = 402 DeletePartitionsCode Code = 403 + GetPartitionsCode Code = 404 DeleteSegmentsCode Code = 503 GetGroupCode Code = 600 GetGroupsCode Code = 601
diff --git a/foreign/go/internal/command/consumer_group.go b/foreign/go/internal/command/consumer_group.go index 593c963..d67f750 100644 --- a/foreign/go/internal/command/consumer_group.go +++ b/foreign/go/internal/command/consumer_group.go
@@ -64,9 +64,11 @@ return iggcon.MarshalIdentifiers(g.StreamId, g.TopicId, g.GroupId) } +// GetConsumerGroups asks for one page of the consumer groups of a topic. type GetConsumerGroups struct { StreamId iggcon.Identifier TopicId iggcon.Identifier + Query iggcon.NamedPageQuery } func (g *GetConsumerGroups) Code() Code { @@ -74,7 +76,11 @@ } func (g *GetConsumerGroups) MarshalBinary() ([]byte, error) { - return iggcon.MarshalIdentifiers(g.StreamId, g.TopicId) + identifiers, err := iggcon.MarshalIdentifiers(g.StreamId, g.TopicId) + if err != nil { + return nil, err + } + return g.Query.AppendBinary(identifiers) } type JoinConsumerGroup struct {
diff --git a/foreign/go/internal/command/consumer_group_test.go b/foreign/go/internal/command/consumer_group_test.go index 37f9f90..3bb17d9 100644 --- a/foreign/go/internal/command/consumer_group_test.go +++ b/foreign/go/internal/command/consumer_group_test.go
@@ -79,15 +79,15 @@ }, { name: "get groups with numeric identifiers", - request: &GetConsumerGroups{StreamId: streamID, TopicId: topicID}, + request: &GetConsumerGroups{StreamId: streamID, TopicId: topicID, Query: iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()}}, code: 601, - want: []byte{1, 4, 4, 3, 2, 1, 1, 4, 8, 7, 6, 5}, + want: []byte{1, 4, 4, 3, 2, 1, 1, 4, 8, 7, 6, 5, 0, 0, 100, 0, 0, 0, 0, 0}, }, { name: "get groups with named identifiers", - request: &GetConsumerGroups{StreamId: namedStreamID, TopicId: namedTopicID}, + request: &GetConsumerGroups{StreamId: namedStreamID, TopicId: namedTopicID, Query: iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()}}, code: 601, - want: []byte{2, 1, 's', 2, 1, 't'}, + want: []byte{2, 1, 's', 2, 1, 't', 0, 0, 100, 0, 0, 0, 0, 0}, }, { name: "join group",
diff --git a/foreign/go/internal/command/partition.go b/foreign/go/internal/command/partition.go index e7b2757..2d5ae95 100644 --- a/foreign/go/internal/command/partition.go +++ b/foreign/go/internal/command/partition.go
@@ -23,6 +23,25 @@ iggcon "github.com/apache/iggy/foreign/go/contracts" ) +// GetPartitions asks for one page of the partitions of a topic. +type GetPartitions struct { + StreamId iggcon.Identifier + TopicId iggcon.Identifier + Query iggcon.PageQuery +} + +func (g *GetPartitions) Code() Code { + return GetPartitionsCode +} + +func (g *GetPartitions) MarshalBinary() ([]byte, error) { + identifiers, err := iggcon.MarshalIdentifiers(g.StreamId, g.TopicId) + if err != nil { + return nil, err + } + return g.Query.AppendBinary(identifiers) +} + type CreatePartitions struct { StreamId iggcon.Identifier `json:"streamId"` TopicId iggcon.Identifier `json:"topicId"`
diff --git a/foreign/go/internal/command/stream.go b/foreign/go/internal/command/stream.go index 5a573a5..1438218 100644 --- a/foreign/go/internal/command/stream.go +++ b/foreign/go/internal/command/stream.go
@@ -98,14 +98,17 @@ return g.StreamId.MarshalBinary() } -type GetStreams struct{} +// GetStreams asks for one page of the streams. +type GetStreams struct { + Query iggcon.NamedPageQuery +} func (g *GetStreams) Code() Code { return GetStreamsCode } func (g *GetStreams) MarshalBinary() ([]byte, error) { - return []byte{}, nil + return g.Query.AppendBinary(nil) } // UpdateStream patches a stream through the generic UpdateResource command.
diff --git a/foreign/go/internal/command/topic.go b/foreign/go/internal/command/topic.go index 6f43476..b6016b1 100644 --- a/foreign/go/internal/command/topic.go +++ b/foreign/go/internal/command/topic.go
@@ -166,8 +166,10 @@ return iggcon.MarshalIdentifiers(g.StreamId, g.TopicId) } +// GetTopics asks for one page of the topics of a stream. type GetTopics struct { StreamId iggcon.Identifier + Query iggcon.NamedPageQuery } func (g *GetTopics) Code() Code { @@ -175,7 +177,11 @@ } func (g *GetTopics) MarshalBinary() ([]byte, error) { - return g.StreamId.MarshalBinary() + streamId, err := g.StreamId.MarshalBinary() + if err != nil { + return nil, err + } + return g.Query.AppendBinary(streamId) } type DeleteTopic struct {
diff --git a/foreign/go/internal/command/user.go b/foreign/go/internal/command/user.go index ed4f6c7..1a23939 100644 --- a/foreign/go/internal/command/user.go +++ b/foreign/go/internal/command/user.go
@@ -97,14 +97,17 @@ return c.Id.MarshalBinary() } -type GetUsers struct{} +// GetUsers asks for one page of the users. +type GetUsers struct { + Query iggcon.NamedPageQuery +} func (g *GetUsers) Code() Code { return GetUsersCode } func (g *GetUsers) MarshalBinary() ([]byte, error) { - return []byte{}, nil + return g.Query.AppendBinary(nil) } type UpdatePermissions struct {
diff --git a/foreign/go/internal/command/user_test.go b/foreign/go/internal/command/user_test.go index e929a51..432c4fa 100644 --- a/foreign/go/internal/command/user_test.go +++ b/foreign/go/internal/command/user_test.go
@@ -245,7 +245,7 @@ } func TestGetUsersMarshalBinary(t *testing.T) { - request := &GetUsers{} + request := &GetUsers{Query: iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()}} if got := request.Code(); got != 32 { t.Fatalf("GetUsers code = %d, want 32", got) } @@ -254,8 +254,10 @@ if err != nil { t.Fatal(err) } - if len(got) != 0 { - t.Fatalf("GetUsers body = %v, want empty", got) + // Order id, ascending, limit 100, no cursor, no name. + want := []byte{0, 0, 100, 0, 0, 0, 0, 0} + if !bytes.Equal(got, want) { + t.Fatalf("GetUsers body = %v, want %v", got, want) } }
diff --git a/foreign/go/internal/vsr/register.go b/foreign/go/internal/vsr/register.go index 0ddf6d3..0d8f987 100644 --- a/foreign/go/internal/vsr/register.go +++ b/foreign/go/internal/vsr/register.go
@@ -25,10 +25,10 @@ ) // ProtocolVersion is the packed semver of the wire contract this codec -// implements, 0.12.2 per core/binary_protocol/src/version.rs. Update it with +// implements, 0.12.3 per core/binary_protocol/src/version.rs. Update it with // the Rust constant during stable release preparation. Edge builds sharing // this number are not guaranteed to have compatible layouts. -var ProtocolVersion = packProtocolVersion(0, 12, 2) +var ProtocolVersion = packProtocolVersion(0, 12, 3) // packProtocolVersion packs a semver into the ten-bits-per-field layout the // register handshake carries.
diff --git a/foreign/go/internal/vsr/register_test.go b/foreign/go/internal/vsr/register_test.go index a6cc2bc..3b5e71c 100644 --- a/foreign/go/internal/vsr/register_test.go +++ b/foreign/go/internal/vsr/register_test.go
@@ -36,10 +36,10 @@ } func TestProtocolVersion_PacksTheWireContractSemver(t *testing.T) { - assert.Equal(t, uint32(12290), ProtocolVersion) + assert.Equal(t, uint32(12291), ProtocolVersion) assert.Equal(t, uint32(0), ProtocolVersion>>20) assert.Equal(t, uint32(12), (ProtocolVersion>>10)&0x3FF) - assert.Equal(t, uint32(2), ProtocolVersion&0x3FF) + assert.Equal(t, uint32(3), ProtocolVersion&0x3FF) } func TestSerializeLoginRegister_EncodesTheDeclaredLayout(t *testing.T) {
diff --git a/foreign/go/tests/e2e_list_pages_test.go b/foreign/go/tests/e2e_list_pages_test.go new file mode 100644 index 0000000..8769b9b --- /dev/null +++ b/foreign/go/tests/e2e_list_pages_test.go
@@ -0,0 +1,177 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package tests_test + +import ( + "context" + "slices" + "testing" + + iggcon "github.com/apache/iggy/foreign/go/contracts" + ierror "github.com/apache/iggy/foreign/go/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Cursor texts of core/common/fixtures/list_pages.json. The text of both is +// valid, so only the server can refuse them. +const ( + // idSevenCursor is a cursor of the id walk. + idSevenCursor = "pg1_AQcAAAAAAAAA" + // unknownKindCursor holds a cursor kind that no server knows. + unknownKindCursor = "pg1_AwcAAAAAAAAA" +) + +func TestE2E_ListPages(t *testing.T) { + t.Run("given_three_streams_when_reading_pages_of_two_should_return_each_once_in_the_order_asked", func(t *testing.T) { + connected := connect(t) + ctx := context.Background() + prefix := uniqueName("pages") + var ids []uint32 + for _, suffix := range []string{"a", "b", "c"} { + stream, err := connected.CreateStream(ctx, prefix+"-"+suffix, nil) + require.NoError(t, err) + scratchStream(t, connected, stream.Id) + ids = append(ids, stream.Id) + } + // A create takes the lowest free id, so a delete by another client can + // give a later stream a lower id. + ascendingIds := slices.Sorted(slices.Values(ids)) + descendingIds := slices.Clone(ascendingIds) + slices.Reverse(descendingIds) + + walks := []struct { + order iggcon.PageOrder + descending bool + want []uint32 + }{ + {iggcon.PageOrderID, false, ascendingIds}, + {iggcon.PageOrderID, true, descendingIds}, + {iggcon.PageOrderCreated, false, ids}, + } + for _, walk := range walks { + query := pageQueryWithName(prefix) + query.Order, query.Descending, query.Limit = walk.order, walk.descending, 2 + first, err := connected.GetStreamsPage(ctx, query) + require.NoError(t, err) + require.Len(t, first.Items, 2, "%+v", walk) + require.NotNil(t, first.Next, "%+v", walk) + + query.Cursor = first.Next + second, err := connected.GetStreamsPage(ctx, query) + require.NoError(t, err) + assert.Nil(t, second.Next, "%+v", walk) + + var walked []uint32 + for _, stream := range append(first.Items, second.Items...) { + walked = append(walked, stream.Id) + } + assert.Equal(t, walk.want, walked, "%+v", walk) + } + + streams, err := connected.GetStreams(ctx) + require.NoError(t, err) + for _, id := range ids { + assert.True(t, slices.ContainsFunc(streams, func(stream iggcon.Stream) bool { return stream.Id == id }), + "the whole list holds stream %d", id) + } + }) + + t.Run("given_a_topic_with_three_partitions_when_reading_pages_of_two_should_return_each_partition_once", func(t *testing.T) { + connected := connect(t) + ctx := context.Background() + streamId, topicId := scratchTopic(t, connected, 3) + + query := iggcon.NewPageQuery() + query.Limit = 2 + first, err := connected.GetPartitionsPage(ctx, streamId, topicId, query) + require.NoError(t, err) + require.Len(t, first.Items, 2) + require.NotNil(t, first.Next) + + query.Cursor = first.Next + second, err := connected.GetPartitionsPage(ctx, streamId, topicId, query) + require.NoError(t, err) + assert.Nil(t, second.Next) + + var ids []uint32 + for _, partition := range append(first.Items, second.Items...) { + ids = append(ids, partition.Id) + } + assert.Equal(t, []uint32{0, 1, 2}, ids) + }) + + t.Run("given_a_topic_a_group_and_a_user_when_filtering_by_name_should_return_only_the_match", func(t *testing.T) { + connected := connect(t) + ctx := context.Background() + streamId, topicId := scratchTopic(t, connected, 1) + partitionsCount := uint32(1) + topic, err := connected.CreateTopic(ctx, streamId, "sensor-readings", &iggcon.TopicOptions{PartitionsCount: &partitionsCount}) + require.NoError(t, err) + group, err := connected.CreateConsumerGroup(ctx, streamId, topicId, "billing") + require.NoError(t, err) + _, err = connected.CreateConsumerGroup(ctx, streamId, topicId, "audit") + require.NoError(t, err) + username := uniqueUsername("pages") + user := scratchUser(t, connected, username) + + topics, err := connected.GetTopicsPage(ctx, streamId, pageQueryWithName("sensor")) + require.NoError(t, err) + require.Len(t, topics.Items, 1) + assert.Equal(t, topic.Id, topics.Items[0].Id) + assert.Nil(t, topics.Next) + + groups, err := connected.GetConsumerGroupsPage(ctx, streamId, topicId, pageQueryWithName("bill")) + require.NoError(t, err) + require.Len(t, groups.Items, 1) + assert.Equal(t, group.Id, groups.Items[0].Id) + assert.Nil(t, groups.Next) + + users, err := connected.GetUsersPage(ctx, pageQueryWithName(username)) + require.NoError(t, err) + require.Len(t, users.Items, 1) + assert.Equal(t, user.Id, users.Items[0].Id) + assert.Nil(t, users.Next) + }) + + t.Run("given_page_requests_the_server_cannot_serve_when_reading_should_be_refused_as_invalid_command", func(t *testing.T) { + connected := connect(t) + ctx := context.Background() + + unknownKind, err := iggcon.ParsePageCursor(unknownKindCursor) + require.NoError(t, err) + query := iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()} + query.Cursor = &unknownKind + _, err = connected.GetStreamsPage(ctx, query) + assert.ErrorIs(t, err, ierror.ErrInvalidCommand, "a cursor of an unknown kind") + + idCursor, err := iggcon.ParsePageCursor(idSevenCursor) + require.NoError(t, err) + query = iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()} + query.Order, query.Cursor = iggcon.PageOrderCreated, &idCursor + _, err = connected.GetStreamsPage(ctx, query) + assert.ErrorIs(t, err, ierror.ErrInvalidCommand, "a cursor of the id walk in a created walk") + + _, err = connected.GetStreamsPage(ctx, iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery()}) + require.NoError(t, err, "the connection stays usable after refused pages") + }) +} + +func pageQueryWithName(name string) iggcon.NamedPageQuery { + return iggcon.NamedPageQuery{PageQuery: iggcon.NewPageQuery(), Name: &name} +}
diff --git a/foreign/java/README.md b/foreign/java/README.md index 146fd9e..719b35d 100644 --- a/foreign/java/README.md +++ b/foreign/java/README.md
@@ -435,6 +435,35 @@ A cursor's `toString()` is its `mc1_` text, which `MetadataChangeCursor.parse` reads back, so a mirror can store it. A query the rules refuse fails with an `IggyValidationException` for invalid command before anything is sent, and a record of a kind this SDK does not know arrives as `MetadataChangeBody.Unknown` or `MetadataChangeBody.UnknownJson`. +### List Pages + +`getStreams`, `getTopics`, `getConsumerGroups` and `getUsers` return a whole list. Over TCP, each of them reads the list in pages of at most 1,000 items, so the result is not one consistent read. All pages share the sign-in and the request timeout of the call, so a new sign-in during the walk fails it. An entity that someone creates or deletes during the walk can appear or not appear. The walk fails with `IggyMalformedResponseException` when the server answers the page cursor it was sent. + +Over HTTP, they read the whole list in one reply. The server builds that reply from pages of 1,000 items, so it is not one consistent read either. + +`getStreamsPage`, `getTopicsPage`, `getPartitionsPage`, `getConsumerGroupsPage` and `getUsersPage` return one page. The page methods of streams, topics, consumer groups and users take a `NamedPageQuery`, which holds a `PageQuery` and an optional name. `getPartitionsPage` takes a `PageQuery`, which has no name. To read the next page, send the same query with the `next()` of the page as its cursor. A page can be empty and still have a `next()`. + +```java +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageQuery; +import org.apache.iggy.stream.StreamBase; + +NamedPageQuery query = new NamedPageQuery(PageQuery.builder().build()); +while (true) { + Page<StreamBase> page = client.streams().getStreamsPage(query); + page.items().forEach(stream -> System.out.println(stream.id() + " " + stream.name())); + if (page.next().isEmpty()) { + break; + } + query = query.withCursor(page.next().get()); +} +``` + +`order` selects `PageOrder.ID` or `PageOrder.CREATED`, and `descending` reverses it. The `name` of a `NamedPageQuery` keeps the entries whose name holds the text, case-sensitive. For example, `new NamedPageQuery(PageQuery.builder().build(), Optional.of("orders"))` reads the entries whose name holds `orders`. + +The client refuses a query that breaks the page rules with an `IggyValidationException` for invalid command, before it sends anything. Examples are a limit outside 1 to 1000 and a name that is empty or longer than 255 bytes. A `PageCursor` prints and parses as the `pg1_` text form that the HTTP API and the CLI use. The client does not read the bytes of a cursor. The server refuses a cursor that it cannot use, also with invalid command. + ## Polling The SDK reads messages at three levels: a poll of one partition, a partition reader that reads many partitions in batches, and a consumer that hands over one message at a time. All three take `PollOptions`, whose `CommitPolicy` decides who stores the consumer offsets.
diff --git a/foreign/java/gradle.properties b/foreign/java/gradle.properties index 81698d5..69c21a5 100644 --- a/foreign/java/gradle.properties +++ b/foreign/java/gradle.properties
@@ -15,5 +15,5 @@ # specific language governing permissions and limitations # under the License. -version=0.10.0 +version=0.10.1-SNAPSHOT group=org.apache.iggy
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/ConsumerGroupsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/ConsumerGroupsClient.java index a8f2d0d..53c0f9e 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/ConsumerGroupsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/ConsumerGroupsClient.java
@@ -25,6 +25,8 @@ import org.apache.iggy.identifier.ConsumerId; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import java.util.List; import java.util.Optional; @@ -99,6 +101,12 @@ /** * Gets all consumer groups for a topic asynchronously. * + * <p>The client reads the list in pages of up to 1000 groups, so the list is not one + * consistent read. All pages share the sign-in and the request timeout of the + * call, so a new sign-in during the read fails it. The call fails with + * {@link org.apache.iggy.exception.IggyMalformedResponseException} when + * the server answers the page cursor it was sent. + * * @param streamId The stream identifier * @param topicId The topic identifier * @return A CompletableFuture containing list of consumer groups @@ -106,6 +114,18 @@ CompletableFuture<List<ConsumerGroup>> getConsumerGroups(StreamId streamId, TopicId topicId); /** + * Gets one page of the consumer groups of a topic asynchronously. + * + * @param streamId The stream identifier + * @param topicId The topic identifier + * @param query The order, limit, cursor and name filter of the page + * @return A CompletableFuture that completes with the page, or fails with an invalid + * command error when the query breaks the page rules + */ + CompletableFuture<Page<ConsumerGroup>> getConsumerGroupsPage( + StreamId streamId, TopicId topicId, NamedPageQuery query); + + /** * Creates a consumer group asynchronously. * * @param streamId The stream identifier (numeric ID)
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/PartitionsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/PartitionsClient.java index d06260e..e0c8340 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/PartitionsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/PartitionsClient.java
@@ -21,6 +21,9 @@ import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageQuery; import java.util.concurrent.CompletableFuture; @@ -72,4 +75,15 @@ * @return A CompletableFuture that completes when the operation is done */ CompletableFuture<Void> deletePartitions(StreamId streamId, TopicId topicId, Long partitionsCount); + + /** + * Gets one page of the partitions of a topic. + * + * @param streamId The stream identifier + * @param topicId The topic identifier + * @param query The order, limit and cursor of the page + * @return A CompletableFuture that completes with the page, or fails with an invalid + * command error when the query breaks the page rules + */ + CompletableFuture<Page<Partition>> getPartitionsPage(StreamId streamId, TopicId topicId, PageQuery query); }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/StreamsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/StreamsClient.java index 9e00b00..f0b9f9b 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/StreamsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/StreamsClient.java
@@ -25,6 +25,8 @@ import org.apache.iggy.stream.StreamDetails; import org.apache.iggy.stream.StreamOptions; import org.apache.iggy.stream.StreamUpdate; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import java.util.List; import java.util.Map; @@ -84,7 +86,12 @@ * Gets a list of all streams on the server. * * <p>Returns basic information about each stream without topic details. Use - * {@link #getStream(StreamId)} for full details about a specific stream. + * {@link #getStream(StreamId)} for full details about a specific stream. The + * client reads the list in pages of up to 1000 streams, so the list is not one + * consistent read. All pages share the sign-in and the request timeout of the + * call, so a new sign-in during the read fails it. The call fails with + * {@link org.apache.iggy.exception.IggyMalformedResponseException} when + * the server answers the page cursor it was sent. * * @return a {@link CompletableFuture} that completes with a list of {@link StreamBase} * objects for all streams @@ -92,6 +99,15 @@ CompletableFuture<List<StreamBase>> getStreams(); /** + * Gets one page of streams. + * + * @param query the order, limit, cursor and name filter of the page + * @return a {@link CompletableFuture} that completes with the page, or fails with an + * invalid command error when the query breaks the page rules + */ + CompletableFuture<Page<StreamBase>> getStreamsPage(NamedPageQuery query); + + /** * Creates a new stream with the given name and no options. * * <p>The stream ID is assigned by the server. Stream names must be unique across
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/TopicsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/TopicsClient.java index a251778..162bc2c 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/TopicsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/TopicsClient.java
@@ -22,6 +22,8 @@ import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; import org.apache.iggy.message.HeaderValue; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.topic.Topic; import org.apache.iggy.topic.TopicDetails; import org.apache.iggy.topic.TopicOptions; @@ -72,12 +74,28 @@ /** * Gets a list of all topics within a stream. * + * <p>The client reads the list in pages of up to 1000 topics, so the list is not one + * consistent read. All pages share the sign-in and the request timeout of the + * call, so a new sign-in during the read fails it. The call fails with + * {@link org.apache.iggy.exception.IggyMalformedResponseException} when + * the server answers the page cursor it was sent. + * * @param streamId the stream identifier * @return a {@link CompletableFuture} that completes with a list of {@link Topic} objects */ CompletableFuture<List<Topic>> getTopics(StreamId streamId); /** + * Gets one page of the topics within a stream. + * + * @param streamId the stream identifier + * @param query the order, limit, cursor and name filter of the page + * @return a {@link CompletableFuture} that completes with the page, or fails with an + * invalid command error when the query breaks the page rules + */ + CompletableFuture<Page<Topic>> getTopicsPage(StreamId streamId, NamedPageQuery query); + + /** * Creates a new topic within a stream with the server's default settings. * * @param streamId the stream identifier to create the topic in
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/UsersClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/UsersClient.java index d027642..2b144a7 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/UsersClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/UsersClient.java
@@ -20,6 +20,8 @@ package org.apache.iggy.client.async; import org.apache.iggy.identifier.UserId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.user.IdentityInfo; import org.apache.iggy.user.Permissions; import org.apache.iggy.user.UserInfo; @@ -82,11 +84,25 @@ /** * Get a list of the users currently registered. * + * <p>The client reads the list in pages of up to 1000 users, so the list is not one consistent read. All pages + * share the sign-in and the request timeout of the call, so a new sign-in during the read fails it. The call + * fails with {@link org.apache.iggy.exception.IggyMalformedResponseException} when the server answers the page + * cursor it was sent. + * * @return A {@link CompletableFuture} that completes with a list of {@link UserInfo} about each of the registered users. */ CompletableFuture<List<UserInfo>> getUsers(); /** + * Get one page of the registered users. The name filter applies to the username. + * + * @param query the order, limit, cursor and name filter of the page + * @return a {@link CompletableFuture} that completes with the page, or fails with an invalid command error when + * the query breaks the page rules + */ + CompletableFuture<Page<UserInfo>> getUsersPage(NamedPageQuery query); + + /** * Create a user with the details provided and no options. * * @see #createUser(String, String, UserStatus, Optional, UserOptions)
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/AsyncTcpConnection.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/AsyncTcpConnection.java index 8724445..112f360 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/AsyncTcpConnection.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/AsyncTcpConnection.java
@@ -67,7 +67,6 @@ import javax.net.ssl.SSLException; import java.io.File; import java.time.Duration; -import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -375,6 +374,10 @@ return consensusSession.owner(); } + long operationDeadline() { + return System.nanoTime() + requestTimeoutNanos; + } + long metadataWatermark() { return consensusSession.metadataWatermark(); } @@ -429,21 +432,6 @@ }); } - public <T> CompletableFuture<List<T>> exchangeForList( - CommandCode commandCode, ByteBuf payload, Function<ByteBuf, T> func) { - return mapResponse(send(commandCode, payload), response -> { - try { - var result = new ArrayList<T>(); - while (response.isReadable()) { - result.add(func.apply(response)); - } - return result; - } finally { - response.release(); - } - }); - } - public <T> CompletableFuture<Optional<T>> exchangeForOptional( CommandCode commandCode, ByteBuf payload, Function<ByteBuf, T> func) { return mapResponse(send(commandCode, payload), response -> { @@ -511,7 +499,7 @@ long requestDeadlineNanos, TransientFailoverState failoverState, long requiredSessionGeneration) { - long deadline = requestDeadlineNanos == 0 ? System.nanoTime() + requestTimeoutNanos : requestDeadlineNanos; + long deadline = requestDeadlineNanos == 0 ? operationDeadline() : requestDeadlineNanos; if (isLoginCode(commandCode) && authenticated) { return logoutThenLogin(commandCode, payload, deadline); }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/ConsumerGroupsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/ConsumerGroupsTcpClient.java index 4515994..e65edee 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/ConsumerGroupsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/ConsumerGroupsTcpClient.java
@@ -30,10 +30,11 @@ import org.apache.iggy.serde.BytesDeserializer; import org.apache.iggy.serde.BytesSerializer; import org.apache.iggy.serde.CommandCode; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @@ -85,23 +86,26 @@ @Override public CompletableFuture<List<ConsumerGroup>> getConsumerGroups(StreamId streamId, TopicId topicId) { - var payload = BytesSerializer.toBytes(streamId); - payload.writeBytes(BytesSerializer.toBytes(topicId)); - log.debug("Getting consumer groups - Stream: {}, Topic: {}", streamId, topicId); - return AsyncTcpConnection.mapResponse( - connection().send(CommandCode.ConsumerGroup.GET_ALL.getValue(), payload), response -> { - try { - List<ConsumerGroup> groups = new ArrayList<>(); - while (response.isReadable()) { - groups.add(BytesDeserializer.readConsumerGroup(response)); - } - return groups; - } finally { - response.release(); - } - }); + return PageReads.readWholeList( + connectionSupplier, + CommandCode.ConsumerGroup.GET_ALL, + BytesDeserializer::readConsumerGroup, + streamId, + topicId); + } + + @Override + public CompletableFuture<Page<ConsumerGroup>> getConsumerGroupsPage( + StreamId streamId, TopicId topicId, NamedPageQuery query) { + return PageReads.read( + connection(), + CommandCode.ConsumerGroup.GET_ALL, + query, + BytesDeserializer::readConsumerGroup, + streamId, + topicId); } @Override
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/PageReads.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/PageReads.java new file mode 100644 index 0000000..7293129 --- /dev/null +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/PageReads.java
@@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.async.tcp; + +import io.netty.buffer.ByteBuf; +import org.apache.iggy.exception.IggyMalformedResponseException; +import org.apache.iggy.exception.IggyValidationException; +import org.apache.iggy.identifier.Identifier; +import org.apache.iggy.serde.BytesDeserializer; +import org.apache.iggy.serde.BytesSerializer; +import org.apache.iggy.serde.CommandCode; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageQuery; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.function.Supplier; + +/** Reads of the list commands: one page, or a walk over a whole list. */ +final class PageReads { + + private static final PageQuery WHOLE_LIST = + PageQuery.builder().limit(PageQuery.MAX_LIMIT).build(); + + private PageReads() {} + + /** + * Sends one list request. A query that {@link NamedPageQuery#validate()} refuses fails the call and sends nothing. + */ + static <T> CompletableFuture<Page<T>> read( + AsyncTcpConnection connection, + CommandCode command, + NamedPageQuery query, + Function<ByteBuf, T> readItem, + Identifier... parents) { + return read(connection, command, query, readItem, 0, new AsyncTcpConnection.TransientFailoverState(), parents); + } + + private static <T> CompletableFuture<Page<T>> read( + AsyncTcpConnection connection, + CommandCode command, + NamedPageQuery query, + Function<ByteBuf, T> readItem, + long deadline, + AsyncTcpConnection.TransientFailoverState state, + Identifier... parents) { + try { + query.validate(); + } catch (IggyValidationException refused) { + return CompletableFuture.failedFuture(refused); + } + return AsyncTcpConnection.mapResponse( + connection.send(command.getValue(), BytesSerializer.toPageRequest(query, parents), deadline, state), + response -> { + try { + return BytesDeserializer.readPage(response, readItem); + } finally { + response.release(); + } + }); + } + + /** + * Reads a whole list as one call: every page keeps the caller sign-in and the budget that the walk started with, so + * a caller sign-in between two pages ends the walk. + */ + static <T> CompletableFuture<List<T>> readWholeList( + Supplier<AsyncTcpConnection> connection, + CommandCode command, + Function<ByteBuf, T> readItem, + Identifier... parents) { + AsyncTcpConnection first = connection.get(); + var state = new AsyncTcpConnection.TransientFailoverState(); + state.startIn(first.sessionOwner()); + long deadline = first.operationDeadline(); + return readWholeList(query -> read( + connection.get(), + command, + new NamedPageQuery(query), + readItem, + deadline, + state.nextHistory(), + parents)); + } + + /** + * Reads a whole list in ascending id order and in pages of {@link PageQuery#MAX_LIMIT}, until a page has no next + * cursor. The result is not one consistent read: an entity that someone creates or deletes during the walk can be + * in it or not. A page whose next cursor is the cursor it was read with fails the walk with + * {@link IggyMalformedResponseException}, because the walk would not end. + */ + static <T> CompletableFuture<List<T>> readWholeList(Function<PageQuery, CompletableFuture<Page<T>>> readPage) { + CompletableFuture<List<T>> result = new CompletableFuture<>(); + readFrom(WHOLE_LIST, readPage, new ArrayList<>(), result); + return result; + } + + /** + * Completes {@code result} by hand, as {@link AsyncTcpConnection#mapResponse} does, so a failed page reaches the + * caller as its own error and not inside a {@link java.util.concurrent.CompletionException}. A cancelled result + * stops the walk after the page in flight. + */ + private static <T> void readFrom( + PageQuery query, + Function<PageQuery, CompletableFuture<Page<T>>> readPage, + List<T> items, + CompletableFuture<List<T>> result) { + CompletableFuture<Page<T>> pending; + try { + pending = readPage.apply(query); + } catch (RuntimeException failure) { + result.completeExceptionally(failure); + return; + } + pending.whenComplete((page, error) -> { + if (error != null) { + result.completeExceptionally(error); + } else if (!result.isDone()) { + try { + items.addAll(page.items()); + Optional<PageCursor> next = page.next(); + if (next.isEmpty()) { + result.complete(items); + } else if (next.equals(query.cursor())) { + throw new IggyMalformedResponseException( + "Malformed page: the server answered the page cursor " + next.get() + " it was sent"); + } else { + readFrom(query.withCursor(next.get()), readPage, items, result); + } + } catch (RuntimeException failure) { + result.completeExceptionally(failure); + } + } + }); + } +}
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/PartitionsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/PartitionsTcpClient.java index 4260025..3add4e9 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/PartitionsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/PartitionsTcpClient.java
@@ -22,8 +22,13 @@ import org.apache.iggy.client.async.PartitionsClient; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.serde.BytesDeserializer; import org.apache.iggy.serde.BytesSerializer; import org.apache.iggy.serde.CommandCode; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -85,4 +90,15 @@ return null; }); } + + @Override + public CompletableFuture<Page<Partition>> getPartitionsPage(StreamId streamId, TopicId topicId, PageQuery query) { + return PageReads.read( + connection(), + CommandCode.Partition.GET_ALL, + new NamedPageQuery(query), + BytesDeserializer::readPartition, + streamId, + topicId); + } }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/StreamsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/StreamsTcpClient.java index 6e108d2..1e9e3b8 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/StreamsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/StreamsTcpClient.java
@@ -19,24 +19,24 @@ package org.apache.iggy.client.async.tcp; -import io.netty.buffer.Unpooled; import org.apache.iggy.client.async.StreamsClient; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.message.HeaderValue; +import org.apache.iggy.serde.BytesDeserializer; import org.apache.iggy.serde.BytesSerializer; import org.apache.iggy.serde.CommandCode; import org.apache.iggy.stream.StreamBase; import org.apache.iggy.stream.StreamDetails; import org.apache.iggy.stream.StreamUpdate; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; -import static org.apache.iggy.serde.BytesDeserializer.readStreamBase; import static org.apache.iggy.serde.BytesDeserializer.readStreamDetails; import static org.apache.iggy.serde.BytesSerializer.toBytes; @@ -96,15 +96,13 @@ @Override public CompletableFuture<List<StreamBase>> getStreams() { - return AsyncTcpConnection.mapResponse( - connection().send(CommandCode.Stream.GET_ALL.getValue(), Unpooled.EMPTY_BUFFER), response -> { - List<StreamBase> streams = new ArrayList<>(); - while (response.isReadable()) { - streams.add(readStreamBase(response)); - } - response.release(); - return streams; - }); + return PageReads.readWholeList( + connectionSupplier, CommandCode.Stream.GET_ALL, BytesDeserializer::readStreamBase); + } + + @Override + public CompletableFuture<Page<StreamBase>> getStreamsPage(NamedPageQuery query) { + return PageReads.read(connection(), CommandCode.Stream.GET_ALL, query, BytesDeserializer::readStreamBase); } @Override
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/TopicsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/TopicsTcpClient.java index 9e0c650..c4b041c 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/TopicsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/TopicsTcpClient.java
@@ -27,12 +27,13 @@ import org.apache.iggy.serde.BytesDeserializer; import org.apache.iggy.serde.BytesSerializer; import org.apache.iggy.serde.CommandCode; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.topic.Topic; import org.apache.iggy.topic.TopicDetails; import org.apache.iggy.topic.TopicOptions; import org.apache.iggy.topic.TopicUpdate; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @@ -87,21 +88,13 @@ @Override public CompletableFuture<List<Topic>> getTopics(StreamId streamId) { - var payload = toBytes(streamId); + return PageReads.readWholeList( + connectionSupplier, CommandCode.Topic.GET_ALL, BytesDeserializer::readTopic, streamId); + } - return AsyncTcpConnection.mapResponse( - connection().send(CommandCode.Topic.GET_ALL.getValue(), payload), response -> { - try { - var topicsCount = response.readUnsignedIntLE(); - List<Topic> topics = new ArrayList<>(Math.toIntExact(topicsCount)); - for (long i = 0; i < topicsCount; i++) { - topics.add(BytesDeserializer.readTopic(response)); - } - return topics; - } finally { - response.release(); - } - }); + @Override + public CompletableFuture<Page<Topic>> getTopicsPage(StreamId streamId, NamedPageQuery query) { + return PageReads.read(connection(), CommandCode.Topic.GET_ALL, query, BytesDeserializer::readTopic, streamId); } @Override
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/UsersTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/UsersTcpClient.java index d3f0f03..78f7408 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/UsersTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/UsersTcpClient.java
@@ -25,6 +25,8 @@ import org.apache.iggy.serde.BytesDeserializer; import org.apache.iggy.serde.BytesSerializer; import org.apache.iggy.serde.CommandCode; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.user.IdentityInfo; import org.apache.iggy.user.Permissions; import org.apache.iggy.user.UserInfo; @@ -77,8 +79,12 @@ @Override public CompletableFuture<List<UserInfo>> getUsers() { - var payload = Unpooled.EMPTY_BUFFER; - return connection().exchangeForList(CommandCode.User.GET_ALL, payload, BytesDeserializer::readUserInfo); + return PageReads.readWholeList(connectionSupplier, CommandCode.User.GET_ALL, BytesDeserializer::readUserInfo); + } + + @Override + public CompletableFuture<Page<UserInfo>> getUsersPage(NamedPageQuery query) { + return PageReads.read(connection(), CommandCode.User.GET_ALL, query, BytesDeserializer::readUserInfo); } @Override
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/vsr/VsrLoginCodec.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/vsr/VsrLoginCodec.java index 8d76705..55ab2dd 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/vsr/VsrLoginCodec.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/async/tcp/vsr/VsrLoginCodec.java
@@ -45,7 +45,7 @@ * protocol version through its current version, including patch components. * Versions outside this range, including newer patches, are rejected. */ - static final int PROTOCOL_VERSION = 12 << 10 | 2; // 0.12.2 + static final int PROTOCOL_VERSION = 12 << 10 | 3; // 0.12.3 static final String SDK_NAME = "java-sdk";
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/ConsumerGroupsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/ConsumerGroupsClient.java index 99a0742..cca6458 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/ConsumerGroupsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/ConsumerGroupsClient.java
@@ -25,6 +25,8 @@ import org.apache.iggy.identifier.ConsumerId; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import java.util.List; import java.util.Optional; @@ -41,8 +43,18 @@ return getConsumerGroups(StreamId.of(streamId), TopicId.of(topicId)); } + /** + * Over TCP, reads the list in pages of up to 1000 groups, so the list is not one consistent read. All pages share + * the sign-in and the request timeout of the call, so a new sign-in during the read fails it. Over TCP, the call + * fails with {@link org.apache.iggy.exception.IggyMalformedResponseException} when the server answers the page + * cursor it was sent. Over HTTP, reads the whole list in one reply, which the server builds from pages of 1000, so + * it is not one consistent read either. + */ List<ConsumerGroup> getConsumerGroups(StreamId streamId, TopicId topicId); + /** Gets one page of consumer groups. A query that breaks the page rules fails with an invalid command error. */ + Page<ConsumerGroup> getConsumerGroupsPage(StreamId streamId, TopicId topicId, NamedPageQuery query); + default ConsumerGroupDetails createConsumerGroup(Long streamId, Long topicId, String name) { return createConsumerGroup(StreamId.of(streamId), TopicId.of(topicId), name); }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/PartitionsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/PartitionsClient.java index 89e63fa..5e500d4 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/PartitionsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/PartitionsClient.java
@@ -21,6 +21,9 @@ import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageQuery; public interface PartitionsClient { @@ -35,4 +38,7 @@ } void deletePartitions(StreamId streamId, TopicId topicId, Long partitionsCount); + + /** Gets one page of partitions. A query that breaks the page rules fails with an invalid command error. */ + Page<Partition> getPartitionsPage(StreamId streamId, TopicId topicId, PageQuery query); }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/StreamsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/StreamsClient.java index 436ad45..c1d0872 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/StreamsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/StreamsClient.java
@@ -25,6 +25,8 @@ import org.apache.iggy.stream.StreamDetails; import org.apache.iggy.stream.StreamOptions; import org.apache.iggy.stream.StreamUpdate; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import java.util.List; import java.util.Map; @@ -38,8 +40,18 @@ Optional<StreamDetails> getStream(StreamId streamId); + /** + * Over TCP, reads the list in pages of up to 1000 streams, so the list is not one consistent read. All pages share + * the sign-in and the request timeout of the call, so a new sign-in during the read fails it. Over TCP, the call + * fails with {@link org.apache.iggy.exception.IggyMalformedResponseException} when the server answers the page + * cursor it was sent. Over HTTP, reads the whole list in one reply, which the server builds from pages of 1000, so + * it is not one consistent read either. + */ List<StreamBase> getStreams(); + /** Gets one page of streams. A query that breaks the page rules fails with an invalid command error. */ + Page<StreamBase> getStreamsPage(NamedPageQuery query); + /** Creates a stream without options. A server with encryption enabled generates the stream's own data key. */ default StreamDetails createStream(String name) { return createStream(name, StreamOptions.empty());
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/TopicsClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/TopicsClient.java index 19261d3..8548668 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/TopicsClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/TopicsClient.java
@@ -22,6 +22,8 @@ import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; import org.apache.iggy.message.HeaderValue; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.topic.Topic; import org.apache.iggy.topic.TopicDetails; import org.apache.iggy.topic.TopicOptions; @@ -43,8 +45,18 @@ return getTopics(StreamId.of(streamId)); } + /** + * Over TCP, reads the list in pages of up to 1000 topics, so the list is not one consistent read. All pages share + * the sign-in and the request timeout of the call, so a new sign-in during the read fails it. Over TCP, the call + * fails with {@link org.apache.iggy.exception.IggyMalformedResponseException} when the server answers the page + * cursor it was sent. Over HTTP, reads the whole list in one reply, which the server builds from pages of 1000, so + * it is not one consistent read either. + */ List<Topic> getTopics(StreamId streamId); + /** Gets one page of topics. A query that breaks the page rules fails with an invalid command error. */ + Page<Topic> getTopicsPage(StreamId streamId, NamedPageQuery query); + default TopicDetails createTopic(Long streamId, String name, long partitionsCount) { return createTopic(StreamId.of(streamId), name, partitionsCount); }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/UsersClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/UsersClient.java index 593b59a..48218e2 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/UsersClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/UsersClient.java
@@ -20,6 +20,8 @@ package org.apache.iggy.client.blocking; import org.apache.iggy.identifier.UserId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.user.IdentityInfo; import org.apache.iggy.user.Permissions; import org.apache.iggy.user.UserInfo; @@ -39,8 +41,21 @@ Optional<UserInfoDetails> getUser(UserId userId); + /** + * Over TCP, reads the list in pages of up to 1000 users, so the list is not one consistent read. All pages share + * the sign-in and the request timeout of the call, so a new sign-in during the read fails it. Over TCP, the call + * fails with {@link org.apache.iggy.exception.IggyMalformedResponseException} when the server answers the page + * cursor it was sent. Over HTTP, reads the whole list in one reply, which the server builds from pages of 1000, so + * it is not one consistent read either. + */ List<UserInfo> getUsers(); + /** + * Gets one page of users. The name filter applies to the username. A query that breaks the page rules fails with + * an invalid command error. + */ + Page<UserInfo> getUsersPage(NamedPageQuery query); + default UserInfoDetails createUser( String username, String password, UserStatus status, Optional<Permissions> permissions) { return createUser(username, password, status, permissions, UserOptions.empty());
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/ConsumerGroupsHttpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/ConsumerGroupsHttpClient.java index bf155ce..7227dda 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/ConsumerGroupsHttpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/ConsumerGroupsHttpClient.java
@@ -27,10 +27,13 @@ import org.apache.iggy.identifier.ConsumerId; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import tools.jackson.core.type.TypeReference; import java.util.List; import java.util.Optional; +import java.util.function.Function; class ConsumerGroupsHttpClient implements ConsumerGroupsClient { @@ -53,6 +56,13 @@ } @Override + public Page<ConsumerGroup> getConsumerGroupsPage(StreamId streamId, TopicId topicId, NamedPageQuery query) { + HttpPage<ConsumerGroup> page = + HttpPage.read(httpClient, path(streamId, topicId), query, new TypeReference<>() {}); + return page.toPage(Function.identity()); + } + + @Override public ConsumerGroupDetails createConsumerGroup(StreamId streamId, TopicId topicId, String name) { var request = httpClient.preparePostRequest(path(streamId, topicId), new CreateConsumerGroup(name)); return httpClient.execute(request, new TypeReference<>() {});
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/HttpPage.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/HttpPage.java new file mode 100644 index 0000000..1c783a6 --- /dev/null +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/HttpPage.java
@@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.blocking.http; + +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.core5.http.message.BasicNameValuePair; +import org.apache.iggy.exception.IggyMalformedResponseException; +import org.apache.iggy.exception.IggyValidationException; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import tools.jackson.core.type.TypeReference; + +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +/** The JSON page of a list route, {@code {"items": [...], "next": "pg1_..."}}, with no next on the last page. */ +record HttpPage<T>(List<T> items, Optional<String> next) { + + /** Reads one page of {@code path}. A query that {@link NamedPageQuery#validate()} refuses is never sent. */ + static <T> HttpPage<T> read( + InternalHttpClient httpClient, String path, NamedPageQuery query, TypeReference<HttpPage<T>> type) { + query.validate(); + NameValuePair[] params = query.httpQuery().entrySet().stream() + .map(pair -> new BasicNameValuePair(pair.getKey(), pair.getValue())) + .toArray(NameValuePair[]::new); + return httpClient.execute(httpClient.prepareGetRequest(path, params), type); + } + + <R> Page<R> toPage(Function<T, R> toItem) { + Optional<PageCursor> cursor; + try { + cursor = next.map(PageCursor::parse); + } catch (IggyValidationException refused) { + throw new IggyMalformedResponseException("Malformed page: next", refused); + } + return new Page<>(items.stream().map(toItem).toList(), cursor); + } +}
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/PartitionsHttpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/PartitionsHttpClient.java index c5d57ed..acc7787 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/PartitionsHttpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/PartitionsHttpClient.java
@@ -23,6 +23,13 @@ import org.apache.iggy.client.blocking.PartitionsClient; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageQuery; +import tools.jackson.core.type.TypeReference; + +import java.util.function.Function; class PartitionsHttpClient implements PartitionsClient { @@ -54,5 +61,15 @@ sendContexts.clear(); } + @Override + public Page<Partition> getPartitionsPage(StreamId streamId, TopicId topicId, PageQuery query) { + HttpPage<Partition> page = HttpPage.read( + httpClient, + STREAMS + "/" + streamId + TOPICS + "/" + topicId + PARTITIONS, + new NamedPageQuery(query), + new TypeReference<>() {}); + return page.toPage(Function.identity()); + } + private record CreatePartitions(Long partitionsCount) {} }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/StreamsHttpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/StreamsHttpClient.java index aea5fd2..5379e12 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/StreamsHttpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/StreamsHttpClient.java
@@ -25,6 +25,8 @@ import org.apache.iggy.stream.StreamBase; import org.apache.iggy.stream.StreamDetails; import org.apache.iggy.stream.StreamUpdate; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import tools.jackson.core.type.TypeReference; import java.math.BigInteger; @@ -59,6 +61,12 @@ } @Override + public Page<StreamBase> getStreamsPage(NamedPageQuery query) { + HttpPage<HttpStream> page = HttpPage.read(httpClient, STREAMS, query, new TypeReference<>() {}); + return page.toPage(HttpStream::toStreamBase); + } + + @Override public StreamDetails createStream(String name, Map<String, HeaderValue> options) { var request = httpClient.preparePostRequest(STREAMS, new CreateStream(name, HttpOptionValue.requestValues(options)));
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/TopicsHttpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/TopicsHttpClient.java index f68eefe..db3cfe9 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/TopicsHttpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/TopicsHttpClient.java
@@ -24,6 +24,8 @@ import org.apache.iggy.identifier.TopicId; import org.apache.iggy.message.HeaderValue; import org.apache.iggy.partition.Partition; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.topic.Topic; import org.apache.iggy.topic.TopicDetails; import org.apache.iggy.topic.TopicOptions; @@ -63,6 +65,13 @@ } @Override + public Page<Topic> getTopicsPage(StreamId streamId, NamedPageQuery query) { + HttpPage<HttpTopic> page = + HttpPage.read(httpClient, STREAMS + "/" + streamId + TOPICS, query, new TypeReference<>() {}); + return page.toPage(HttpTopic::toTopic); + } + + @Override public TopicDetails createTopic( StreamId streamId, String name, long partitionsCount, Map<String, HeaderValue> options) { var request = httpClient.preparePostRequest(
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/UsersHttpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/UsersHttpClient.java index e62b1d5..84517dc 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/UsersHttpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/http/UsersHttpClient.java
@@ -22,6 +22,8 @@ import org.apache.iggy.IggyVersion; import org.apache.iggy.client.blocking.UsersClient; import org.apache.iggy.identifier.UserId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.user.IdentityInfo; import org.apache.iggy.user.Permissions; import org.apache.iggy.user.TokenInfo; @@ -62,6 +64,12 @@ } @Override + public Page<UserInfo> getUsersPage(NamedPageQuery query) { + HttpPage<HttpUser> page = HttpPage.read(httpClient, USERS, query, new TypeReference<>() {}); + return page.toPage(HttpUser::toUserInfo); + } + + @Override public UserInfoDetails createUser( String username, String password,
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/ConsumerGroupsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/ConsumerGroupsTcpClient.java index d8b452e..0887702 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/ConsumerGroupsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/ConsumerGroupsTcpClient.java
@@ -26,6 +26,8 @@ import org.apache.iggy.identifier.ConsumerId; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import java.util.List; import java.util.Optional; @@ -49,6 +51,11 @@ } @Override + public Page<ConsumerGroup> getConsumerGroupsPage(StreamId streamId, TopicId topicId, NamedPageQuery query) { + return FutureUtil.resolve(delegate.getConsumerGroupsPage(streamId, topicId, query)); + } + + @Override public ConsumerGroupDetails createConsumerGroup(StreamId streamId, TopicId topicId, String name) { return FutureUtil.resolve(delegate.createConsumerGroup(streamId, topicId, name)); }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/PartitionsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/PartitionsTcpClient.java index d2060b2..24dc5c6 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/PartitionsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/PartitionsTcpClient.java
@@ -22,6 +22,9 @@ import org.apache.iggy.client.blocking.PartitionsClient; import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageQuery; final class PartitionsTcpClient implements PartitionsClient { @@ -40,4 +43,9 @@ public void deletePartitions(StreamId streamId, TopicId topicId, Long partitionsCount) { FutureUtil.resolve(delegate.deletePartitions(streamId, topicId, partitionsCount)); } + + @Override + public Page<Partition> getPartitionsPage(StreamId streamId, TopicId topicId, PageQuery query) { + return FutureUtil.resolve(delegate.getPartitionsPage(streamId, topicId, query)); + } }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/StreamsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/StreamsTcpClient.java index ab12356..f794e06 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/StreamsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/StreamsTcpClient.java
@@ -25,6 +25,8 @@ import org.apache.iggy.stream.StreamBase; import org.apache.iggy.stream.StreamDetails; import org.apache.iggy.stream.StreamUpdate; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import java.util.List; import java.util.Map; @@ -49,6 +51,11 @@ } @Override + public Page<StreamBase> getStreamsPage(NamedPageQuery query) { + return FutureUtil.resolve(delegate.getStreamsPage(query)); + } + + @Override public StreamDetails createStream(String name, Map<String, HeaderValue> options) { return FutureUtil.resolve(delegate.createStream(name, options)); }
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/TopicsTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/TopicsTcpClient.java index 042cd49..a465bbd 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/TopicsTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/TopicsTcpClient.java
@@ -23,6 +23,8 @@ import org.apache.iggy.identifier.StreamId; import org.apache.iggy.identifier.TopicId; import org.apache.iggy.message.HeaderValue; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.topic.Topic; import org.apache.iggy.topic.TopicDetails; import org.apache.iggy.topic.TopicUpdate; @@ -50,6 +52,11 @@ } @Override + public Page<Topic> getTopicsPage(StreamId streamId, NamedPageQuery query) { + return FutureUtil.resolve(delegate.getTopicsPage(streamId, query)); + } + + @Override public TopicDetails createTopic( StreamId streamId, String name, long partitionsCount, Map<String, HeaderValue> options) { return FutureUtil.resolve(delegate.createTopic(streamId, name, partitionsCount, options));
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/UsersTcpClient.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/UsersTcpClient.java index 102ec82..7bb4dd2 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/UsersTcpClient.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/client/blocking/tcp/UsersTcpClient.java
@@ -21,6 +21,8 @@ import org.apache.iggy.client.blocking.UsersClient; import org.apache.iggy.identifier.UserId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; import org.apache.iggy.user.IdentityInfo; import org.apache.iggy.user.Permissions; import org.apache.iggy.user.UserInfo; @@ -51,6 +53,11 @@ } @Override + public Page<UserInfo> getUsersPage(NamedPageQuery query) { + return FutureUtil.resolve(delegate.getUsersPage(query)); + } + + @Override public UserInfoDetails createUser( String username, String password,
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/exception/IggyErrorCode.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/exception/IggyErrorCode.java index 9656da3..42bd5fc 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/exception/IggyErrorCode.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/exception/IggyErrorCode.java
@@ -86,6 +86,12 @@ * request again. */ TIERED_READ_FAILED(96), + /** + * The server sent this error in place of a reply above the reply size limit: a GetClients reply, or a reply to a + * read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata. The + * connection stays open. For a list, the page methods return the same items in smaller replies. + */ + REPLY_TOO_LARGE(97), // Client errors CLIENT_NOT_FOUND(100),
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesDeserializer.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesDeserializer.java index e14910d..2fa4da1 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesDeserializer.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesDeserializer.java
@@ -61,6 +61,9 @@ import org.apache.iggy.system.MetadataChanges; import org.apache.iggy.system.MetadataCurrentItem; import org.apache.iggy.system.OptionSpec; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageQuery; import org.apache.iggy.system.Stats; import org.apache.iggy.topic.Topic; import org.apache.iggy.topic.TopicDetails; @@ -80,6 +83,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.function.Function; import java.util.function.Supplier; /** @@ -724,6 +728,32 @@ return readMetadataChangesPart(() -> MetadataChangesReader.readItemBody(group, body)); } + /** + * Reads the reply of a list command: {@code [next_len:u8][next][count:u32][item]*}. A body short of {@code count} + * items, or with bytes after them, is malformed. The next cursor keeps its bytes as they came, because only the + * server reads them. + */ + public static <T> Page<T> readPage(ByteBuf response, Function<ByteBuf, T> readItem) { + try { + byte[] next = new byte[response.readUnsignedByte()]; + response.readBytes(next); + long count = response.readUnsignedIntLE(); + // A server never sends more than MAX_LIMIT items, so a larger count does not size the allocation. + List<T> items = new ArrayList<>((int) Math.min(count, PageQuery.MAX_LIMIT)); + for (long index = 0; index < count; index++) { + items.add(readItem.apply(response)); + } + if (response.isReadable()) { + throw new IggyMalformedResponseException( + "Malformed page: " + response.readableBytes() + " bytes after its " + count + " items"); + } + // A cursor has 1 to 255 bytes, so a next of 0 bytes marks the last page. + return new Page<>(items, PageCursor.fromBytes(next)); + } catch (IndexOutOfBoundsException truncated) { + throw new IggyMalformedResponseException("Malformed page: it is truncated", truncated); + } + } + public static UserInfoDetails readUserInfoDetails(ByteBuf response) { var userInfo = readUserInfo(response);
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesSerializer.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesSerializer.java index 7b38d32..fc37e78 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesSerializer.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/BytesSerializer.java
@@ -43,7 +43,10 @@ import org.apache.iggy.system.MetadataChangeStart; import org.apache.iggy.system.MetadataChangesQuery; import org.apache.iggy.system.MetadataCurrentPageToken; +import org.apache.iggy.system.NamedPageQuery; import org.apache.iggy.system.OptionsScope; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageQuery; import org.apache.iggy.topic.TopicUpdate; import org.apache.iggy.user.GlobalPermissions; import org.apache.iggy.user.Permissions; @@ -313,6 +316,30 @@ } /** + * A list request: the identifiers of its parents, then the page block {@code [order:u8][descending:u8][limit:u32]} + * {@code [cursor_len:u8][cursor][name_len:u8][name]}, where a length of 0 means no cursor or no name. A list without + * names sends its {@link PageQuery} as a query without a name. Validate the query first. + */ + public static ByteBuf toPageRequest(NamedPageQuery query, Identifier... parents) { + PageQuery page = query.page(); + byte[] cursor = page.cursor().map(PageCursor::toBytes).orElse(new byte[0]); + byte[] name = + query.name().map(text -> text.getBytes(StandardCharsets.UTF_8)).orElse(new byte[0]); + var payload = Unpooled.buffer(); + for (Identifier parent : parents) { + writeAndRelease(payload, toBytes(parent)); + } + payload.writeByte(page.order().asCode()); + payload.writeBoolean(page.descending()); + payload.writeIntLE((int) page.limit()); + payload.writeByte(cursor.length); + payload.writeBytes(cursor); + payload.writeByte(name.length); + payload.writeBytes(name); + return payload; + } + + /** * {@code CreateTopic}: {@code [stream_id][partitions_count:u32][name][options to end]}. * {@code partitions_count} is an argument of the command, never an option: admission consumes it to * compute partition assignments.
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/CommandCode.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/CommandCode.java index e885261..12c89ef 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/CommandCode.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/serde/CommandCode.java
@@ -173,7 +173,8 @@ enum Partition implements CommandCode { CREATE(402), - DELETE(403); + DELETE(403), + GET_ALL(404); private final int value;
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/MetadataChangeEncoding.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/MetadataChangeEncoding.java index d830418..764d9dc 100644 --- a/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/MetadataChangeEncoding.java +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/MetadataChangeEncoding.java
@@ -28,7 +28,10 @@ import java.util.Base64; import java.util.Optional; -/** Little-endian unsigned values and canonical Base64url, the encodings of change cursors and page tokens. */ +/** + * Little-endian unsigned values and canonical Base64url, the encodings of change cursors, page tokens and list page + * cursors. + */ final class MetadataChangeEncoding { private MetadataChangeEncoding() {}
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/NamedPageQuery.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/NamedPageQuery.java new file mode 100644 index 0000000..ca94234 --- /dev/null +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/NamedPageQuery.java
@@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.system; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * One page request of a list of named entities: streams, topics, consumer groups and users. + * + * @param page the order, limit and cursor of the page + * @param name keeps only the entries whose name holds this text, case-sensitive, empty for every entry + */ +public record NamedPageQuery(PageQuery page, Optional<String> name) { + + /** Most bytes of a name filter in UTF-8. */ + public static final int MAX_NAME_SIZE = 255; + + public NamedPageQuery { + Objects.requireNonNull(page, "page"); + Objects.requireNonNull(name, "name"); + } + + /** The query of {@code page} without a name filter. */ + public NamedPageQuery(PageQuery page) { + this(page, Optional.empty()); + } + + /** The same query after {@code value}, how a walk moves to the next page. */ + public NamedPageQuery withCursor(PageCursor value) { + return new NamedPageQuery(page.withCursor(value), name); + } + + /** + * Applies {@link PageQuery#validate()} and the name rule of the server, so a refused query is never sent: a name of + * 1 to {@link #MAX_NAME_SIZE} bytes of UTF-8. + * + * @throws org.apache.iggy.exception.IggyValidationException invalid command naming the broken rule + */ + public void validate() { + page.validate(); + if (name.isEmpty()) { + return; + } + // A lone surrogate has no UTF-8 form, so the server would read another name. + if (!StandardCharsets.UTF_8.newEncoder().canEncode(name.get())) { + throw MetadataChangeEncoding.refused("The name must be valid Unicode text"); + } + int size = name.get().getBytes(StandardCharsets.UTF_8).length; + if (size < 1 || size > MAX_NAME_SIZE) { + throw MetadataChangeEncoding.refused( + "The name must be 1 to " + MAX_NAME_SIZE + " bytes of UTF-8, got " + size); + } + } + + /** The {@link PageQuery#httpQuery()} keys of the page, and the name filter last. */ + public Map<String, String> httpQuery() { + Map<String, String> pairs = new LinkedHashMap<>(page.httpQuery()); + name.ifPresent(value -> pairs.put("name", value)); + return pairs; + } +}
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/Page.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/Page.java new file mode 100644 index 0000000..ae320db --- /dev/null +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/Page.java
@@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.system; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * One page of a list. A page can be short or empty and still have a next cursor, so a walk ends at the first page + * without one. + * + * @param items the items in the order of the query + * @param next the cursor of the next page, empty on the last page + * @param <T> the item type + */ +public record Page<T>(List<T> items, Optional<PageCursor> next) { + + public Page { + items = List.copyOf(items); + Objects.requireNonNull(next, "next"); + } +}
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageCursor.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageCursor.java new file mode 100644 index 0000000..d82a8dc --- /dev/null +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageCursor.java
@@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.system; + +import java.util.Arrays; +import java.util.Optional; + +/** + * The position after which the next page of a list starts. Send it back as you got it, with the query that returned + * it: it holds no order, direction, filter or parent. Only the server reads its bytes, so the client keeps any 1 to + * {@link #MAX_SIZE} bytes as they came, and the server refuses a cursor that it cannot use. + * + * <p>The text form is {@code pg1_} followed by unpadded Base64url of the bytes. + */ +public final class PageCursor { + + /** Text prefix of a page cursor. */ + public static final String PREFIX = "pg1_"; + + /** Most bytes of a cursor: its length on the wire is one byte. */ + public static final int MAX_SIZE = 255; + + private static final int MAX_TEXT_LENGTH = PREFIX.length() + (MAX_SIZE * 4 + 2) / 3; + + private final byte[] bytes; + + private PageCursor(byte[] bytes) { + this.bytes = bytes; + } + + /** + * Parses the {@code pg1_} text form, refusing a wrong prefix, padding, the standard Base64 alphabet, non-canonical + * encodings, no bytes and more than {@link #MAX_SIZE} bytes. + * + * @throws org.apache.iggy.exception.IggyValidationException invalid command for any refused text + */ + public static PageCursor parse(String text) { + if (text == null || text.length() > MAX_TEXT_LENGTH || !text.startsWith(PREFIX)) { + throw MetadataChangeEncoding.refused("A page cursor is pg1_ followed by Base64url"); + } + return MetadataChangeEncoding.decodeCanonical(text.substring(PREFIX.length())) + .flatMap(PageCursor::fromBytes) + .orElseThrow(() -> MetadataChangeEncoding.refused( + "A page cursor is canonical Base64url of 1 to " + MAX_SIZE + " bytes")); + } + + /** The cursor of {@code bytes}, or empty when they are not 1 to {@link #MAX_SIZE} bytes. */ + public static Optional<PageCursor> fromBytes(byte[] bytes) { + if (bytes.length == 0 || bytes.length > MAX_SIZE) { + return Optional.empty(); + } + return Optional.of(new PageCursor(MetadataChangeEncoding.copy(bytes))); + } + + /** The bytes a list request carries. */ + public byte[] toBytes() { + return MetadataChangeEncoding.copy(bytes); + } + + /** The {@code pg1_} text form. */ + @Override + public String toString() { + return PREFIX + MetadataChangeEncoding.encode(bytes); + } + + @Override + public boolean equals(Object other) { + return other instanceof PageCursor cursor && Arrays.equals(bytes, cursor.bytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(bytes); + } +}
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageOrder.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageOrder.java new file mode 100644 index 0000000..8f23325 --- /dev/null +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageOrder.java
@@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.system; + +/** The order of a list page. */ +public enum PageOrder { + /** The numeric ids. */ + ID(0, "id"), + /** + * The creation order. Entities created at the same time keep the order of their ids. Partitions and consumer + * groups walk by id in this order too, because their ids follow creation. + */ + CREATED(1, "created"); + + private final int code; + private final String value; + + PageOrder(int code, String value) { + this.code = code; + this.value = value; + } + + public int asCode() { + return code; + } + + /** The name of the order in an HTTP query. */ + public String value() { + return value; + } +}
diff --git a/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageQuery.java b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageQuery.java new file mode 100644 index 0000000..8ab2d6e --- /dev/null +++ b/foreign/java/java-sdk/src/main/java/org/apache/iggy/system/PageQuery.java
@@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.system; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** + * One page request of a list command. To read the next page, send the same query with the {@link Page#next()} of the + * page as its cursor. The lists of named entities take a {@link NamedPageQuery}, which adds a name filter. + * + * @param order the order of the walk + * @param descending whether the walk starts at the end of the order + * @param limit items per page, 1 to 1000 + * @param cursor the next cursor of the previous page, empty for the first page + */ +public record PageQuery(PageOrder order, boolean descending, long limit, Optional<PageCursor> cursor) { + + /** Items per page when the caller does not say. */ + public static final long DEFAULT_LIMIT = 100; + + /** Most items one page returns. */ + public static final long MAX_LIMIT = 1000; + + public PageQuery { + Objects.requireNonNull(order, "order"); + Objects.requireNonNull(cursor, "cursor"); + } + + public static Builder builder() { + return new Builder(); + } + + /** The same query after {@code value}, how a walk moves to the next page. */ + public PageQuery withCursor(PageCursor value) { + return new PageQuery(order, descending, limit, Optional.of(value)); + } + + /** + * Applies the page rules of the server, so a refused query is never sent: a limit of 1 to {@link #MAX_LIMIT}. + * + * @throws org.apache.iggy.exception.IggyValidationException invalid command naming the broken rule + */ + public void validate() { + if (limit < 1 || limit > MAX_LIMIT) { + throw MetadataChangeEncoding.refused("The limit must be 1 to " + MAX_LIMIT + ", got " + limit); + } + } + + /** + * The query keys of an HTTP list route, in a stable order. They always hold the limit, so the server answers one + * page and not the whole list. + */ + public Map<String, String> httpQuery() { + Map<String, String> pairs = new LinkedHashMap<>(); + pairs.put("order", order.value()); + pairs.put("descending", Boolean.toString(descending)); + pairs.put("limit", Long.toString(limit)); + cursor.ifPresent(value -> pairs.put("cursor", value.toString())); + return pairs; + } + + /** Builds a query from the defaults: ascending id order, a limit of 100 and no cursor. */ + public static final class Builder { + private PageOrder order = PageOrder.ID; + private boolean descending; + private long limit = DEFAULT_LIMIT; + private Optional<PageCursor> cursor = Optional.empty(); + + private Builder() {} + + public Builder order(PageOrder value) { + order = value; + return this; + } + + public Builder descending(boolean value) { + descending = value; + return this; + } + + public Builder limit(long value) { + limit = value; + return this; + } + + public Builder cursor(PageCursor value) { + cursor = Optional.of(value); + return this; + } + + public PageQuery build() { + return new PageQuery(order, descending, limit, cursor); + } + } +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/ListPagesFixture.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/ListPagesFixture.java new file mode 100644 index 0000000..b1bbf88 --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/ListPagesFixture.java
@@ -0,0 +1,167 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy; + +import io.netty.buffer.ByteBuf; +import org.apache.iggy.consumergroup.ConsumerGroup; +import org.apache.iggy.identifier.StreamId; +import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.serde.BytesDeserializer; +import org.apache.iggy.stream.StreamBase; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageOrder; +import org.apache.iggy.system.PageQuery; +import org.apache.iggy.topic.Topic; +import org.apache.iggy.user.UserInfo; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; +import java.util.function.Function; + +/** The shared list page vectors that {@code core/common/examples/list_pages_fixtures.rs} writes. */ +public final class ListPagesFixture { + + private static final JsonNode ROOT = load(); + + private ListPagesFixture() {} + + public static JsonNode section(String name) { + return ROOT.get(name); + } + + public static JsonNode refused(String name) { + return ROOT.get("refused").get(name); + } + + /** The query a vector's {@code input} describes without its name, and without the page rules applied. */ + public static PageQuery query(JsonNode input) { + var builder = PageQuery.builder() + .order(PageOrder.valueOf(input.get("order").asString().toUpperCase(Locale.ROOT))) + .descending(input.get("descending").asBoolean()) + .limit(input.get("limit").asLong()); + if (!input.get("cursor").isNull()) { + builder.cursor(PageCursor.parse(input.get("cursor").asString())); + } + return builder.build(); + } + + /** The query a vector's {@code input} describes with its name, and without the page rules applied. */ + public static NamedPageQuery namedQuery(JsonNode input) { + JsonNode name = input.get("name"); + return new NamedPageQuery(query(input), name.isNull() ? Optional.empty() : Optional.of(name.asString())); + } + + public static Optional<StreamId> streamId(JsonNode input) { + return identifier(input.get("stream_id"), StreamId::of, StreamId::of); + } + + public static Optional<TopicId> topicId(JsonNode input) { + return identifier(input.get("topic_id"), TopicId::of, TopicId::of); + } + + public static Map<String, String> httpQuery(JsonNode vector) { + Map<String, String> pairs = new TreeMap<>(); + vector.get("http_query") + .properties() + .forEach(pair -> pairs.put(pair.getKey(), pair.getValue().asString())); + return pairs; + } + + /** Decodes a reply of {@code command} to the ids and names the vectors list. */ + public static Page<Item> readPage(String command, ByteBuf reply) { + Function<ByteBuf, Item> readItem = switch (command) { + case "get_streams" -> + body -> { + StreamBase stream = BytesDeserializer.readStreamBase(body); + return new Item(stream.id(), Optional.of(stream.name())); + }; + case "get_topics" -> + body -> { + Topic topic = BytesDeserializer.readTopic(body); + return new Item(topic.id(), Optional.of(topic.name())); + }; + case "get_partitions" -> + body -> { + Partition partition = BytesDeserializer.readPartition(body); + return new Item(partition.id(), Optional.empty()); + }; + case "get_consumer_groups" -> + body -> { + ConsumerGroup group = BytesDeserializer.readConsumerGroup(body); + return new Item(group.id(), Optional.of(group.name())); + }; + case "get_users" -> + body -> { + UserInfo user = BytesDeserializer.readUserInfo(body); + return new Item(user.id(), Optional.of(user.username())); + }; + default -> throw new IllegalArgumentException("unknown command " + command); + }; + return BytesDeserializer.readPage(reply, readItem); + } + + /** The {@code items} of a response vector. */ + public static List<Item> items(JsonNode vector) { + List<Item> items = new ArrayList<>(); + for (JsonNode item : vector.get("items")) { + JsonNode name = item.get("name"); + items.add( + new Item(item.get("id").asLong(), name.isNull() ? Optional.empty() : Optional.of(name.asString()))); + } + return items; + } + + private static <T> Optional<T> identifier(JsonNode id, Function<Long, T> numeric, Function<String, T> named) { + if (id.isNull()) { + return Optional.empty(); + } + JsonNode value = id.get("value"); + return Optional.of( + id.get("kind").asString().equals("numeric") + ? numeric.apply(value.asLong()) + : named.apply(value.asString())); + } + + private static JsonNode load() { + try (InputStream fixture = ListPagesFixture.class.getResourceAsStream("/list_pages.json")) { + if (fixture == null) { + throw new IllegalStateException("list_pages.json is not on the test classpath"); + } + return JsonMapper.builder().build().readTree(fixture); + } catch (IOException unreadable) { + throw new UncheckedIOException(unreadable); + } + } + + /** The id and the name of one list item. A partition has no name. */ + public record Item(long id, Optional<String> name) {} +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/ProtocolParityTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/ProtocolParityTest.java index ad03ab9..499f473 100644 --- a/foreign/java/java-sdk/src/test/java/org/apache/iggy/ProtocolParityTest.java +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/ProtocolParityTest.java
@@ -100,6 +100,7 @@ Map.entry(CommandCode.Topic.DELETE, "DELETE_TOPIC_CODE"), Map.entry(CommandCode.Partition.CREATE, "CREATE_PARTITIONS_CODE"), Map.entry(CommandCode.Partition.DELETE, "DELETE_PARTITIONS_CODE"), + Map.entry(CommandCode.Partition.GET_ALL, "GET_PARTITIONS_CODE"), Map.entry(CommandCode.ConsumerGroup.GET, "GET_CONSUMER_GROUP_CODE"), Map.entry(CommandCode.ConsumerGroup.GET_ALL, "GET_CONSUMER_GROUPS_CODE"), Map.entry(CommandCode.ConsumerGroup.CREATE, "CREATE_CONSUMER_GROUP_CODE"),
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/async/AsyncListPagesTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/async/AsyncListPagesTest.java new file mode 100644 index 0000000..9d7e849 --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/async/AsyncListPagesTest.java
@@ -0,0 +1,217 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.async; + +import org.apache.iggy.client.BaseIntegrationTest; +import org.apache.iggy.client.async.tcp.AsyncIggyTcpClient; +import org.apache.iggy.consumergroup.ConsumerGroup; +import org.apache.iggy.exception.IggyErrorCode; +import org.apache.iggy.exception.IggyValidationException; +import org.apache.iggy.identifier.StreamId; +import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.stream.StreamBase; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageOrder; +import org.apache.iggy.system.PageQuery; +import org.apache.iggy.topic.Topic; +import org.apache.iggy.user.UserInfo; +import org.apache.iggy.user.UserStatus; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import static org.apache.iggy.TestConstants.PERSISTED_TOPIC_OPTIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** The page methods of the async TCP client against a live server. */ +class AsyncListPagesTest extends BaseIntegrationTest { + + private static final int TIMEOUT_SECONDS = 5; + + /** A page cursor of a kind that no server writes. The client sends it and the server refuses it. */ + private static final String UNKNOWN_KIND_CURSOR = "pg1_AwcAAAAAAAAA"; + + private static final long WALK_LIMIT = 2; + private static final long PARTITIONS = 3; + private static final String PASSWORD = "list-pages-password"; + + private final List<Long> streams = new ArrayList<>(); + private final List<Long> users = new ArrayList<>(); + private AsyncIggyTcpClient client; + + @BeforeEach + void setUp() throws Exception { + client = AsyncIggyTcpClient.builder() + .host(serverHost()) + .port(serverTcpPort()) + .build(); + client.connect().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + await(client.users().login("iggy", "iggy")); + } + + @AfterEach + void tearDown() throws Exception { + for (Long stream : streams) { + client.streams().deleteStream(stream).exceptionally(ignored -> null).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + for (Long user : users) { + client.users().deleteUser(user).exceptionally(ignored -> null).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + client.close().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + + @Test + void givenThreeStreamsWhenWalkingTheirPagesShouldReturnThemInTheOrderOfTheQuery() throws Exception { + String prefix = unique("pages-walk"); + List<Long> created = new ArrayList<>(); + for (String suffix : List.of("-a", "-b", "-c")) { + created.add(createStream(prefix + suffix)); + } + + assertThat(walk(PageOrder.ID, false, prefix)) + .isEqualTo(created.stream().sorted().toList()); + assertThat(walk(PageOrder.ID, true, prefix)) + .isEqualTo(created.stream().sorted(Comparator.reverseOrder()).toList()); + assertThat(walk(PageOrder.CREATED, false, prefix)).isEqualTo(created); + assertThat(await(client.streams().getStreams())) + .extracting(StreamBase::id) + .containsAll(created); + } + + @Test + void givenATopicWithThreePartitionsWhenReadingPagesShouldReturnEveryPartition() throws Exception { + StreamId stream = StreamId.of(createStream(unique("pages-partitions"))); + TopicId topic = + TopicId.of(await(client.topics().createTopic(stream, "events", PARTITIONS, PERSISTED_TOPIC_OPTIONS)) + .id()); + PageQuery query = PageQuery.builder().limit(WALK_LIMIT).build(); + + Page<Partition> first = await(client.partitions().getPartitionsPage(stream, topic, query)); + Page<Partition> second = await(client.partitions() + .getPartitionsPage(stream, topic, query.withCursor(first.next().orElseThrow()))); + + assertThat(first.items()).extracting(Partition::id).containsExactly(0L, 1L); + assertThat(second.items()).extracting(Partition::id).containsExactly(2L); + assertThat(second.next()).isEmpty(); + } + + @Test + void givenANameFilterWhenReadingPagesShouldKeepOnlyTheMatchingEntries() throws Exception { + StreamId stream = StreamId.of(createStream(unique("pages-names"))); + TopicId topic = + TopicId.of(await(client.topics().createTopic(stream, "sensor-readings", 1L, PERSISTED_TOPIC_OPTIONS)) + .id()); + await(client.topics().createTopic(stream, "events", 1L, PERSISTED_TOPIC_OPTIONS)); + await(client.consumerGroups().createConsumerGroup(stream, topic, "billing")); + await(client.consumerGroups().createConsumerGroup(stream, topic, "audit")); + String username = unique("pages-user"); + users.add(await(client.users().createUser(username, PASSWORD, UserStatus.Active, Optional.empty())) + .id()); + + Page<Topic> topics = await(client.topics().getTopicsPage(stream, named("sensor"))); + Page<ConsumerGroup> groups = await(client.consumerGroups().getConsumerGroupsPage(stream, topic, named("bill"))); + Page<UserInfo> found = await(client.users().getUsersPage(named(username))); + + assertThat(topics.items()).extracting(Topic::name).containsExactly("sensor-readings"); + assertThat(groups.items()).extracting(ConsumerGroup::name).containsExactly("billing"); + assertThat(found.items()).extracting(UserInfo::username).containsExactly(username); + assertThat(List.of(topics.next(), groups.next(), found.next())).containsOnly(Optional.empty()); + } + + @Test + void givenQueriesTheServerCannotServeWhenReadingPagesShouldRefuseThemAndStayUsable() throws Exception { + StreamId stream = StreamId.of(createStream(unique("pages-refused"))); + TopicId topic = TopicId.of(await(client.topics().createTopic(stream, "events", 1L, PERSISTED_TOPIC_OPTIONS)) + .id()); + + assertRefused(client.streams() + .getStreamsPage(new NamedPageQuery(PageQuery.builder() + .cursor(PageCursor.parse(UNKNOWN_KIND_CURSOR)) + .build()))); + + assertThat(await(client.partitions() + .getPartitionsPage( + stream, topic, PageQuery.builder().build())) + .items()) + .extracting(Partition::id) + .containsExactly(0L); + } + + /** Reads the streams that hold {@code name} in pages of two and checks that the second page is the last. */ + private List<Long> walk(PageOrder order, boolean descending, String name) throws Exception { + NamedPageQuery query = new NamedPageQuery( + PageQuery.builder() + .order(order) + .descending(descending) + .limit(WALK_LIMIT) + .build(), + Optional.of(name)); + Page<StreamBase> first = await(client.streams().getStreamsPage(query)); + Page<StreamBase> second = await( + client.streams().getStreamsPage(query.withCursor(first.next().orElseThrow()))); + + assertThat(first.items()).hasSize((int) WALK_LIMIT); + assertThat(second.next()).isEmpty(); + return Stream.concat(first.items().stream(), second.items().stream()) + .map(StreamBase::id) + .toList(); + } + + private long createStream(String name) throws Exception { + long id = await(client.streams().createStream(name)).id(); + streams.add(id); + return id; + } + + private static NamedPageQuery named(String name) { + return new NamedPageQuery(PageQuery.builder().build(), Optional.of(name)); + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID(); + } + + private static void assertRefused(CompletableFuture<?> page) { + assertThatThrownBy(() -> page.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .cause() + .isInstanceOfSatisfying( + IggyValidationException.class, + refusal -> assertThat(refusal.getErrorCode()).isEqualTo(IggyErrorCode.INVALID_COMMAND)); + } + + private static <T> T await(CompletableFuture<T> future) throws Exception { + return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/async/tcp/ListPagesWalkTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/async/tcp/ListPagesWalkTest.java new file mode 100644 index 0000000..777e1df --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/async/tcp/ListPagesWalkTest.java
@@ -0,0 +1,388 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.async.tcp; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.apache.iggy.client.async.tcp.AsyncIggyTcpClientEndpointFailoverTest.MockNode; +import org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.Request; +import org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.Response; +import org.apache.iggy.client.async.tcp.vsr.VsrOperation; +import org.apache.iggy.consumergroup.ConsumerGroup; +import org.apache.iggy.exception.IggyErrorCode; +import org.apache.iggy.exception.IggyMalformedResponseException; +import org.apache.iggy.exception.IggyTimeoutException; +import org.apache.iggy.exception.IggyValidationException; +import org.apache.iggy.identifier.Identifier; +import org.apache.iggy.identifier.StreamId; +import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.serde.BytesSerializer; +import org.apache.iggy.serde.CommandCode; +import org.apache.iggy.stream.StreamBase; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageQuery; +import org.apache.iggy.topic.Topic; +import org.apache.iggy.user.UserInfo; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; + +import java.net.InetAddress; +import java.net.ServerSocket; +import java.time.Duration; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.apache.iggy.ListPagesFixture.section; +import static org.apache.iggy.MetadataChangesFixture.buffer; +import static org.apache.iggy.MetadataChangesFixture.bytes; +import static org.apache.iggy.MetadataChangesFixture.find; +import static org.apache.iggy.ResourceOptionsFixture.hex; +import static org.apache.iggy.client.async.AsyncClientIntegrationTest.field; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientFetchMessagesTest.signedIn; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientFetchMessagesTest.singleNode; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientFetchMessagesTest.unexpected; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.GET_CLUSTER_METADATA_CODE; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.OPERATION_NON_REPLICATED; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.OPERATION_REGISTER; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.assertServerError; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.registerBody; +import static org.apache.iggy.client.async.tcp.AsyncIggyTcpClientTransientFailoverTest.singleNodeMetadata; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** The page walk of the whole-list methods and the refusal of a broken query, against one fake node. */ +class ListPagesWalkTest { + + private static final Duration TIMEOUT = Duration.ofSeconds(5); + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(2); + // One page fits in the request timeout and two do not. + private static final Duration PAGE_DELAY = REQUEST_TIMEOUT.multipliedBy(3).dividedBy(5); + // A sign-in needs another loop than the one a paused walk holds. + private static final int IO_THREADS = 4; + private static final HexFormat HEX = HexFormat.of(); + + /** {@code [next_len = 0][count = 0]}: an empty last page. */ + private static final String EMPTY_LAST_PAGE_HEX = "0000000000"; + + private static final StreamId STREAM = StreamId.of(7L); + private static final TopicId TOPIC = TopicId.of(3L); + + /** + * The first page of each list, from the shared vectors. Each has two items and a next cursor. The second page holds + * the same two items without the cursor, so a walk that drops a page fails. + */ + private static final Map<Integer, String> FIRST_PAGES = Map.of( + CommandCode.Stream.GET_ALL.getValue(), "streams_with_next", + CommandCode.Topic.GET_ALL.getValue(), "topics_created_descending_with_next", + CommandCode.ConsumerGroup.GET_ALL.getValue(), "consumer_groups_with_next", + CommandCode.User.GET_ALL.getValue(), "users_with_next"); + + private static final NamedPageQuery WHOLE_LIST = + new NamedPageQuery(PageQuery.builder().limit(PageQuery.MAX_LIMIT).build()); + + private static final NamedPageQuery FIRST_PAGE = + new NamedPageQuery(PageQuery.builder().build()); + + @Test + void givenTwoPagesWhenReadingWholeListsShouldSendTheNextCursorAndJoinThePages() throws Exception { + assertThat(hex(BytesSerializer.toPageRequest(WHOLE_LIST))) + .isEqualTo(find(section("requests"), "streams_whole_list_walk") + .get("request_hex") + .asString()); + List<Request> lists = new CopyOnWriteArrayList<>(); + try (ServerSocket socket = new ServerSocket(0, 4, InetAddress.getLoopbackAddress())) { + CompletableFuture<Void> served = singleNode(socket, request -> { + if (request.operation() != OPERATION_NON_REPLICATED + || !FIRST_PAGES.containsKey(request.commandCode())) { + return unexpected(request); + } + boolean first = lists.stream().noneMatch(seen -> seen.commandCode() == request.commandCode()); + lists.add(request); + return Response.success( + OPERATION_NON_REPLICATED, + first + ? reply(FIRST_PAGES.get(request.commandCode())) + : lastPage(FIRST_PAGES.get(request.commandCode()))); + }); + AsyncIggyTcpClient client = signedIn(socket); + try { + assertThat(await(client.streams().getStreams())) + .extracting(StreamBase::id) + .containsExactly(1L, 4L, 1L, 4L); + assertThat(await(client.topics().getTopics(STREAM))) + .extracting(Topic::id) + .containsExactly(3L, 1L, 3L, 1L); + assertThat(await(client.consumerGroups().getConsumerGroups(STREAM, TOPIC))) + .extracting(ConsumerGroup::id) + .containsExactly(1L, 3L, 1L, 3L); + assertThat(await(client.users().getUsers())) + .extracting(UserInfo::id) + .containsExactly(1L, 2L, 1L, 2L); + } finally { + client.close().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + served.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + + assertThat(lists.stream().map(request -> HEX.formatHex(request.body()))) + .containsExactly( + firstPage(), + secondPage(CommandCode.Stream.GET_ALL.getValue()), + firstPage(STREAM), + secondPage(CommandCode.Topic.GET_ALL.getValue(), STREAM), + firstPage(STREAM, TOPIC), + secondPage(CommandCode.ConsumerGroup.GET_ALL.getValue(), STREAM, TOPIC), + firstPage(), + secondPage(CommandCode.User.GET_ALL.getValue())); + } + + @Test + void givenAPageThatRepeatsItsCursorWhenReadingAWholeListShouldFailAsMalformed() throws Exception { + List<Request> lists = new CopyOnWriteArrayList<>(); + try (ServerSocket socket = new ServerSocket(0, 4, InetAddress.getLoopbackAddress())) { + CompletableFuture<Void> served = singleNode(socket, request -> { + if (!request.is(CommandCode.Stream.GET_ALL.getValue(), OPERATION_NON_REPLICATED)) { + return unexpected(request); + } + lists.add(request); + // Bounded, so a walk without the guard ends on the third page and does not loop. + return Response.success( + OPERATION_NON_REPLICATED, + lists.size() <= 2 ? reply("streams_with_next") : lastPage("streams_with_next")); + }); + AsyncIggyTcpClient client = signedIn(socket); + try { + assertThatThrownBy(() -> await(client.streams().getStreams())) + .cause() + .isInstanceOf(IggyMalformedResponseException.class); + } finally { + client.close().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + served.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + + assertThat(lists.stream().map(request -> HEX.formatHex(request.body()))) + .containsExactly(firstPage(), secondPage(CommandCode.Stream.GET_ALL.getValue())); + } + + @Test + void givenABrokenQueryWhenReadingAPageShouldFailBeforeSendingIt() throws Exception { + PageQuery broken = PageQuery.builder().limit(0).build(); + NamedPageQuery brokenNamed = new NamedPageQuery(broken); + List<Request> lists = new CopyOnWriteArrayList<>(); + try (ServerSocket socket = new ServerSocket(0, 4, InetAddress.getLoopbackAddress())) { + CompletableFuture<Void> served = singleNode(socket, request -> { + if (!request.is(CommandCode.Stream.GET_ALL.getValue(), OPERATION_NON_REPLICATED)) { + return unexpected(request); + } + lists.add(request); + return Response.success(OPERATION_NON_REPLICATED, buffer(EMPTY_LAST_PAGE_HEX)); + }); + AsyncIggyTcpClient client = signedIn(socket); + try { + List<CompletableFuture<?>> refused = List.of( + client.streams().getStreamsPage(brokenNamed), + client.topics().getTopicsPage(STREAM, brokenNamed), + client.partitions().getPartitionsPage(STREAM, TOPIC, broken), + client.consumerGroups().getConsumerGroupsPage(STREAM, TOPIC, brokenNamed), + client.users().getUsersPage(brokenNamed)); + for (CompletableFuture<?> page : refused) { + assertThat(page).isCompletedExceptionally(); + assertThatThrownBy(() -> await(page)) + .cause() + .isInstanceOfSatisfying( + IggyValidationException.class, + refusal -> assertThat(refusal.getErrorCode()) + .isEqualTo(IggyErrorCode.INVALID_COMMAND)); + } + + assertThat(await(client.streams().getStreamsPage(FIRST_PAGE)).next()) + .isEmpty(); + } finally { + client.close().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + served.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + + assertThat(lists.stream().map(request -> HEX.formatHex(request.body()))) + .containsExactly(hex(BytesSerializer.toPageRequest(FIRST_PAGE))); + } + + /** + * The walk is one call, so a caller sign-in after page 1 ends it with 40 instead of reading page 2 as the new user. + * The walk holds the event loop of its connection while the caller signs in, so the caller reconnects first, as + * in {@code AsyncIggyTcpClientSessionRulesTest}. + */ + @Test + void givenACallerSignInBetweenTwoPagesWhenReadingAWholeListShouldFailAsUnauthenticated() throws Exception { + List<Request> lists = new CopyOnWriteArrayList<>(); + AtomicInteger registrations = new AtomicInteger(); + try (ServerSocket socket = new ServerSocket(0, 4, InetAddress.getLoopbackAddress())) { + MockNode node = MockNode.serve(socket, request -> { + if (request.operation() == OPERATION_REGISTER) { + return Response.success(OPERATION_REGISTER, registerBody(registrations.incrementAndGet())); + } + if (request.operation() == VsrOperation.LOGOUT) { + return Response.success(VsrOperation.LOGOUT, Unpooled.EMPTY_BUFFER); + } + if (request.is(GET_CLUSTER_METADATA_CODE, OPERATION_NON_REPLICATED)) { + return Response.success(OPERATION_NON_REPLICATED, singleNodeMetadata(socket.getLocalPort())); + } + if (!request.is(CommandCode.Stream.GET_ALL.getValue(), OPERATION_NON_REPLICATED)) { + return unexpected(request); + } + lists.add(request); + return Response.success( + OPERATION_NON_REPLICATED, + lists.size() == 1 ? reply("streams_with_next") : lastPage("streams_with_next")); + }); + AsyncIggyTcpClient client = client(socket); + CompletableFuture<Void> paused = new CompletableFuture<>(); + CompletableFuture<Void> resume = new CompletableFuture<>(); + try { + client.connect().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + client.users().login("alice", "alice-password").get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + @SuppressWarnings("unchecked") + var connection = (AtomicReference<AsyncTcpConnection>) field(client, "connection"); + AtomicBoolean held = new AtomicBoolean(); + var streams = new StreamsTcpClient(() -> { + if (!lists.isEmpty() && held.compareAndSet(false, true)) { + paused.complete(null); + resume.join(); + } + return connection.get(); + }); + + var walk = streams.getStreams(); + paused.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + client.connect().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + client.users().login("bob", "bob-password").get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + resume.complete(null); + + assertServerError(walk, IggyErrorCode.UNAUTHENTICATED.getCode()); + assertThat(lists).hasSize(1); + } finally { + resume.complete(null); + client.close().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + node.close(); + } + } + } + + @Test + void givenPagesThatTogetherOutlastTheRequestTimeoutWhenReadingAWholeListShouldTimeOut() throws Exception { + List<Request> lists = new CopyOnWriteArrayList<>(); + try (ServerSocket socket = new ServerSocket(0, 4, InetAddress.getLoopbackAddress())) { + singleNode(socket, request -> { + if (!request.is(CommandCode.Stream.GET_ALL.getValue(), OPERATION_NON_REPLICATED)) { + return unexpected(request); + } + lists.add(request); + try { + Thread.sleep(PAGE_DELAY.toMillis()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + return Response.success( + OPERATION_NON_REPLICATED, + lists.size() == 1 ? reply("streams_with_next") : lastPage("streams_with_next")); + }); + AsyncIggyTcpClient client = client(socket); + try { + client.connect().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + client.users().login("alice", "alice-password").get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + + assertThatThrownBy(() -> await(client.streams().getStreams())) + .cause() + .isInstanceOf(IggyTimeoutException.class); + assertThat(lists).hasSize(2); + } finally { + client.close().get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } + } + } + + @Test + void givenAFailedPageWhenReadingAWholeListShouldPassItsOwnErrorToTheCaller() { + PageCursor next = PageCursor.parse( + find(section("responses"), "streams_with_next").get("next").asString()); + IllegalStateException refused = new IllegalStateException("page refused"); + + CompletableFuture<List<Long>> firstFails = + PageReads.readWholeList(query -> CompletableFuture.failedFuture(refused)); + CompletableFuture<List<Long>> secondFails = + PageReads.readWholeList(query -> query.cursor().isEmpty() + ? CompletableFuture.completedFuture(new Page<>(List.of(1L), Optional.of(next))) + : CompletableFuture.failedFuture(refused)); + + for (CompletableFuture<List<Long>> walk : List.of(firstFails, secondFails)) { + assertThat(walk.handle((items, error) -> error).join()).isSameAs(refused); + } + } + + private static AsyncIggyTcpClient client(ServerSocket socket) { + return AsyncIggyTcpClient.builder() + .host(socket.getInetAddress().getHostAddress()) + .port(socket.getLocalPort()) + .ioThreads(IO_THREADS) + .requestTimeout(REQUEST_TIMEOUT) + .heartbeatInterval(Duration.ofMinutes(1)) + .build(); + } + + private static ByteBuf reply(String vectorCase) { + return buffer(find(section("responses"), vectorCase).get("response_hex").asString()); + } + + /** The reply of {@code vectorCase} with its next cursor cut out: the same items on the last page. */ + private static ByteBuf lastPage(String vectorCase) { + byte[] page = + bytes(find(section("responses"), vectorCase).get("response_hex").asString()); + int nextSize = Byte.toUnsignedInt(page[0]); + byte[] last = new byte[page.length - nextSize]; + System.arraycopy(page, 1 + nextSize, last, 1, last.length - 1); + return Unpooled.wrappedBuffer(last); + } + + private static String firstPage(Identifier... parents) { + return hex(BytesSerializer.toPageRequest(WHOLE_LIST, parents)); + } + + /** The second request of a walk carries the next cursor of the first page of {@code command}. */ + private static String secondPage(int command, Identifier... parents) { + JsonNode first = find(section("responses"), FIRST_PAGES.get(command)); + PageCursor next = PageCursor.parse(first.get("next").asString()); + return hex(BytesSerializer.toPageRequest(WHOLE_LIST.withCursor(next), parents)); + } + + private static <T> T await(CompletableFuture<T> future) throws Exception { + return future.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); + } +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/ListPagesClientBaseTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/ListPagesClientBaseTest.java new file mode 100644 index 0000000..863d96e --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/ListPagesClientBaseTest.java
@@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.blocking; + +import org.apache.iggy.consumergroup.ConsumerGroup; +import org.apache.iggy.exception.IggyErrorCode; +import org.apache.iggy.exception.IggyValidationException; +import org.apache.iggy.identifier.StreamId; +import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.partition.Partition; +import org.apache.iggy.stream.StreamBase; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageOrder; +import org.apache.iggy.system.PageQuery; +import org.apache.iggy.topic.Topic; +import org.apache.iggy.user.UserInfo; +import org.apache.iggy.user.UserStatus; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Stream; + +import static org.apache.iggy.TestConstants.PERSISTED_TOPIC_OPTIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** The page methods of a blocking client against a live server. */ +public abstract class ListPagesClientBaseTest extends IntegrationTest { + + /** A page cursor of a kind that no server writes. The client sends it and the server refuses it. */ + private static final String UNKNOWN_KIND_CURSOR = "pg1_AwcAAAAAAAAA"; + + private static final long WALK_LIMIT = 2; + private static final long PARTITIONS = 3; + private static final String PASSWORD = "list-pages-password"; + + @BeforeEach + void beforeEachListPagesTest() { + login(); + } + + @Test + void givenThreeStreamsWhenWalkingTheirPagesShouldReturnThemInTheOrderOfTheQuery() { + String prefix = unique("pages-walk"); + List<Long> created = new ArrayList<>(); + for (String suffix : List.of("-a", "-b", "-c")) { + long id = client.streams().createStream(prefix + suffix).id(); + trackStream(id); + created.add(id); + } + assertThat(walk(PageOrder.ID, false, prefix)) + .isEqualTo(created.stream().sorted().toList()); + assertThat(walk(PageOrder.ID, true, prefix)) + .isEqualTo(created.stream().sorted(Comparator.reverseOrder()).toList()); + assertThat(walk(PageOrder.CREATED, false, prefix)).isEqualTo(created); + assertThat(client.streams().getStreams()).extracting(StreamBase::id).containsAll(created); + } + + @Test + void givenATopicWithThreePartitionsWhenReadingPagesShouldReturnEveryPartition() { + StreamId stream = StreamId.of(createStream(unique("pages-partitions"))); + TopicId topic = TopicId.of(client.topics() + .createTopic(stream, "events", PARTITIONS, PERSISTED_TOPIC_OPTIONS) + .id()); + PageQuery query = PageQuery.builder().limit(WALK_LIMIT).build(); + + Page<Partition> first = client.partitions().getPartitionsPage(stream, topic, query); + Page<Partition> second = client.partitions() + .getPartitionsPage(stream, topic, query.withCursor(first.next().orElseThrow())); + + assertThat(first.items()).extracting(Partition::id).containsExactly(0L, 1L); + assertThat(second.items()).extracting(Partition::id).containsExactly(2L); + assertThat(second.next()).isEmpty(); + } + + @Test + void givenANameFilterWhenReadingPagesShouldKeepOnlyTheMatchingEntries() { + StreamId stream = StreamId.of(createStream(unique("pages-names"))); + TopicId topic = TopicId.of(client.topics() + .createTopic(stream, "sensor-readings", 1L, PERSISTED_TOPIC_OPTIONS) + .id()); + client.topics().createTopic(stream, "events", 1L, PERSISTED_TOPIC_OPTIONS); + client.consumerGroups().createConsumerGroup(stream, topic, "billing"); + client.consumerGroups().createConsumerGroup(stream, topic, "audit"); + String username = unique("pages-user"); + trackUser(client.users() + .createUser(username, PASSWORD, UserStatus.Active, Optional.empty()) + .id()); + + Page<Topic> topics = client.topics().getTopicsPage(stream, named("sensor")); + Page<ConsumerGroup> groups = client.consumerGroups().getConsumerGroupsPage(stream, topic, named("bill")); + Page<UserInfo> users = client.users().getUsersPage(named(username)); + + assertThat(topics.items()).extracting(Topic::name).containsExactly("sensor-readings"); + assertThat(groups.items()).extracting(ConsumerGroup::name).containsExactly("billing"); + assertThat(users.items()).extracting(UserInfo::username).containsExactly(username); + assertThat(List.of(topics.next(), groups.next(), users.next())).containsOnly(Optional.empty()); + } + + @Test + void givenQueriesTheServerCannotServeWhenReadingPagesShouldRefuseThemAndStayUsable() { + StreamId stream = StreamId.of(createStream(unique("pages-refused"))); + TopicId topic = TopicId.of(client.topics() + .createTopic(stream, "events", 1L, PERSISTED_TOPIC_OPTIONS) + .id()); + + assertRefused(() -> client.streams() + .getStreamsPage(new NamedPageQuery(PageQuery.builder() + .cursor(PageCursor.parse(UNKNOWN_KIND_CURSOR)) + .build()))); + + assertThat(client.partitions() + .getPartitionsPage(stream, topic, PageQuery.builder().build()) + .items()) + .extracting(Partition::id) + .containsExactly(0L); + } + + /** Reads the streams that hold {@code name} in pages of two and checks that the second page is the last. */ + private List<Long> walk(PageOrder order, boolean descending, String name) { + NamedPageQuery query = new NamedPageQuery( + PageQuery.builder() + .order(order) + .descending(descending) + .limit(WALK_LIMIT) + .build(), + Optional.of(name)); + Page<StreamBase> first = client.streams().getStreamsPage(query); + Page<StreamBase> second = + client.streams().getStreamsPage(query.withCursor(first.next().orElseThrow())); + + assertThat(first.items()).hasSize((int) WALK_LIMIT); + assertThat(second.next()).isEmpty(); + return Stream.concat(first.items().stream(), second.items().stream()) + .map(StreamBase::id) + .toList(); + } + + private long createStream(String name) { + long id = client.streams().createStream(name).id(); + trackStream(id); + return id; + } + + private static NamedPageQuery named(String name) { + return new NamedPageQuery(PageQuery.builder().build(), Optional.of(name)); + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID(); + } + + private static void assertRefused(ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOfSatisfying( + IggyValidationException.class, + refusal -> assertThat(refusal.getErrorCode()).isEqualTo(IggyErrorCode.INVALID_COMMAND)); + } +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/http/ListPagesHttpClientTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/http/ListPagesHttpClientTest.java new file mode 100644 index 0000000..90eb73e --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/http/ListPagesHttpClientTest.java
@@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.blocking.http; + +import org.apache.iggy.client.blocking.IggyBaseClient; +import org.apache.iggy.client.blocking.ListPagesClientBaseTest; + +class ListPagesHttpClientTest extends ListPagesClientBaseTest { + + @Override + protected IggyBaseClient getClient() { + return HttpClientFactory.create(serverHost(), serverHttpPort()); + } +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/http/ListPagesHttpTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/http/ListPagesHttpTest.java new file mode 100644 index 0000000..4bad73d --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/http/ListPagesHttpTest.java
@@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.blocking.http; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import org.apache.iggy.exception.IggyErrorCode; +import org.apache.iggy.exception.IggyMalformedResponseException; +import org.apache.iggy.exception.IggyValidationException; +import org.apache.iggy.identifier.StreamId; +import org.apache.iggy.identifier.TopicId; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageQuery; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + +import static org.apache.iggy.ListPagesFixture.httpQuery; +import static org.apache.iggy.ListPagesFixture.namedQuery; +import static org.apache.iggy.ListPagesFixture.query; +import static org.apache.iggy.ListPagesFixture.section; +import static org.apache.iggy.ListPagesFixture.streamId; +import static org.apache.iggy.ListPagesFixture.topicId; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** The page methods of the HTTP client against a loopback peer that records each request. */ +class ListPagesHttpTest { + + private static final String CURSOR = "pg1_AQcAAAAAAAAA"; + private static final String PAGE_WITH_NEXT = "{\"items\":[],\"next\":\"" + CURSOR + "\"}"; + private static final String LAST_PAGE = "{\"items\":[]}"; + private static final String PAGE_WITH_FOREIGN_NEXT = "{\"items\":[],\"next\":\"mc1_AQ\"}"; + private static final StreamId STREAM = StreamId.of(1L); + private static final TopicId TOPIC = TopicId.of(1L); + private static final NamedPageQuery FIRST_PAGE = + new NamedPageQuery(PageQuery.builder().build()); + + private final List<String> paths = new CopyOnWriteArrayList<>(); + private final List<String> queries = new CopyOnWriteArrayList<>(); + private final Queue<String> answers = new ConcurrentLinkedQueue<>(); + + @Test + void givenSharedRequestsWhenReadingPagesShouldSendExactlyTheirHttpQuery() throws IOException { + List<JsonNode> vectors = new ArrayList<>(); + section("requests").forEach(vectors::add); + vectors.forEach(vector -> answers.add(LAST_PAGE)); + + withClient(client -> vectors.forEach(vector -> read(client, vector))); + + assertThat(paths).hasSize(vectors.size()); + for (int index = 0; index < vectors.size(); index++) { + JsonNode vector = vectors.get(index); + String name = vector.get("case").asString(); + assertThat(paths.get(index)).as(name).isEqualTo(route(vector)); + assertThat(decode(queries.get(index))).as(name).isEqualTo(httpQuery(vector)); + } + } + + @Test + void givenEachPageShapeWhenReadingShouldKeepTheNextCursorOnlyWhenSent() throws IOException { + answers.addAll(List.of(PAGE_WITH_NEXT, LAST_PAGE, PAGE_WITH_FOREIGN_NEXT)); + List<Page<?>> pages = new ArrayList<>(); + + withClient(client -> { + pages.add(client.streams().getStreamsPage(FIRST_PAGE)); + pages.add(client.streams().getStreamsPage(FIRST_PAGE)); + assertThatThrownBy(() -> client.streams().getStreamsPage(FIRST_PAGE)) + .isInstanceOf(IggyMalformedResponseException.class); + }); + + assertThat(pages.get(0).next()).contains(PageCursor.parse(CURSOR)); + assertThat(pages.get(1).next()).isEmpty(); + } + + @Test + void givenABrokenQueryWhenReadingAPageShouldFailBeforeSendingIt() throws IOException { + PageQuery broken = PageQuery.builder().limit(0).build(); + NamedPageQuery brokenNamed = new NamedPageQuery(broken); + + withClient(client -> { + assertRefused(() -> client.streams().getStreamsPage(brokenNamed)); + assertRefused(() -> client.topics().getTopicsPage(STREAM, brokenNamed)); + assertRefused(() -> client.partitions().getPartitionsPage(STREAM, TOPIC, broken)); + assertRefused(() -> client.consumerGroups().getConsumerGroupsPage(STREAM, TOPIC, brokenNamed)); + assertRefused(() -> client.users().getUsersPage(brokenNamed)); + }); + + assertThat(paths).isEmpty(); + } + + private void withClient(Consumer<IggyHttpClient> calls) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext("/", this::answer); + server.start(); + try (var client = + new IggyHttpClient("http://" + InetAddress.getLoopbackAddress().getHostAddress() + ":" + + server.getAddress().getPort())) { + calls.accept(client); + } finally { + server.stop(0); + } + } + + private void answer(HttpExchange exchange) throws IOException { + paths.add(exchange.getRequestURI().getPath()); + queries.add(exchange.getRequestURI().getRawQuery()); + byte[] body = answers.remove().getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + } + + private static void read(IggyHttpClient client, JsonNode vector) { + JsonNode input = vector.get("input"); + switch (vector.get("command").asString()) { + case "get_streams" -> client.streams().getStreamsPage(namedQuery(input)); + case "get_topics" -> client.topics().getTopicsPage(streamOf(input), namedQuery(input)); + case "get_partitions" -> + client.partitions().getPartitionsPage(streamOf(input), topicOf(input), query(input)); + case "get_consumer_groups" -> + client.consumerGroups().getConsumerGroupsPage(streamOf(input), topicOf(input), namedQuery(input)); + case "get_users" -> client.users().getUsersPage(namedQuery(input)); + default -> throw new IllegalArgumentException("unknown command " + vector.get("command")); + } + } + + private static String route(JsonNode vector) { + JsonNode input = vector.get("input"); + return switch (vector.get("command").asString()) { + case "get_streams" -> "/streams"; + case "get_topics" -> "/streams/" + streamOf(input) + "/topics"; + case "get_partitions" -> "/streams/" + streamOf(input) + "/topics/" + topicOf(input) + "/partitions"; + case "get_consumer_groups" -> + "/streams/" + streamOf(input) + "/topics/" + topicOf(input) + "/consumer-groups"; + case "get_users" -> "/users"; + default -> throw new IllegalArgumentException("unknown command " + vector.get("command")); + }; + } + + /** Decodes a query string as the server does, refusing a repeated key as the server does. */ + private static Map<String, String> decode(String rawQuery) { + Map<String, String> pairs = new TreeMap<>(); + for (String pair : rawQuery.split("&")) { + int separator = pair.indexOf('='); + String key = URLDecoder.decode(pair.substring(0, separator), StandardCharsets.UTF_8); + String value = URLDecoder.decode(pair.substring(separator + 1), StandardCharsets.UTF_8); + assertThat(pairs.put(key, value)).as("repeated key " + key).isNull(); + } + return pairs; + } + + private static StreamId streamOf(JsonNode input) { + return streamId(input).orElseThrow(); + } + + private static TopicId topicOf(JsonNode input) { + return topicId(input).orElseThrow(); + } + + private static void assertRefused(ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOfSatisfying( + IggyValidationException.class, + refusal -> assertThat(refusal.getErrorCode()).isEqualTo(IggyErrorCode.INVALID_COMMAND)); + } +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/tcp/ListPagesTcpClientTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/tcp/ListPagesTcpClientTest.java new file mode 100644 index 0000000..6ea695e --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/client/blocking/tcp/ListPagesTcpClientTest.java
@@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.client.blocking.tcp; + +import org.apache.iggy.client.blocking.IggyBaseClient; +import org.apache.iggy.client.blocking.ListPagesClientBaseTest; + +class ListPagesTcpClientTest extends ListPagesClientBaseTest { + + @Override + protected IggyBaseClient getClient() { + return TcpClientFactory.create(serverHost(), serverTcpPort()); + } +}
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/exception/IggyErrorCodeTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/exception/IggyErrorCodeTest.java index fb8816d..227e83f 100644 --- a/foreign/java/java-sdk/src/test/java/org/apache/iggy/exception/IggyErrorCodeTest.java +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/exception/IggyErrorCodeTest.java
@@ -194,6 +194,7 @@ "89, NOT_PRIMARY", "90, DEFERRED_POLL_CAPACITY_EXCEEDED", "96, TIERED_READ_FAILED", + "97, REPLY_TOO_LARGE", // Client errors "100, CLIENT_NOT_FOUND",
diff --git a/foreign/java/java-sdk/src/test/java/org/apache/iggy/serde/ListPagesTest.java b/foreign/java/java-sdk/src/test/java/org/apache/iggy/serde/ListPagesTest.java new file mode 100644 index 0000000..7756614 --- /dev/null +++ b/foreign/java/java-sdk/src/test/java/org/apache/iggy/serde/ListPagesTest.java
@@ -0,0 +1,229 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iggy.serde; + +import org.apache.iggy.ListPagesFixture.Item; +import org.apache.iggy.client.async.tcp.vsr.VsrOperation; +import org.apache.iggy.exception.IggyErrorCode; +import org.apache.iggy.exception.IggyMalformedResponseException; +import org.apache.iggy.exception.IggyValidationException; +import org.apache.iggy.identifier.Identifier; +import org.apache.iggy.system.NamedPageQuery; +import org.apache.iggy.system.Page; +import org.apache.iggy.system.PageCursor; +import org.apache.iggy.system.PageOrder; +import org.apache.iggy.system.PageQuery; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; + +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static org.apache.iggy.ListPagesFixture.httpQuery; +import static org.apache.iggy.ListPagesFixture.items; +import static org.apache.iggy.ListPagesFixture.namedQuery; +import static org.apache.iggy.ListPagesFixture.query; +import static org.apache.iggy.ListPagesFixture.readPage; +import static org.apache.iggy.ListPagesFixture.refused; +import static org.apache.iggy.ListPagesFixture.section; +import static org.apache.iggy.ListPagesFixture.streamId; +import static org.apache.iggy.ListPagesFixture.topicId; +import static org.apache.iggy.MetadataChangesFixture.buffer; +import static org.apache.iggy.MetadataChangesFixture.bytes; +import static org.apache.iggy.ResourceOptionsFixture.hex; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * The shared list page vectors against this SDK's own types, encoder and decoder. Every request must match the Rust + * encoder byte for byte, and every response must decode to the ids, names and next cursor of its vector. + */ +class ListPagesTest { + + /** Order id, ascending and the default limit: the page block before its cursor. */ + private static final String DEFAULT_QUERY_HEX = "000064000000"; + + private static final String NO_NAME_HEX = "00"; + + @Test + void givenSharedConstantsWhenComparingShouldMatchTheSdk() { + JsonNode constants = section("constants"); + JsonNode codes = constants.get("codes"); + + assertThat(codes.get("get_streams").asInt()).isEqualTo(CommandCode.Stream.GET_ALL.getValue()); + assertThat(codes.get("get_topics").asInt()).isEqualTo(CommandCode.Topic.GET_ALL.getValue()); + assertThat(codes.get("get_partitions").asInt()).isEqualTo(CommandCode.Partition.GET_ALL.getValue()); + assertThat(codes.get("get_consumer_groups").asInt()).isEqualTo(CommandCode.ConsumerGroup.GET_ALL.getValue()); + assertThat(codes.get("get_users").asInt()).isEqualTo(CommandCode.User.GET_ALL.getValue()); + codes.properties() + .forEach(code -> assertThat( + VsrOperation.operationForCode(code.getValue().asInt())) + .as(code.getKey()) + .isEqualTo(VsrOperation.NON_REPLICATED)); + assertThat(constants.get("orders").get("id").asInt()).isEqualTo(PageOrder.ID.asCode()); + assertThat(constants.get("orders").get("created").asInt()).isEqualTo(PageOrder.CREATED.asCode()); + assertThat(constants.get("cursor_prefix").asString()).isEqualTo(PageCursor.PREFIX); + assertThat(constants.get("max_cursor_bytes").asInt()).isEqualTo(PageCursor.MAX_SIZE); + assertThat(constants.get("default_limit").asLong()) + .isEqualTo(PageQuery.DEFAULT_LIMIT) + .isEqualTo(PageQuery.builder().build().limit()); + assertThat(constants.get("max_limit").asLong()).isEqualTo(PageQuery.MAX_LIMIT); + assertThat(constants.get("max_name_bytes").asInt()).isEqualTo(NamedPageQuery.MAX_NAME_SIZE); + assertThat(constants.get("errors").get("invalid_command").asInt()) + .isEqualTo(IggyErrorCode.INVALID_COMMAND.getCode()); + assertThat(constants.get("errors").get("reply_too_large").asInt()) + .isEqualTo(IggyErrorCode.REPLY_TOO_LARGE.getCode()); + } + + @Test + void givenSharedAndOpaqueCursorsWhenParsingShouldRoundTripTheirTextAndBytes() { + for (String group : List.of("cursors", "opaque_cursors")) { + for (JsonNode vector : section(group)) { + String name = vector.get("case").asString(); + String text = vector.get("text").asString(); + byte[] cursorBytes = bytes(vector.get("hex").asString()); + + PageCursor cursor = PageCursor.parse(text); + + assertThat(cursor.toString()).as(name).isEqualTo(text); + assertThat(cursor.toBytes()).as(name).isEqualTo(cursorBytes); + assertThat(PageCursor.fromBytes(cursorBytes)).as(name).contains(cursor); + } + } + } + + /** The partitions page methods send their {@link PageQuery} as a query without a name. */ + @Test + void givenSharedRequestsWhenEncodingShouldMatchTheRustEncoderAndHttpQuery() { + for (JsonNode vector : section("requests")) { + String name = vector.get("case").asString(); + JsonNode input = vector.get("input"); + NamedPageQuery query = vector.get("command").asString().equals("get_partitions") + ? new NamedPageQuery(query(input)) + : namedQuery(input); + + query.validate(); + + assertThat(hex(BytesSerializer.toPageRequest(query, parents(input)))) + .as(name) + .isEqualTo(vector.get("request_hex").asString()); + assertThat(query.httpQuery()).as(name).isEqualTo(httpQuery(vector)); + } + } + + @Test + void givenSharedAndOpaqueResponsesWhenDecodingShouldKeepTheirItemsAndNextCursor() { + for (String group : List.of("responses", "opaque_responses")) { + for (JsonNode vector : section(group)) { + String name = vector.get("case").asString(); + JsonNode next = vector.get("next"); + + Page<Item> page = readPage( + vector.get("command").asString(), + buffer(vector.get("response_hex").asString())); + + assertThat(page.items()).as(name).isEqualTo(items(vector)); + assertThat(page.next().map(PageCursor::toString)) + .as(name) + .isEqualTo(next.isNull() ? Optional.empty() : Optional.of(next.asString())); + } + } + } + + @Test + void givenOpaqueCursorsAndNextsWhenSendingThemBackShouldKeepTheirBytes() { + for (JsonNode vector : section("opaque_cursors")) { + assertSentBack( + vector.get("case").asString(), + PageCursor.parse(vector.get("text").asString()), + vector.get("hex").asString()); + } + for (JsonNode vector : section("opaque_responses")) { + String reply = vector.get("response_hex").asString(); + int nextSize = HexFormat.fromHexDigits(reply, 0, 2); + Page<Item> page = readPage(vector.get("command").asString(), buffer(reply)); + + assertSentBack( + vector.get("case").asString(), page.next().orElseThrow(), reply.substring(2, 2 + nextSize * 2)); + } + } + + @Test + void givenRefusedCursorsWhenParsingShouldRefuseThemAsInvalidCommand() { + for (JsonNode vector : refused("cursors")) { + assertRefused(() -> PageCursor.parse(vector.get("text").asString())); + } + assertThat(PageCursor.fromBytes(new byte[0])).isEmpty(); + assertThat(PageCursor.fromBytes(new byte[PageCursor.MAX_SIZE + 1])).isEmpty(); + } + + @Test + void givenRefusedQueriesWhenValidatingShouldRefuseThemBeforeSending() { + for (JsonNode vector : refused("queries")) { + JsonNode input = vector.get("input"); + assertRefused(namedQuery(input)::validate); + if (input.get("name").isNull()) { + assertRefused(query(input)::validate); + } + } + NamedPageQuery loneSurrogate = new NamedPageQuery(PageQuery.builder().build(), Optional.of("\uD800")); + assertRefused(loneSurrogate::validate); + } + + @Test + void givenRefusedResponsesWhenDecodingShouldRefuseThemAsMalformed() { + for (JsonNode vector : refused("responses")) { + assertThatThrownBy(() -> readPage( + vector.get("command").asString(), + buffer(vector.get("response_hex").asString()))) + .as(vector.get("case").asString()) + .isInstanceOf(IggyMalformedResponseException.class); + } + } + + private static Identifier[] parents(JsonNode input) { + return Stream.concat(streamId(input).stream(), topicId(input).stream()).toArray(Identifier[]::new); + } + + /** The validate-then-encode path of a list method keeps the bytes of a cursor that it cannot read. */ + private static void assertSentBack(String name, PageCursor cursor, String cursorHex) { + NamedPageQuery query = + new NamedPageQuery(PageQuery.builder().cursor(cursor).build()); + + query.validate(); + + assertThat(hex(BytesSerializer.toPageRequest(query))) + .as(name) + .isEqualTo(DEFAULT_QUERY_HEX + + HexFormat.of().toHexDigits((byte) (cursorHex.length() / 2)) + + cursorHex + + NO_NAME_HEX); + } + + private static void assertRefused(ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOfSatisfying( + IggyValidationException.class, + refusal -> assertThat(refusal.getErrorCode()).isEqualTo(IggyErrorCode.INVALID_COMMAND)); + } +}
diff --git a/foreign/java/java-sdk/src/test/resources/list_pages.json b/foreign/java/java-sdk/src/test/resources/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/java/java-sdk/src/test/resources/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/java/java-sdk/src/test/resources/resource_options.json b/foreign/java/java-sdk/src/test/resources/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/java/java-sdk/src/test/resources/resource_options.json +++ b/foreign/java/java-sdk/src/test/resources/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/node/README.md b/foreign/node/README.md index 1fd8ebf..214f2b7 100644 --- a/foreign/node/README.md +++ b/foreign/node/README.md
@@ -120,7 +120,7 @@ a call fails with status 40 until the caller signs in again. A sign-in or logout of the caller ends each earlier call that has to wait for a new session: with status 40 if it sent nothing, or with `OperationUncertainError` if its -outcome is unknown. A Next poll that commits nothing, which has no operation ID, ends with status 57 instead, and an auto-commit poll ends with `FetchProgressUncertainError` (see below). A typed send and a group poll can send more than one +outcome is unknown. A Next poll that commits nothing, which has no operation ID, ends with status 57 instead, and an auto-commit poll ends with `FetchProgressUncertainError` (see below). A typed send, a group poll and a whole-list read can send more than one command. If the caller signs in or logs out before the next command of such a call, the call fails with status 40. Only a call that waits for the client's own sign-in goes on under the new session. If the server refuses that sign-in, the call fails with @@ -728,6 +728,31 @@ Reads return every setting in `options` (keys the client set) and `derivedOptions` (keys the server filled). `u64` values stay `bigint`, so values above 2^53 keep their precision. `system.describeOptions({ scope: OptionsScope.Stream })` lists the keys a server accepts per scope, with `updatable`, `resettable`, `secret`, `readOnly` and `critical`. +### list pages + +`stream.list`, `topic.list`, `group.list` and `user.list` return a whole list. Each of them reads the list in pages of at most 1,000 items, so the result is not one consistent read. An entity that someone creates or deletes during the walk can appear or not appear. The walk keeps the sign-in and the deadline that it started with. If the server answers a page request with the cursor that the request sent, the walk fails with a `DeserializeError`. + +`stream.listPage`, `topic.listPage`, `partition.listPage`, `group.listPage` and `user.listPage` return one page. To read the next page, send the same query with the `next` of the page as its `cursor`. A page can be empty and still have a `next`. + +```ts +import { Client, type NamedPageQuery } from "apache-iggy"; + +const printStreams = async (client: Client) => { + let query: NamedPageQuery = {}; + for (;;) { + const page = await client.stream.listPage(query); + for (const stream of page.items) + console.log(stream.id, stream.name); + if (!page.next) return; + query = { ...query, cursor: page.next }; + } +}; +``` + +A `PageQuery` holds `order`, `descending`, `limit` and `cursor`. `order` selects `PageOrder.Id` or `PageOrder.Created`, and `descending` reverses it. A `NamedPageQuery` is a `PageQuery` with an optional `name`, which keeps the entries whose name holds the text, case-sensitive. `stream.listPage`, `topic.listPage`, `group.listPage` and `user.listPage` take a `NamedPageQuery`. `partition.listPage` takes a `PageQuery`, which has no name. + +The client refuses a query that breaks the page rules with error 3 (invalid command), before it sends anything. Examples are a limit outside 1 to 1000, a name that is empty or longer than 255 bytes, and a `partition.listPage` query with a name. A `PageCursor` prints and parses as the `pg1_` text form that the HTTP API and the CLI use, and `JSON.stringify` writes it as that text. The client does not read the bytes of a cursor. The server refuses a cursor that it cannot use, also with error 3. + ### metadata changes `system.getMetadataChanges` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `next` cursor. The call needs root or the global `manage_servers` permission.
diff --git a/foreign/node/package-lock.json b/foreign/node/package-lock.json index 711c97b..d424de0 100644 --- a/foreign/node/package-lock.json +++ b/foreign/node/package-lock.json
@@ -1,12 +1,12 @@ { "name": "apache-iggy", - "version": "0.11.0", + "version": "0.11.1-edge.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "apache-iggy", - "version": "0.11.0", + "version": "0.11.1-edge.1", "license": "Apache-2.0", "dependencies": { "@node-rs/xxhash": "1.7.8",
diff --git a/foreign/node/package.json b/foreign/node/package.json index 00c131e..643b88a 100644 --- a/foreign/node/package.json +++ b/foreign/node/package.json
@@ -1,7 +1,7 @@ { "name": "apache-iggy", "type": "module", - "version": "0.11.0", + "version": "0.11.1-edge.1", "description": "Official Apache Iggy NodeJS SDK", "keywords": [ "iggy",
diff --git a/foreign/node/src/client/client.socket.test.ts b/foreign/node/src/client/client.socket.test.ts index 2732b1d..226dd5e 100644 --- a/foreign/node/src/client/client.socket.test.ts +++ b/foreign/node/src/client/client.socket.test.ts
@@ -33,6 +33,7 @@ import { UPDATE_USER } from '../wire/user/update-user.command.js'; import { UPDATE_TOPIC } from '../wire/topic/update-topic.command.js'; import { UPDATE_STREAM } from '../wire/stream/update-stream.command.js'; +import { getStreams } from '../wire/stream/get-streams.command.js'; import { OptionsScope } from '../wire/system/describe-options.command.js'; import { MetadataChangeStart, getMetadataChanges } from '../wire/system/get-metadata-changes.command.js'; import { CHANGE_PASSWORD } from '../wire/user/change-password.command.js'; @@ -1542,38 +1543,41 @@ } }); - it('replays the identical frame on a transient response', async () => { - let attempts = 0; - const server = await startVsrServer((frame, socket) => { - const operation = frame.readUInt8(REQUEST_OFFSET.operation); - if (operation !== Operation.NonReplicated || - frame.readUInt32LE(REQUEST_OFFSET.reserved) !== COMMAND_CODE.GetStats) - return singleNodeHandler(server.port)(frame, socket); - attempts += 1; - socket.write( - attempts === 1 - ? replyFrame(frame, operation, Buffer.alloc(0), 57) - : replyFrame(frame, operation, Buffer.from('done')) - ); + for (const code of [COMMAND_CODE.GetStats, COMMAND_CODE.GetUsers, COMMAND_CODE.GetStreams, + COMMAND_CODE.GetTopics, COMMAND_CODE.GetPartitions, COMMAND_CODE.GetGroups]) { + it(`replays the identical frame of read ${code} on a transient response`, async () => { + let attempts = 0; + const server = await startVsrServer((frame, socket) => { + const operation = frame.readUInt8(REQUEST_OFFSET.operation); + if (operation !== Operation.NonReplicated || + frame.readUInt32LE(REQUEST_OFFSET.reserved) !== code) + return singleNodeHandler(server.port)(frame, socket); + attempts += 1; + socket.write( + attempts === 1 + ? replyFrame(frame, operation, Buffer.alloc(0), 57) + : replyFrame(frame, operation, Buffer.from('done')) + ); + }); + const client = new CommandResponseStream(vsrConfig(server.port)); + try { + const response = await client.sendCommand( + code, + Buffer.from('retry-me') + ); + assert.equal(attempts, 2); + assert.deepEqual(response.data, Buffer.from('done')); + const sent = server.frames.filter( + (frame) => frame.readUInt32LE(REQUEST_OFFSET.reserved) === code + ); + assert.equal(sent.length, 2); + assert.deepEqual(sent[0], sent[1]); + } finally { + client.destroy(); + await server.close(); + } }); - const client = new CommandResponseStream(vsrConfig(server.port)); - try { - const response = await client.sendCommand( - COMMAND_CODE.GetStats, - Buffer.from('retry-me') - ); - assert.equal(attempts, 2); - assert.deepEqual(response.data, Buffer.from('done')); - const sent = server.frames.filter( - (frame) => frame.readUInt32LE(REQUEST_OFFSET.reserved) === COMMAND_CODE.GetStats - ); - assert.equal(sent.length, 2); - assert.deepEqual(sent[0], sent[1]); - } finally { - client.destroy(); - await server.close(); - } - }); + } it('resends a metadata changes read after an uncommitted response', async () => { // A behind answer before op 1: status 1, phase 0, no log id, zero ops, no cursor. @@ -3372,6 +3376,54 @@ } finally { client.destroy(); await server.close(); } }); + /** A node whose stream list has `pages` empty pages. It runs `onPage` before it answers each one. */ + const startStreamListServer = async (pages: number, onPage = () => {}): Promise<VsrTestServer> => { + const server = await startVsrServer((frame, socket) => { + if (frame.readUInt32LE(REQUEST_OFFSET.reserved) !== COMMAND_CODE.GetStreams) { + singleNodeHandler(server.port)(frame, socket); + return; + } + onPage(); + const page = countCommand(server, COMMAND_CODE.GetStreams); + // `[next_len:u8][next][count:u32 = 0]`, with a one-byte next on each page but the last. + socket.write(replyFrame(frame, Operation.NonReplicated, + page < pages ? Buffer.from([1, page, 0, 0, 0, 0]) : Buffer.alloc(5))); + }); + return server; + }; + + it('ends a whole list walk with 40 when the caller signs in as another user between its pages', async () => { + const server = await startStreamListServer(2); + const client = new CommandResponseStream({ ...vsrConfig(server.port), heartbeatInterval: 0 }); + try { + await client.sendCommand(LOGIN.code, LOGIN.serialize({ username: 'first', password: 'secret' })); + const sendCommand = client.sendCommand.bind(client); + let pages = 0; + client.sendCommand = async (code, payload, options) => { + if (code === COMMAND_CODE.GetStreams && ++pages === 2) + await sendCommand(LOGIN.code, LOGIN.serialize({ username: 'other', password: 'secret' })); + return sendCommand(code, payload, options); + }; + await assert.rejects(getStreams(async () => client)(), (error: unknown) => error instanceof ResponseError && + error.errorCode === UNAUTHENTICATED && error.commandCode === COMMAND_CODE.GetStreams); + assert.equal(readWireName(registerCredentialsBody(framesOf(server, Operation.Register).at(-1)!), 0).value, 'other'); + assert.equal(countCommand(server, COMMAND_CODE.GetStreams), 1); + } finally { client.destroy(); await server.close(); } + }); + + it('ends a whole list walk with 58 at the deadline it started with and sends no later page', async (context) => { + // Each page takes 0.6 of the deadline, so the third page would start after it. + const server = await startStreamListServer(3, () => context.mock.timers.tick(0.6 * OPERATION_TIMEOUT_MS)); + const client = new CommandResponseStream({ ...vsrConfig(server.port), heartbeatInterval: 0 }); + try { + await client.authenticate(vsrConfig(server.port).credentials); + context.mock.timers.enable({ apis: ['Date'], now: Date.now() }); + await assert.rejects(getStreams(async () => client)(), (error: unknown) => error instanceof ResponseError && + error.errorCode === TRANSIENT_NOT_ACCEPTED && error.commandCode === COMMAND_CODE.GetStreams); + assert.equal(countCommand(server, COMMAND_CODE.GetStreams), 2); + } finally { context.mock.timers.reset(); client.destroy(); await server.close(); } + }); + it('ends a call that waits for its first sign-in with 58 at its deadline', async () => { // The sign-in never ends. const server = await startVsrServer((frame, socket) => {
diff --git a/foreign/node/src/client/client.socket.ts b/foreign/node/src/client/client.socket.ts index 6e3b177..07f9e0c 100644 --- a/foreign/node/src/client/client.socket.ts +++ b/foreign/node/src/client/client.socket.ts
@@ -126,7 +126,8 @@ COMMAND_CODE.GetClient, COMMAND_CODE.GetClients, COMMAND_CODE.GetUser, COMMAND_CODE.GetUsers, COMMAND_CODE.GetAccessTokens, COMMAND_CODE.GetPartitionRoute, COMMAND_CODE.GetOffset, COMMAND_CODE.GetStream, COMMAND_CODE.GetStreams, COMMAND_CODE.GetTopic, - COMMAND_CODE.GetTopics, COMMAND_CODE.GetGroup, COMMAND_CODE.GetGroups, COMMAND_CODE.SyncGroup, + COMMAND_CODE.GetTopics, COMMAND_CODE.GetPartitions, COMMAND_CODE.GetGroup, COMMAND_CODE.GetGroups, + COMMAND_CODE.SyncGroup, ]); const OFFSET_COMMANDS = new Set<number>([ COMMAND_CODE.GetOffset, COMMAND_CODE.StoreOffset, COMMAND_CODE.DeleteConsumerOffset
diff --git a/foreign/node/src/e2e/list-pages.e2e.ts b/foreign/node/src/e2e/list-pages.e2e.ts new file mode 100644 index 0000000..59f3465 --- /dev/null +++ b/foreign/node/src/e2e/list-pages.e2e.ts
@@ -0,0 +1,137 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { randomBytes } from 'node:crypto'; +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { ResponseError } from '../wire/error.utils.js'; +import { PageCursor, PageOrder, UserStatus, type NamedPageQuery, type PageQuery } from '../wire/index.js'; +import { getTestClient } from './test-client.utils.js'; + +// Cursor texts of core/common/fixtures/list_pages.json. The text of both is +// valid, so only the server can refuse them. +/** A cursor of the id walk */ +const ID_SEVEN_CURSOR = 'pg1_AQcAAAAAAAAA'; +/** A cursor of a kind that no server knows */ +const UNKNOWN_KIND_CURSOR = 'pg1_AwcAAAAAAAAA'; +const INVALID_COMMAND = 3; + +const isRefusedByServer = (error: unknown) => + error instanceof ResponseError && error.fromServer && error.errorCode === INVALID_COMMAND; + +describe('e2e -> list pages', async () => { + + const c = getTestClient(); + // Other e2e files run at the same time, so every name holds a random part. + const prefix = `e2e-pages-${randomBytes(4).toString('hex')}`; + const streamIds: number[] = []; + const userIds: number[] = []; + + const createStream = async (name: string) => { + const stream = await c.stream.create({ name: `${prefix}-${name}` }); + streamIds.push(stream.id); + return stream; + }; + + it('e2e -> list pages::walks three streams in pages of two in each order', async () => { + const created: number[] = []; + for (const suffix of ['a', 'b', 'c']) + created.push((await createStream(`walk-${suffix}`)).id); + // A create takes the lowest free id, so a delete by another client can + // give a later stream a lower id. + const ascending = created.toSorted((left, right) => left - right); + const walks: [PageQuery, number[]][] = [ + [{ order: PageOrder.Id }, ascending], + [{ order: PageOrder.Id, descending: true }, ascending.toReversed()], + [{ order: PageOrder.Created }, created] + ]; + for (const [order, want] of walks) { + const query: NamedPageQuery = { ...order, name: `${prefix}-walk`, limit: 2 }; + const first = await c.stream.listPage(query); + assert.equal(first.items.length, 2, JSON.stringify(order)); + assert.ok(first.next, JSON.stringify(order)); + const second = await c.stream.listPage({ ...query, cursor: first.next }); + assert.equal(second.next, undefined, JSON.stringify(order)); + assert.deepEqual([...first.items, ...second.items].map((stream) => stream.id), want, JSON.stringify(order)); + } + + const streams = await c.stream.list(); + for (const id of created) + assert.ok(streams.some((stream) => stream.id === id), `the whole list holds stream ${id}`); + }); + + it('e2e -> list pages::reads the partitions of a topic in pages of two', async () => { + const stream = await createStream('partitions'); + const topic = await c.topic.create({ streamId: stream.id, name: 'events', partitionCount: 3 }); + const query = { streamId: stream.id, topicId: topic.id, limit: 2 }; + + const first = await c.partition.listPage(query); + assert.equal(first.items.length, 2); + assert.ok(first.next); + const second = await c.partition.listPage({ ...query, cursor: first.next }); + assert.equal(second.next, undefined); + assert.deepEqual([...first.items, ...second.items].map((partition) => partition.id), [0, 1, 2]); + }); + + it('e2e -> list pages::keeps the topics, consumer groups and users whose name holds the filter', async () => { + const stream = await createStream('names'); + const events = await c.topic.create({ streamId: stream.id, name: 'events', partitionCount: 1 }); + const readings = await c.topic.create({ streamId: stream.id, name: 'sensor-readings', partitionCount: 1 }); + const target = { streamId: stream.id, topicId: events.id }; + const billing = await c.group.create({ ...target, name: 'billing' }); + await c.group.create({ ...target, name: 'audit' }); + const username = `${prefix}-user`; + const user = await c.user.create({ username, password: 'e2e-pages-pwd1$', status: UserStatus.Active }); + userIds.push(user.id); + + const topics = await c.topic.listPage({ streamId: stream.id, name: 'sensor' }); + assert.deepEqual(topics.items.map((topic) => topic.id), [readings.id]); + assert.equal(topics.next, undefined); + + const groups = await c.group.listPage({ ...target, name: 'bill' }); + assert.deepEqual(groups.items.map((group) => group.id), [billing.id]); + assert.equal(groups.next, undefined); + + const users = await c.user.listPage({ name: username }); + assert.deepEqual(users.items.map((entry) => entry.id), [user.id]); + assert.equal(users.next, undefined); + }); + + it('e2e -> list pages::refuses pages the server cannot serve and stays usable', async () => { + const stream = await createStream('refusals'); + + await assert.rejects( + c.stream.listPage({ cursor: PageCursor.parse(UNKNOWN_KIND_CURSOR) }), + isRefusedByServer, 'a cursor of an unknown kind' + ); + await assert.rejects( + c.stream.listPage({ order: PageOrder.Created, cursor: PageCursor.parse(ID_SEVEN_CURSOR) }), + isRefusedByServer, 'a cursor of the id walk in a created walk' + ); + + const page = await c.stream.listPage({ name: `${prefix}-refusals` }); + assert.deepEqual(page.items.map((entry) => entry.id), [stream.id]); + }); + + after(async () => { + for (const streamId of streamIds) + await c.stream.delete({ streamId }); + for (const userId of userIds) + await c.user.delete({ userId }); + c.destroy(); + }); +});
diff --git a/foreign/node/src/index.ts b/foreign/node/src/index.ts index 369e53a..c714667 100644 --- a/foreign/node/src/index.ts +++ b/foreign/node/src/index.ts
@@ -55,6 +55,16 @@ type StreamOptions, type TopicOptions, type UserOptions, + PageOrder, + PageCursor, + DEFAULT_PAGE_LIMIT, + MAX_PAGE_LIMIT, + PAGE_CURSOR_PREFIX, + MAX_PAGE_CURSOR_SIZE, + MAX_PAGE_NAME_SIZE, + type PageQuery, + type NamedPageQuery, + type Page, MetadataChangeGroup, MetadataChangeKind, MetadataChangeStatus,
diff --git a/foreign/node/src/wire/command-set.ts b/foreign/node/src/wire/command-set.ts index 826d2c0..ea3b6ee 100644 --- a/foreign/node/src/wire/command-set.ts +++ b/foreign/node/src/wire/command-set.ts
@@ -31,7 +31,7 @@ import { createGroup } from './consumer-group/create-group.command.js'; import { joinGroup } from './consumer-group/join-group.command.js'; import { getGroup } from './consumer-group/get-group.command.js'; -import { getGroups } from './consumer-group/get-groups.command.js'; +import { getGroups, getGroupsPage } from './consumer-group/get-groups.command.js'; import { leaveGroup } from './consumer-group/leave-group.command.js'; import { deleteGroup } from './consumer-group/delete-group.command.js'; import { @@ -41,7 +41,7 @@ import { createTopic } from './topic/create-topic.command.js'; import { updateTopic } from './topic/update-topic.command.js'; import { getTopic } from './topic/get-topic.command.js'; -import { getTopics } from './topic/get-topics.command.js'; +import { getTopics, getTopicsPage } from './topic/get-topics.command.js'; import { deleteTopic } from './topic/delete-topic.command.js'; import { ensureTopic } from './topic/ensure-topic.virtual.command.js'; @@ -58,12 +58,13 @@ import { createStream } from './stream/create-stream.command.js'; import { updateStream } from './stream/update-stream.command.js'; import { getStream } from './stream/get-stream.command.js'; -import { getStreams } from './stream/get-streams.command.js'; +import { getStreams, getStreamsPage } from './stream/get-streams.command.js'; import { deleteStream } from './stream/delete-stream.command.js'; import { ensureStream } from './stream/ensure-stream.virtual.command.js'; import { createPartition } from './partition/create-partition.command.js'; import { deletePartition } from './partition/delete-partition.command.js'; +import { getPartitionsPage } from './partition/get-partitions.command.js'; import { deleteSegments } from './segment/delete-segments.command.js'; @@ -85,12 +86,13 @@ import { updateUser } from './user/update-user.command.js'; import { updatePermissions } from './user/update-permissions.command.js'; import { deleteUser } from './user/delete-user.command.js'; -import { getUsers } from './user/get-users.command.js'; +import { getUsers, getUsersPage } from './user/get-users.command.js'; const userAPI = (c: ClientProvider) => ({ get: getUser(c), list: getUsers(c), + listPage: getUsersPage(c), create: createUser(c), update: updateUser(c), updatePermissions: updatePermissions(c), @@ -127,6 +129,7 @@ const streamAPI = (c: ClientProvider) => ({ get: getStream(c), list: getStreams(c), + listPage: getStreamsPage(c), create: createStream(c), update: updateStream(c), delete: deleteStream(c), @@ -138,6 +141,7 @@ const topicAPI = (c: ClientProvider) => ({ get: getTopic(c), list: getTopics(c), + listPage: getTopicsPage(c), create: createTopic(c), update: updateTopic(c), delete: deleteTopic(c), @@ -147,6 +151,7 @@ type TopicAPI = ReturnType<typeof topicAPI>; const partitionAPI = (c: ClientProvider) => ({ + listPage: getPartitionsPage(c), create: createPartition(c), delete: deletePartition(c), }); @@ -162,6 +167,7 @@ const groupAPI = (c: ClientProvider) => ({ get: getGroup(c), list: getGroups(c), + listPage: getGroupsPage(c), create: createGroup(c), join: joinGroup(c), leave: leaveGroup(c),
diff --git a/foreign/node/src/wire/command.code.ts b/foreign/node/src/wire/command.code.ts index 835abb4..f84b35f 100644 --- a/foreign/node/src/wire/command.code.ts +++ b/foreign/node/src/wire/command.code.ts
@@ -67,6 +67,7 @@ // 304 is retired and must never be reused. CreatePartitions: 402, DeletePartitions: 403, + GetPartitions: 404, DeleteSegments: 503, GetGroup: 600, GetGroups: 601,
diff --git a/foreign/node/src/wire/consumer-group/get-groups.command.ts b/foreign/node/src/wire/consumer-group/get-groups.command.ts index 0ab80dd..5640f1f 100644 --- a/foreign/node/src/wire/consumer-group/get-groups.command.ts +++ b/foreign/node/src/wire/consumer-group/get-groups.command.ts
@@ -15,12 +15,15 @@ // specific language governing permissions and limitations // under the License. -import type { CommandResponse } from '../../client/client.type.js'; +import type { ClientProvider, CommandResponse } from '../../client/client.type.js'; import type { ConsumerGroup } from './group.utils.js'; import { serializeIdentifier, type Id } from '../identifier.utils.js'; -import { deserializeConsumerGroups } from './group.utils.js'; +import { deserializeConsumerGroup } from './group.utils.js'; import { wrapCommand } from '../command.utils.js'; import { COMMAND_CODE } from '../command.code.js'; +import { + deserializePage, readWholeList, serializeNamedPageQuery, type NamedPageQuery, type Page +} from '../page.utils.js'; /** * Parameters for the get consumer groups command. @@ -33,26 +36,39 @@ }; /** + * Parameters for the get consumer groups page command: the topic and one page + * request. + */ +export type GetGroupsPage = GetGroups & NamedPageQuery; + +/** * Get consumer groups command definition. - * Retrieves all consumer groups within a topic. + * Retrieves one page of the consumer groups within a topic. */ export const GET_GROUPS = { code: COMMAND_CODE.GetGroups, - serialize: ({ streamId, topicId }: GetGroups) => { + serialize: ({ streamId, topicId, ...query }: GetGroupsPage) => { return Buffer.concat([ serializeIdentifier(streamId), serializeIdentifier(topicId), + serializeNamedPageQuery(COMMAND_CODE.GetGroups, query) ]); }, - deserialize: (r: CommandResponse) => { - return deserializeConsumerGroups(r.data); - } + deserialize: (r: CommandResponse) => deserializePage(r.data, deserializeConsumerGroup) }; /** - * Executable get consumer groups command function. + * Executable get consumer groups page command function. */ -export const getGroups = wrapCommand<GetGroups, ConsumerGroup[]>(GET_GROUPS); +export const getGroupsPage = wrapCommand<GetGroupsPage, Page<ConsumerGroup>>(GET_GROUPS); + +/** + * Executable get consumer groups command function. Reads every consumer group + * of the topic page by page. + */ +export const getGroups = (c: ClientProvider) => + ({ streamId, topicId }: GetGroups): Promise<ConsumerGroup[]> => + readWholeList(c, GET_GROUPS, (query) => ({ streamId, topicId, ...query }));
diff --git a/foreign/node/src/wire/consumer-group/group.utils.ts b/foreign/node/src/wire/consumer-group/group.utils.ts index 7a0144d..b18885f 100644 --- a/foreign/node/src/wire/consumer-group/group.utils.ts +++ b/foreign/node/src/wire/consumer-group/group.utils.ts
@@ -89,21 +89,3 @@ } } }; - -/** - * Deserializes multiple consumer groups from a buffer. - * - * @param r - Buffer containing serialized consumer groups data - * @param pos - Starting position in the buffer - * @returns Array of deserialized consumer groups - */ -export const deserializeConsumerGroups = (r: Buffer, pos = 0) => { - const end = r.length; - const cgroups = []; - while (pos < end) { - const { bytesRead, data } = deserializeConsumerGroup(r, pos); - cgroups.push(data); - pos += bytesRead; - } - return cgroups; -};
diff --git a/foreign/node/src/wire/error.code.test.ts b/foreign/node/src/wire/error.code.test.ts index a756342..738b36e 100644 --- a/foreign/node/src/wire/error.code.test.ts +++ b/foreign/node/src/wire/error.code.test.ts
@@ -50,6 +50,10 @@ assert.equal(translateErrorCode(96), 'Tiered data cannot be read from the object store; a retry does not help'); }); +it('translates the reply size refusal', () => { + assert.equal(translateErrorCode(97), 'The reply is larger than the reply size limit'); +}); + it('translates the consumer-offset capacity error', () => { assert.equal(translateErrorCode(3024), 'Consumer offset limit reached for partition, raise [partition] consumer_offsets_max'); });
diff --git a/foreign/node/src/wire/error.code.ts b/foreign/node/src/wire/error.code.ts index a82dfa1..cb8907a 100644 --- a/foreign/node/src/wire/error.code.ts +++ b/foreign/node/src/wire/error.code.ts
@@ -92,6 +92,7 @@ case '89': return "The replica is not the partition primary."; case '90': return "Deferred poll capacity exceeded; retry after backoff on the same replica"; case '96': return "Tiered data cannot be read from the object store; a retry does not help"; + case '97': return "The reply is larger than the reply size limit"; case '100': return "Client with ID: {0} was not found."; case '101': return "Invalid client ID";
diff --git a/foreign/node/src/wire/fixtures/list_pages.json b/foreign/node/src/wire/fixtures/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/node/src/wire/fixtures/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/node/src/wire/fixtures/resource_options.json b/foreign/node/src/wire/fixtures/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/node/src/wire/fixtures/resource_options.json +++ b/foreign/node/src/wire/fixtures/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/node/src/wire/index.ts b/foreign/node/src/wire/index.ts index 1f256a3..a90a8f8 100644 --- a/foreign/node/src/wire/index.ts +++ b/foreign/node/src/wire/index.ts
@@ -29,6 +29,10 @@ export * from './command-set.js'; export { type Id } from './identifier.utils.js'; export { + PAGE_CURSOR_PREFIX, DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT, MAX_PAGE_CURSOR_SIZE, MAX_PAGE_NAME_SIZE, + PageOrder, PageCursor, type PageQuery, type NamedPageQuery, type Page +} from './page.utils.js'; +export { StreamOptionKey, TopicOptionKey, UserOptionKey, type OptionEntry, type ParsedOptions } from './options.utils.js';
diff --git a/foreign/node/src/wire/list-pages.test.ts b/foreign/node/src/wire/list-pages.test.ts new file mode 100644 index 0000000..002bc8c --- /dev/null +++ b/foreign/node/src/wire/list-pages.test.ts
@@ -0,0 +1,428 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import type { ClientProvider, CommandResponse, RawClient } from '../client/client.type.js'; +import { COMMAND_CODE } from './command.code.js'; +import { translateErrorCode } from './error.code.js'; +import { DeserializeError, ResponseError } from './error.utils.js'; +import { serializeIdentifier, type Id } from './identifier.utils.js'; +import { + DEFAULT_PAGE_LIMIT, MAX_PAGE_CURSOR_SIZE, MAX_PAGE_LIMIT, MAX_PAGE_NAME_SIZE, PAGE_CURSOR_PREFIX, + PAGE_ORDER_CODE, PageCursor, type NamedPageQuery, type Page, type PageOrder, type PageQuery +} from './page.utils.js'; +import { Operation, operationForCode } from './vsr/operation.js'; +import { GET_GROUPS, getGroups, getGroupsPage } from './consumer-group/get-groups.command.js'; +import { GET_PARTITIONS, getPartitionsPage } from './partition/get-partitions.command.js'; +import { GET_STREAMS, getStreams, getStreamsPage } from './stream/get-streams.command.js'; +import { GET_TOPICS, getTopics, getTopicsPage } from './topic/get-topics.command.js'; +import { GET_USERS, getUsers, getUsersPage } from './user/get-users.command.js'; + +type ListCommand = 'get_users' | 'get_streams' | 'get_topics' | 'get_partitions' | 'get_consumer_groups'; + +type FixtureId = { kind: 'numeric', value: number } | { kind: 'named', value: string }; + +type FixtureInput = { + stream_id: FixtureId | null, + topic_id: FixtureId | null, + order: PageOrder, + descending: boolean, + limit: number, + cursor: string | null, + name: string | null +}; + +type FixtureItem = { id: number, name: string | null }; + +type FixtureResponse = { + case: string, command: ListCommand, response_hex: string, next: string | null, items: FixtureItem[] +}; + +type Fixture = { + schema_version: number, + constants: { + codes: Record<ListCommand, number>, + orders: Record<string, number>, + cursor_prefix: string, + max_cursor_bytes: number, + default_limit: number, + max_limit: number, + max_name_bytes: number, + errors: { invalid_command: number, reply_too_large: number } + }, + cursors: { case: string, text: string, hex: string }[], + opaque_cursors: { case: string, text: string, hex: string }[], + requests: { case: string, command: ListCommand, input: FixtureInput, request_hex: string }[], + responses: FixtureResponse[], + opaque_responses: FixtureResponse[], + refused: { + cursors: { case: string, text: string }[], + queries: { case: string, input: FixtureInput }[], + responses: { case: string, command: ListCommand, response_hex: string }[] + } +}; + +const fixture: Fixture = JSON.parse(readFileSync(new URL('./fixtures/list_pages.json', import.meta.url), 'utf8')); +const { constants } = fixture; + +/** `PageCursor.parse` runs outside of any command. */ +const NO_COMMAND = 0; +/** `[next_len:u8 = 0][count:u32 = 0]` */ +const EMPTY_LAST_PAGE = Buffer.alloc(5); + +const fromHex = (hex: string) => Buffer.from(hex, 'hex'); + +const u32 = (value: number) => { + const bytes = Buffer.alloc(4); + bytes.writeUInt32LE(value); + return bytes; +}; + +const reply = (data: Buffer): CommandResponse => ({ status: 0, length: data.length, data }); + +const fixtureResponse = (name: string): FixtureResponse => { + const vector = fixture.responses.find((response) => response.case === name); + assert.ok(vector, `no response vector ${name}`); + return vector; +}; + +const fixtureId = (id: FixtureId | null): Id => { + assert.ok(id, 'the command needs this parent id'); + return id.value; +}; + +const fixtureQuery = (input: FixtureInput): PageQuery => ({ + order: input.order, + descending: input.descending, + limit: input.limit, + ...(input.cursor === null ? {} : { cursor: PageCursor.parse(input.cursor) }) +}); + +const fixtureNamedQuery = (input: FixtureInput): NamedPageQuery => ({ + ...fixtureQuery(input), + ...(input.name === null ? {} : { name: input.name }) +}); + +/** The page with each item as the fixture writes it. An absent next stays absent. */ +const fixturePage = <T>(page: Page<T>, item: (entry: T) => FixtureItem): Page<FixtureItem> => + ({ ...page, items: page.items.map(item) }); + +const LIST_COMMANDS: Record<ListCommand, { + code: number, + encode: (input: FixtureInput) => Buffer, + decode: (data: Buffer) => Page<FixtureItem> +}> = { + get_users: { + code: COMMAND_CODE.GetUsers, + encode: (input) => GET_USERS.serialize(fixtureNamedQuery(input)), + decode: (data) => fixturePage(GET_USERS.deserialize(reply(data)), (user) => ({ id: user.id, name: user.userName })) + }, + get_streams: { + code: COMMAND_CODE.GetStreams, + encode: (input) => GET_STREAMS.serialize(fixtureNamedQuery(input)), + decode: (data) => fixturePage(GET_STREAMS.deserialize(reply(data)), (stream) => ({ id: stream.id, name: stream.name })) + }, + get_topics: { + code: COMMAND_CODE.GetTopics, + encode: (input) => GET_TOPICS.serialize({ streamId: fixtureId(input.stream_id), ...fixtureNamedQuery(input) }), + decode: (data) => fixturePage(GET_TOPICS.deserialize(reply(data)), (topic) => ({ id: topic.id, name: topic.name })) + }, + get_partitions: { + code: COMMAND_CODE.GetPartitions, + encode: (input) => GET_PARTITIONS.serialize({ + streamId: fixtureId(input.stream_id), topicId: fixtureId(input.topic_id), ...fixtureQuery(input) + }), + decode: (data) => fixturePage(GET_PARTITIONS.deserialize(reply(data)), (partition) => ({ id: partition.id, name: null })) + }, + get_consumer_groups: { + code: COMMAND_CODE.GetGroups, + encode: (input) => GET_GROUPS.serialize({ + streamId: fixtureId(input.stream_id), topicId: fixtureId(input.topic_id), ...fixtureNamedQuery(input) + }), + decode: (data) => fixturePage(GET_GROUPS.deserialize(reply(data)), (group) => ({ id: group.id, name: group.name })) + } +}; + +const isInvalidCommand = (commandCode: number) => (error: unknown) => + error instanceof ResponseError && !error.fromServer && error.commandCode === commandCode && + error.errorCode === constants.errors.invalid_command; + +/** A raw client that answers each request with the next reply and records the requests. */ +const scriptedClient = (replies: Buffer[]) => { + const sent: { code: number, payload: Buffer }[] = []; + const client = { + sendCommand: async (code: number, payload: Buffer): Promise<CommandResponse> => { + sent.push({ code, payload: Buffer.from(payload) }); + const data = replies.shift(); + assert.ok(data, 'a request after the last scripted reply'); + return reply(data); + } + } as unknown as RawClient; + const provider: ClientProvider = async () => client; + return { sent, provider }; +}; + +/** The page block of a whole list walk: id order, ascending, limit 1000, then `cursor` and no name. */ +const walkBlock = (cursor: Buffer) => + Buffer.concat([Buffer.from([PAGE_ORDER_CODE.id, 0]), u32(MAX_PAGE_LIMIT), cursor, Buffer.from([0])]); + +describe('given the shared list page vectors when encoding and decoding should match the server contract', () => { + it('has the schema version this test reads', () => { + assert.equal(fixture.schema_version, 1); + }); + + it('names the codes, orders, limits and errors of this SDK', () => { + assert.deepEqual( + constants.codes, + Object.fromEntries(Object.entries(LIST_COMMANDS).map(([name, { code }]) => [name, code])) + ); + for (const code of Object.values(constants.codes)) + assert.equal(operationForCode(code), Operation.NonReplicated); + assert.deepEqual(constants.orders, PAGE_ORDER_CODE); + assert.equal(constants.cursor_prefix, PAGE_CURSOR_PREFIX); + assert.equal(constants.max_cursor_bytes, MAX_PAGE_CURSOR_SIZE); + assert.equal(constants.default_limit, DEFAULT_PAGE_LIMIT); + assert.equal(constants.max_limit, MAX_PAGE_LIMIT); + assert.equal(constants.max_name_bytes, MAX_PAGE_NAME_SIZE); + assert.equal(translateErrorCode(constants.errors.invalid_command), 'Invalid command'); + assert.equal(translateErrorCode(constants.errors.reply_too_large), 'The reply is larger than the reply size limit'); + }); + + // The client checks only the text, so the opaque cursors that the server refuses parse too. + it('parses and prints every cursor', () => { + for (const vector of [...fixture.cursors, ...fixture.opaque_cursors]) { + const cursor = PageCursor.parse(vector.text); + assert.equal(cursor.toString(), vector.text, vector.case); + assert.equal(JSON.stringify(cursor), JSON.stringify(vector.text), vector.case); + assert.equal(cursor.toBytes().toString('hex'), vector.hex, vector.case); + assert.equal(PageCursor.fromBytes(fromHex(vector.hex)).toString(), vector.text, vector.case); + } + }); + + // The Node SDK has no HTTP transport, so http_query has no encoder to check. + it('encodes every request', () => { + for (const vector of fixture.requests) + assert.equal(LIST_COMMANDS[vector.command].encode(vector.input).toString('hex'), vector.request_hex, vector.case); + }); + + it('fills the defaults of an empty query', () => { + const firstPage = fixture.requests.find((vector) => vector.case === 'streams_first_page'); + assert.ok(firstPage); + assert.equal(GET_STREAMS.serialize({}).toString('hex'), firstPage.request_hex); + }); + + it('decodes every reply, also a next that the server would refuse', () => { + for (const vector of [...fixture.responses, ...fixture.opaque_responses]) { + const page = LIST_COMMANDS[vector.command].decode(fromHex(vector.response_hex)); + assert.equal(Object.hasOwn(page, 'next'), vector.next !== null, vector.case); + assert.deepEqual( + { next: page.next?.toString() ?? null, items: page.items }, + { next: vector.next, items: vector.items }, + vector.case + ); + } + }); + + it('sends an opaque next back with its bytes unchanged', () => { + for (const vector of fixture.opaque_responses) { + const data = fromHex(vector.response_hex); + const page = GET_STREAMS.deserialize(reply(data)); + assert.ok(page.next, vector.case); + // [order][descending][limit:u32][cursor_len][cursor][name_len], with the + // [next_len][next] of the reply as the cursor. + const expected = Buffer.concat([ + Buffer.from([PAGE_ORDER_CODE.id, 0]), u32(DEFAULT_PAGE_LIMIT), data.subarray(0, 1 + data[0]), Buffer.from([0]) + ]); + assert.deepEqual(GET_STREAMS.serialize({ cursor: page.next }), expected, vector.case); + } + }); +}); + +describe('given refused list page vectors when parsing, encoding or decoding should refuse them', () => { + it('refuses every cursor text', () => { + for (const vector of fixture.refused.cursors) + assert.throws(() => PageCursor.parse(vector.text), isInvalidCommand(NO_COMMAND), vector.case); + }); + + it('refuses every query of each page method before it connects', async () => { + let connects = 0; + const provider: ClientProvider = async () => { + connects += 1; + throw new Error('must not connect'); + }; + const parents = { streamId: 1, topicId: 2 }; + const namedPageReads: [number, (query: NamedPageQuery) => Promise<unknown>][] = [ + [COMMAND_CODE.GetStreams, (query) => getStreamsPage(provider)(query)], + [COMMAND_CODE.GetUsers, (query) => getUsersPage(provider)(query)], + [COMMAND_CODE.GetTopics, (query) => getTopicsPage(provider)({ ...parents, ...query })], + [COMMAND_CODE.GetGroups, (query) => getGroupsPage(provider)({ ...parents, ...query })] + ]; + for (const vector of fixture.refused.queries) { + for (const [code, readPage] of namedPageReads) + await assert.rejects(readPage(fixtureNamedQuery(vector.input)), isInvalidCommand(code), vector.case); + if (vector.input.name === null) + await assert.rejects( + getPartitionsPage(provider)({ ...parents, ...fixtureQuery(vector.input) }), + isInvalidCommand(COMMAND_CODE.GetPartitions), vector.case + ); + } + assert.equal(connects, 0); + }); + + it('refuses every malformed reply', () => { + for (const vector of fixture.refused.responses) + assert.throws( + () => LIST_COMMANDS[vector.command].decode(fromHex(vector.response_hex)), DeserializeError, vector.case + ); + }); +}); + +describe('given values the shared vectors cannot hold when encoding or decoding should refuse them', () => { + it('refuses a query with an unknown order, a fractional limit, a cursor text or a lone surrogate', () => { + const refused: [string, NamedPageQuery][] = [ + ['unknown order', { order: 'name' as PageOrder }], + ['fractional limit', { limit: 1.5 }], + ['cursor text', { cursor: fixture.cursors[0].text as unknown as PageCursor }], + ['lone surrogate', { name: 'a\uD800' }] + ]; + for (const [name, query] of refused) + assert.throws(() => GET_STREAMS.serialize(query), isInvalidCommand(COMMAND_CODE.GetStreams), name); + }); + + // A spread skips the excess property check, so a NamedPageQuery reaches the partitions method. + it('refuses a partitions query with a name before it sends', async () => { + const { sent, provider } = scriptedClient([]); + const query: NamedPageQuery = { name: 'p' }; + await assert.rejects( + getPartitionsPage(provider)({ streamId: 1, topicId: 2, ...query }), + isInvalidCommand(COMMAND_CODE.GetPartitions) + ); + assert.deepEqual(sent, []); + }); + + it('sends a partitions query with an undefined name as a query without a name', () => { + const query: NamedPageQuery = { name: undefined }; + assert.deepEqual( + GET_PARTITIONS.serialize({ streamId: 1, topicId: 2, ...query }), + GET_PARTITIONS.serialize({ streamId: 1, topicId: 2 }) + ); + }); + + it('refuses bytes after the last item of every reply', () => { + for (const vector of fixture.responses) { + const data = Buffer.concat([fromHex(vector.response_hex), Buffer.from([0])]); + assert.throws(() => LIST_COMMANDS[vector.command].decode(data), DeserializeError, vector.case); + } + }); + + // The group decoder cuts a name short without a bounds check, so only the + // page decoder sees that the last name of the groups reply is cut. + it('refuses every reply cut by its last byte', () => { + for (const vector of fixture.responses) { + const data = fromHex(vector.response_hex); + assert.throws( + () => LIST_COMMANDS[vector.command].decode(data.subarray(0, data.length - 1)), DeserializeError, vector.case + ); + } + }); + + it('refuses cursor bytes of no byte or of more than 255 bytes', () => { + for (const size of [0, MAX_PAGE_CURSOR_SIZE + 1]) + assert.throws(() => PageCursor.fromBytes(Buffer.alloc(size, 1)), DeserializeError, `${size} bytes`); + }); +}); + +describe('given a page cursor when its source or its bytes change should keep its own bytes', () => { + const [vector] = fixture.cursors; + + it('copies the bytes it is built from and the bytes it returns', () => { + const bytes = fromHex(vector.hex); + const cursor = PageCursor.fromBytes(bytes); + bytes.fill(0); + cursor.toBytes().fill(0); + assert.equal(cursor.toString(), vector.text); + }); + + it('copies the next out of the reply', () => { + const response = fixtureResponse('streams_with_next'); + const data = fromHex(response.response_hex); + const page = GET_STREAMS.deserialize(reply(data)); + data.fill(0); + assert.equal(page.next?.toString(), response.next); + }); +}); + +describe('given a list of several pages when reading the whole list should walk every page by id', () => { + it('starts with the whole list request of the shared vectors', () => { + const walk = fixture.requests.find((request) => request.case === 'streams_whole_list_walk'); + assert.ok(walk); + assert.equal(walkBlock(Buffer.from([0])).toString('hex'), walk.request_hex); + }); + + const walks: { + name: string, code: number, parents: Buffer, reply: string, + list: (provider: ClientProvider) => Promise<{ id: number }[]> + }[] = [ + { + name: 'streams', code: COMMAND_CODE.GetStreams, parents: Buffer.alloc(0), reply: 'streams_with_next', + list: (provider) => getStreams(provider)() + }, + { + name: 'topics', code: COMMAND_CODE.GetTopics, parents: serializeIdentifier('orders'), + reply: 'topics_created_descending_with_next', + list: (provider) => getTopics(provider)({ streamId: 'orders' }) + }, + { + name: 'consumer groups', code: COMMAND_CODE.GetGroups, + parents: Buffer.concat([serializeIdentifier(1), serializeIdentifier('events')]), + reply: 'consumer_groups_with_next', + list: (provider) => getGroups(provider)({ streamId: 1, topicId: 'events' }) + }, + { + name: 'users', code: COMMAND_CODE.GetUsers, parents: Buffer.alloc(0), reply: 'users_with_next', + list: (provider) => getUsers(provider)() + } + ]; + + for (const walk of walks) + it(`reads every page of the ${walk.name} and sends each next back`, async () => { + const vector = fixtureResponse(walk.reply); + const first = fromHex(vector.response_hex); + const { sent, provider } = scriptedClient([first, EMPTY_LAST_PAGE]); + const items = await walk.list(provider); + assert.deepEqual(items.map((item) => item.id), vector.items.map((item) => item.id)); + assert.deepEqual(sent, [ + { code: walk.code, payload: Buffer.concat([walk.parents, walkBlock(Buffer.from([0]))]) }, + { code: walk.code, payload: Buffer.concat([walk.parents, walkBlock(first.subarray(0, 1 + first[0]))]) } + ]); + }); +}); + +describe('given a server that answers the cursor it was sent when reading the whole list should fail', () => { + it('refuses the second page and sends no third request', async () => { + const first = fromHex(fixtureResponse('streams_with_next').response_hex); + const { sent, provider } = scriptedClient([first, first]); + await assert.rejects(getStreams(provider)(), { + name: 'DeserializeError', message: 'cannot deserialize list page: the server answered the page cursor it was sent' + }); + assert.deepEqual(sent.map((request) => request.payload), [ + walkBlock(Buffer.from([0])), walkBlock(first.subarray(0, 1 + first[0])) + ]); + }); +});
diff --git a/foreign/node/src/wire/page.utils.ts b/foreign/node/src/wire/page.utils.ts new file mode 100644 index 0000000..83da78b --- /dev/null +++ b/foreign/node/src/wire/page.utils.ts
@@ -0,0 +1,288 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import { OPERATION_TIMEOUT_MS } from '../client/client.operation.js'; +import type { ClientProvider } from '../client/client.type.js'; +import type { Command } from './command.utils.js'; +import { DeserializeError, deserializeError, responseError } from './error.utils.js'; +import { decodeCanonicalBase64 } from './system/metadata-changes.utils.js'; + +/** Text prefix of a page cursor. */ +export const PAGE_CURSOR_PREFIX = 'pg1_'; + +/** Items per page when the query does not say. */ +export const DEFAULT_PAGE_LIMIT = 100; + +/** Most items one page returns. */ +export const MAX_PAGE_LIMIT = 1000; + +/** Most bytes of a cursor: its length on the wire is one byte. */ +export const MAX_PAGE_CURSOR_SIZE = 255; + +/** Most bytes of a name filter in UTF-8: its length on the wire is one byte. */ +export const MAX_PAGE_NAME_SIZE = 255; + +const MAX_PAGE_CURSOR_TEXT_LENGTH = PAGE_CURSOR_PREFIX.length + Math.ceil(MAX_PAGE_CURSOR_SIZE * 4 / 3); +const INVALID_COMMAND = 3; +/** A cursor is parsed outside of any command, so its refusal names none. */ +const NO_COMMAND = 0; +/** `[order:u8][descending:u8][limit:u32][cursor_len:u8]` and `[name_len:u8]` */ +const PAGE_BLOCK_FIXED_SIZE = 8; +/** `[count:u32]` after the next cursor of a reply */ +const PAGE_COUNT_SIZE = 4; +const PAGE_NAME = 'list page'; + +/** Order of a list page. */ +export const PageOrder = { + /** The numeric ids */ + Id: 'id', + /** + * The creation order. Entities created at the same time keep the order of + * their ids. Partitions and consumer groups walk by id in this order too, + * because their ids follow creation. + */ + Created: 'created' +} as const; + +export type PageOrder = typeof PageOrder[keyof typeof PageOrder]; + +/** The wire code of each order. */ +export const PAGE_ORDER_CODE: Readonly<Record<PageOrder, number>> = { id: 0, created: 1 }; + +/** + * The position after which the next page of a list starts. Send it back as + * you got it, with the query that returned it: it holds no order, direction, + * filter or parent. Only the server reads its bytes, so the client keeps any + * 1 to 255 bytes as they came, and the server refuses a cursor that it cannot + * use. + * + * Its text form, `toString()` and `toJSON()`, is `pg1_` followed by unpadded + * Base64url of the bytes. + */ +export class PageCursor { + readonly #bytes: Buffer; + + private constructor(bytes: Buffer) { + this.#bytes = bytes; + } + + /** + * Reads the text form. Anything but the prefix and canonical unpadded + * Base64url of 1 to 255 bytes is refused. + * + * @throws ResponseError with code 3 (invalid command) + */ + static parse(text: string): PageCursor { + if (text.length > MAX_PAGE_CURSOR_TEXT_LENGTH) + throw responseError(NO_COMMAND, INVALID_COMMAND, `a page cursor holds at most ${MAX_PAGE_CURSOR_SIZE} bytes`); + const bytes = decodeCanonicalBase64(text, PAGE_CURSOR_PREFIX, NO_COMMAND); + if (bytes.length === 0) + throw responseError(NO_COMMAND, INVALID_COMMAND, 'a page cursor holds at least one byte'); + return new PageCursor(bytes); + } + + /** + * Keeps a copy of the cursor bytes a reply carries. + * + * @throws DeserializeError for 0 or more than 255 bytes + */ + static fromBytes(bytes: Buffer): PageCursor { + if (bytes.length === 0 || bytes.length > MAX_PAGE_CURSOR_SIZE) + throw new DeserializeError( + `cannot deserialize a page cursor of ${bytes.length} bytes, it holds 1 to ${MAX_PAGE_CURSOR_SIZE}` + ); + return new PageCursor(Buffer.from(bytes)); + } + + /** A copy of the bytes a list request carries */ + toBytes(): Buffer { + return Buffer.from(this.#bytes); + } + + toString(): string { + return PAGE_CURSOR_PREFIX + this.#bytes.toString('base64url'); + } + + toJSON(): string { + return this.toString(); + } +} + +/** + * One page request of a list command. To read the next page, send the same + * query with the `next` of the page as its `cursor`. + * + * Refused with `ResponseError` code 3 (invalid command) before anything is + * sent: an unknown order, a limit outside 1 to 1000 and a cursor that is not a + * `PageCursor`. + */ +export type PageQuery = { + /** Defaults to `id` */ + order?: PageOrder, + /** Walks from the end of the order, false when absent */ + descending?: boolean, + /** Items per page, 1 to 1000, 100 when absent */ + limit?: number, + /** The `next` of the previous page, absent for the first page */ + cursor?: PageCursor +}; + +/** + * One page request of a list whose entries have a name: streams, topics, + * consumer groups and users. Also refused before anything is sent: a name + * that is empty, longer than 255 bytes of UTF-8 or not well-formed Unicode. + */ +export type NamedPageQuery = PageQuery & { + /** Keeps only the entries whose name holds this text, case-sensitive */ + name?: string +}; + +/** One page of a list. A page can be short or empty and still have a `next`. */ +export type Page<T> = { + items: T[], + /** The cursor of the next page, absent on the last page */ + next?: PageCursor +}; + +/** Reads one item at `position`, returning it with its size. */ +export type PageItemReader<T> = (payload: Buffer, position: number) => { bytesRead: number, data: T }; + +/** + * The page block that ends every list request: `[order:u8][descending:u8] + * [limit:u32][cursor_len:u8][cursor][name_len:u8][name]`. A length of 0 means + * no cursor or no name. + * + * @throws ResponseError with code 3 (invalid command) against `commandCode` + * for a query that breaks a page rule + */ +export const serializeNamedPageQuery = (commandCode: number, query: NamedPageQuery): Buffer => { + const { order = PageOrder.Id, descending = false, limit = DEFAULT_PAGE_LIMIT, cursor, name } = query; + const refused = (detail: string) => responseError(commandCode, INVALID_COMMAND, detail); + if (!Object.hasOwn(PAGE_ORDER_CODE, order)) + throw refused(`unknown order ${order}`); + if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) + throw refused(`limit ${limit} is outside 1 to ${MAX_PAGE_LIMIT}`); + if (cursor !== undefined && !(cursor instanceof PageCursor)) + throw refused('a cursor is a PageCursor'); + const nameBytes = Buffer.from(name ?? '', 'utf8'); + if (name !== undefined && (nameBytes.length < 1 || nameBytes.length > MAX_PAGE_NAME_SIZE)) + throw refused(`a name holds 1 to ${MAX_PAGE_NAME_SIZE} bytes of UTF-8, got ${nameBytes.length}`); + // UTF-8 replaces a lone surrogate, so the server would read another name. + if (name !== undefined && nameBytes.toString('utf8') !== name) + throw refused('a name is well-formed Unicode text'); + + const cursorBytes = cursor?.toBytes() ?? Buffer.alloc(0); + const block = Buffer.alloc(PAGE_BLOCK_FIXED_SIZE + cursorBytes.length + nameBytes.length); + let position = block.writeUInt8(PAGE_ORDER_CODE[order], 0); + position = block.writeUInt8(descending ? 1 : 0, position); + position = block.writeUInt32LE(limit, position); + position = block.writeUInt8(cursorBytes.length, position); + position += cursorBytes.copy(block, position); + position = block.writeUInt8(nameBytes.length, position); + nameBytes.copy(block, position); + return block; +}; + +/** + * The page block of a list without a name filter, so its name length is 0. + * + * @throws ResponseError with code 3 (invalid command) against `commandCode` + * for a query that breaks a page rule or that has a `name` property + */ +export const serializePageQuery = (commandCode: number, query: PageQuery): Buffer => { + // TypeScript lets a NamedPageQuery pass as a PageQuery, and JS callers skip types. + if ((query as NamedPageQuery).name !== undefined) + throw responseError(commandCode, INVALID_COMMAND, 'this list has no name filter'); + return serializeNamedPageQuery(commandCode, query); +}; + +/** + * Reads the reply of a list command: `[next_len:u8][next][count:u32][item]*`. + * A body short of `count` items, or with bytes after them, is refused. The + * next cursor keeps its bytes as they came, because only the server reads + * them. + * + * @throws DeserializeError for a malformed reply + */ +export const deserializePage = <T>(payload: Buffer, readItem: PageItemReader<T>): Page<T> => { + if (payload.length === 0) + deserializeError(PAGE_NAME, 0, payload.length, 1); + const countPosition = 1 + payload.readUInt8(0); + let position = countPosition + PAGE_COUNT_SIZE; + if (payload.length < position) + deserializeError(PAGE_NAME, 0, payload.length, position); + const count = payload.readUInt32LE(countPosition); + + const items: T[] = []; + for (let index = 0; index < count; index++) { + let item: { bytesRead: number, data: T }; + try { + item = readItem(payload, position); + } catch (cause) { + throw new DeserializeError(`cannot deserialize ${PAGE_NAME}: item ${index} of ${count}`, { cause }); + } + position += item.bytesRead; + items.push(item.data); + } + // An item decoder can cut a name short and still count its full length, so + // the items can end past the reply as well as before its end. + if (position !== payload.length) + throw new DeserializeError( + `cannot deserialize ${PAGE_NAME}: its ${count} items end at byte ${position} of ${payload.length}` + ); + return countPosition === 1 + ? { items } + : { items, next: PageCursor.fromBytes(payload.subarray(1, countPosition)) }; +}; + +/** + * Reads a whole list one page at a time, in ascending id order and in pages + * of 1000, until a page has no next cursor. The result is not one consistent + * read: an entity that someone creates or deletes during the walk can appear + * or not appear. The walk keeps the sign-in and the deadline that it started + * with. + * + * @throws DeserializeError for a page whose next cursor is the cursor its + * request sent, because the walk would never end + */ +export const readWholeList = async <I, T>( + getClient: ClientProvider, command: Command<I, Page<T>>, request: (query: PageQuery) => I +): Promise<T[]> => { + const client = await getClient(); + const release = client.hold?.(); + try { + const call = { deadline: Date.now() + OPERATION_TIMEOUT_MS, lineage: client.lineage }; + const items: T[] = []; + let query: PageQuery = { order: PageOrder.Id, descending: false, limit: MAX_PAGE_LIMIT }; + for (;;) { + const page = command.deserialize( + await client.sendCommand(command.code, command.serialize(request(query)), call)); + // One push per item: a spread of a huge page could overflow the call stack. + for (const item of page.items) + items.push(item); + if (page.next === undefined) + return items; + if (query.cursor?.toBytes().equals(page.next.toBytes())) + throw new DeserializeError( + `cannot deserialize ${PAGE_NAME}: the server answered the page cursor it was sent` + ); + query = { ...query, cursor: page.next }; + } + } finally { + release?.(); + } +};
diff --git a/foreign/node/src/wire/partition/get-partitions.command.ts b/foreign/node/src/wire/partition/get-partitions.command.ts new file mode 100644 index 0000000..8ec2574 --- /dev/null +++ b/foreign/node/src/wire/partition/get-partitions.command.ts
@@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import type { CommandResponse } from '../../client/client.type.js'; +import { wrapCommand } from '../command.utils.js'; +import { COMMAND_CODE } from '../command.code.js'; +import { serializeIdentifier, type Id } from '../identifier.utils.js'; +import { deserializePage, serializePageQuery, type Page, type PageQuery } from '../page.utils.js'; +import { deserializePartition, type Partition } from '../topic/topic.utils.js'; + +/** + * Parameters for the get partitions page command: the topic and one page + * request. A partition has no name, so the request is a `PageQuery`. The + * client refuses a request with a name before it sends anything. + */ +export type GetPartitionsPage = { + /** Stream identifier (ID or name) */ + streamId: Id, + /** Topic identifier (ID or name) */ + topicId: Id +} & PageQuery; + +/** + * Get partitions command definition. + * Retrieves one page of the partitions of a topic. + */ +export const GET_PARTITIONS = { + code: COMMAND_CODE.GetPartitions, + + serialize: ({ streamId, topicId, ...query }: GetPartitionsPage) => Buffer.concat([ + serializeIdentifier(streamId), + serializeIdentifier(topicId), + serializePageQuery(COMMAND_CODE.GetPartitions, query) + ]), + + deserialize: (r: CommandResponse) => deserializePage(r.data, deserializePartition) +}; + +/** + * Executable get partitions page command function. + */ +export const getPartitionsPage = wrapCommand<GetPartitionsPage, Page<Partition>>(GET_PARTITIONS);
diff --git a/foreign/node/src/wire/partition/index.ts b/foreign/node/src/wire/partition/index.ts index 51911b9..031a006 100644 --- a/foreign/node/src/wire/partition/index.ts +++ b/foreign/node/src/wire/partition/index.ts
@@ -17,3 +17,4 @@ export * from './create-partition.command.js'; export * from './delete-partition.command.js'; +export * from './get-partitions.command.js';
diff --git a/foreign/node/src/wire/stream/get-streams.command.ts b/foreign/node/src/wire/stream/get-streams.command.ts index d424ddc..2ce47d3 100644 --- a/foreign/node/src/wire/stream/get-streams.command.ts +++ b/foreign/node/src/wire/stream/get-streams.command.ts
@@ -15,35 +15,33 @@ // specific language governing permissions and limitations // under the License. -import type { CommandResponse } from '../../client/client.type.js'; +import type { ClientProvider, CommandResponse } from '../../client/client.type.js'; import { wrapCommand } from '../command.utils.js'; import { COMMAND_CODE } from '../command.code.js'; +import { + deserializePage, readWholeList, serializeNamedPageQuery, type NamedPageQuery, type Page +} from '../page.utils.js'; import { deserializeToStream, type Stream } from './stream.utils.js'; /** * Get streams command definition. - * Retrieves all streams. + * Retrieves one page of the streams. */ export const GET_STREAMS = { code: COMMAND_CODE.GetStreams, - serialize: () => Buffer.alloc(0), + serialize: (query: NamedPageQuery) => serializeNamedPageQuery(COMMAND_CODE.GetStreams, query), - deserialize: (r: CommandResponse) => { - const payloadSize = r.data.length; - const streams = []; - let pos = 0; - while (pos < payloadSize) { - const { bytesRead, data } = deserializeToStream(r.data, pos) - streams.push(data); - pos += bytesRead; - } - return streams; - } + deserialize: (r: CommandResponse) => deserializePage(r.data, deserializeToStream) }; +/** + * Executable get streams page command function. + */ +export const getStreamsPage = wrapCommand<NamedPageQuery, Page<Stream>>(GET_STREAMS); /** - * Executable get streams command function. + * Executable get streams command function. Reads every stream page by page. */ -export const getStreams = wrapCommand<void, Stream[]>(GET_STREAMS); +export const getStreams = (c: ClientProvider) => + (): Promise<Stream[]> => readWholeList(c, GET_STREAMS, (query) => query);
diff --git a/foreign/node/src/wire/system/metadata-changes.utils.ts b/foreign/node/src/wire/system/metadata-changes.utils.ts index 3533197..2efb22b 100644 --- a/foreign/node/src/wire/system/metadata-changes.utils.ts +++ b/foreign/node/src/wire/system/metadata-changes.utils.ts
@@ -499,7 +499,9 @@ static parse(text: string): MetadataChangeCursor { if (text.length !== CURSOR_TEXT_LENGTH) throw invalidCommand('a change cursor is 63 characters'); - const cursor = decodeCursor(decodeCanonicalBase64(text, METADATA_CHANGE_CURSOR_PREFIX)); + const cursor = decodeCursor( + decodeCanonicalBase64(text, METADATA_CHANGE_CURSOR_PREFIX, COMMAND_CODE.GetMetadataChanges) + ); if (cursor === undefined) throw invalidCommand(NON_CANONICAL_CURSOR); return cursor; @@ -545,7 +547,9 @@ static parse(text: string): MetadataCurrentPageToken { if (text.length > MAX_PAGE_TOKEN_TEXT_LENGTH) throw invalidCommand('the page token is too long'); - const payload = decodeCanonicalBase64(text, METADATA_CURRENT_PAGE_TOKEN_PREFIX); + const payload = decodeCanonicalBase64( + text, METADATA_CURRENT_PAGE_TOKEN_PREFIX, COMMAND_CODE.GetMetadataChanges + ); const refusal = pageTokenRefusal(payload); if (refusal !== undefined) throw invalidCommand(refusal); @@ -1125,14 +1129,16 @@ /** * Strips `prefix` and decodes unpadded Base64url that encodes back to the * same text, so one value has exactly one text form. + * + * @throws ResponseError with code 3 (invalid command) against `commandCode` */ -const decodeCanonicalBase64 = (text: string, prefix: string): Buffer => { +export const decodeCanonicalBase64 = (text: string, prefix: string, commandCode: number): Buffer => { if (!text.startsWith(prefix)) - throw invalidCommand(`expected the ${prefix} prefix`); + throw responseError(commandCode, INVALID_COMMAND, `expected the ${prefix} prefix`); const encoded = text.slice(prefix.length); const bytes = Buffer.from(encoded, 'base64url'); if (bytes.toString('base64url') !== encoded) - throw invalidCommand('expected canonical unpadded Base64url'); + throw responseError(commandCode, INVALID_COMMAND, 'expected canonical unpadded Base64url'); return bytes; };
diff --git a/foreign/node/src/wire/topic/get-topics.command.ts b/foreign/node/src/wire/topic/get-topics.command.ts index 0780e43..624ddc4 100644 --- a/foreign/node/src/wire/topic/get-topics.command.ts +++ b/foreign/node/src/wire/topic/get-topics.command.ts
@@ -15,11 +15,14 @@ // specific language governing permissions and limitations // under the License. -import type { CommandResponse } from '../../client/client.type.js'; +import type { ClientProvider, CommandResponse } from '../../client/client.type.js'; import { wrapCommand } from '../command.utils.js'; import { COMMAND_CODE } from '../command.code.js'; import { serializeIdentifier, type Id } from '../identifier.utils.js'; -import { deserializeTopics, type Topic } from './topic.utils.js'; +import { + deserializePage, readWholeList, serializeNamedPageQuery, type NamedPageQuery, type Page +} from '../page.utils.js'; +import { deserializeBaseTopic, type Topic } from './topic.utils.js'; /** * Parameters for the get topics command. @@ -30,22 +33,40 @@ }; /** + * Parameters for the get topics page command: the stream and one page request. + */ +export type GetTopicsPage = GetTopics & NamedPageQuery; + +/** * Get topics command definition. - * Retrieves all topics within a stream. + * Retrieves one page of the topics within a stream. A topic of a page carries + * no partition details. */ export const GET_TOPICS = { code: COMMAND_CODE.GetTopics, - serialize: ({streamId}: GetTopics) => { - return serializeIdentifier(streamId); - }, + serialize: ({ streamId, ...query }: GetTopicsPage) => Buffer.concat([ + serializeIdentifier(streamId), + serializeNamedPageQuery(COMMAND_CODE.GetTopics, query) + ]), - deserialize: (r: CommandResponse) => { - return deserializeTopics(r.data); - } + deserialize: (r: CommandResponse) => deserializePage(r.data, deserializeTopicHeader) }; /** - * Executable get topics command function. + * Executable get topics page command function. */ -export const getTopics = wrapCommand<GetTopics, Topic[]>(GET_TOPICS); +export const getTopicsPage = wrapCommand<GetTopicsPage, Page<Topic>>(GET_TOPICS); + +/** + * Executable get topics command function. Reads every topic of the stream page + * by page. + */ +export const getTopics = (c: ClientProvider) => + ({ streamId }: GetTopics): Promise<Topic[]> => + readWholeList(c, GET_TOPICS, (query) => ({ streamId, ...query })); + +const deserializeTopicHeader = (p: Buffer, pos: number): { bytesRead: number, data: Topic } => { + const { bytesRead, data } = deserializeBaseTopic(p, pos); + return { bytesRead, data: { ...data, partitions: [] } }; +};
diff --git a/foreign/node/src/wire/topic/topic.utils.ts b/foreign/node/src/wire/topic/topic.utils.ts index f4c6990..587cdd1 100644 --- a/foreign/node/src/wire/topic/topic.utils.ts +++ b/foreign/node/src/wire/topic/topic.utils.ts
@@ -306,27 +306,6 @@ return { bytesRead: pos - start, data: { ...data, partitions } }; }; - -/** - * Deserializes a GetTopics response: `[topics_count:u32_le]` prefix followed - * by count-driven topic headers (no partition details). - * - * @param p - Buffer containing serialized topics data - * @param pos - Starting position in the buffer - * @returns Array of deserialized topics - */ -export const deserializeTopics = (p: Buffer, pos = 0): Topic[] => { - const topicsCount = p.readUInt32LE(pos); - pos += 4; - const topics = []; - for (let i = 0; i < topicsCount; i++) { - const { bytesRead, data } = deserializeBaseTopic(p, pos); - topics.push({ ...data, partitions: [] }); - pos += bytesRead; - } - return topics; -}; - export const Durability = { Replicated: 'replicated', Persisted: 'persisted'
diff --git a/foreign/node/src/wire/user/get-users.command.ts b/foreign/node/src/wire/user/get-users.command.ts index 0930c3b..d6555f3 100644 --- a/foreign/node/src/wire/user/get-users.command.ts +++ b/foreign/node/src/wire/user/get-users.command.ts
@@ -15,26 +15,35 @@ // specific language governing permissions and limitations // under the License. -import type { CommandResponse } from '../../client/client.type.js'; +import type { ClientProvider, CommandResponse } from '../../client/client.type.js'; import { wrapCommand } from '../command.utils.js'; import { COMMAND_CODE } from '../command.code.js'; -import { deserializeUsers, type BaseUser } from './user.utils.js'; +import { + deserializePage, readWholeList, serializeNamedPageQuery, type NamedPageQuery, type Page +} from '../page.utils.js'; +import { deserializeBaseUser, type BaseUser } from './user.utils.js'; /** * Get users command definition. - * Retrieves all users (without permissions). + * Retrieves one page of the users (without permissions). */ export const GET_USERS = { code: COMMAND_CODE.GetUsers, - serialize: () => Buffer.alloc(0), + serialize: (query: NamedPageQuery) => serializeNamedPageQuery(COMMAND_CODE.GetUsers, query), - deserialize: (r: CommandResponse) => deserializeUsers(r.data) + deserialize: (r: CommandResponse) => deserializePage(r.data, deserializeBaseUser) }; /** - * Executable get users command function. + * Executable get users page command function. */ -export const getUsers = wrapCommand<void, BaseUser[]>(GET_USERS); +export const getUsersPage = wrapCommand<NamedPageQuery, Page<BaseUser>>(GET_USERS); + +/** + * Executable get users command function. Reads every user page by page. + */ +export const getUsers = (c: ClientProvider) => + (): Promise<BaseUser[]> => readWholeList(c, GET_USERS, (query) => query);
diff --git a/foreign/node/src/wire/user/user.utils.ts b/foreign/node/src/wire/user/user.utils.ts index 4a6fd2c..d41cf80 100644 --- a/foreign/node/src/wire/user/user.utils.ts +++ b/foreign/node/src/wire/user/user.utils.ts
@@ -130,22 +130,3 @@ return { ...data, permissions }; }; - - -/** - * Deserializes multiple base users from a buffer. - * - * @param p - Buffer containing serialized users data - * @param pos - Starting position in the buffer - * @returns Array of deserialized base users - */ -export const deserializeUsers = (p: Buffer, pos = 0): BaseUser[] => { - const users = []; - const end = p.length; - while (pos < end) { - const { bytesRead, data } = deserializeBaseUser(p, pos); - users.push(data); - pos += bytesRead; - } - return users; -};
diff --git a/foreign/node/src/wire/vsr/register.ts b/foreign/node/src/wire/vsr/register.ts index 53ae201..8c7294e 100644 --- a/foreign/node/src/wire/vsr/register.ts +++ b/foreign/node/src/wire/vsr/register.ts
@@ -30,11 +30,11 @@ /** * Packed protocol semver of the wire contract this port implements, - * `pack(0, 12, 2)` per `core/binary_protocol/src/version.rs`. Update with the + * `pack(0, 12, 3)` per `core/binary_protocol/src/version.rs`. Update with the * Rust constant during stable release preparation. Edge builds sharing this * number are not guaranteed to have compatible layouts. */ -export const IGGY_PROTOCOL_VERSION = (0 << 20) | (12 << 10) | 2; +export const IGGY_PROTOCOL_VERSION = (0 << 20) | (12 << 10) | 3; const SDK_NAME = 'node-sdk';
diff --git a/foreign/php/Cargo.toml b/foreign/php/Cargo.toml index 4f2d333..4d3420c 100644 --- a/foreign/php/Cargo.toml +++ b/foreign/php/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy-php" -version = "0.2.0" +version = "0.2.1" edition = "2024" authors = ["Iggy Committers <dev@iggy.apache.org>"] license = "Apache-2.0"
diff --git a/foreign/php/README.md b/foreign/php/README.md index 891c56e..fcabf72 100644 --- a/foreign/php/README.md +++ b/foreign/php/README.md
@@ -254,6 +254,32 @@ - `describeOptions(Iggy\OptionsScope)` returns the server catalog as `Iggy\OptionSpec` objects with `key`, `kind`, `updatable`, `resettable`, `secret`, `read_only`, `critical`, `default_value` and `description`. - SDK exceptions carry the server error code in `getCode()`, for example 4103 (option cannot be updated), 4104 (option cannot be reset), 4105 (read-only option), 4108 (root user cannot be changed by this caller), 4041 (unsupported option key) and 2018 (invalid replication factor). +## List Pages + +`getStreamsPage()`, `getTopicsPage()`, `getPartitionsPage()`, `getConsumerGroupsPage()` and `getUsersPage()` read one page of a list. Named arguments set the order, the direction, the limit, the cursor and a name filter. To read the next page, call the method again with the same arguments and the `next` of the page as `cursor`. A page can be empty and still have a `next`, so a walk ends at the first page without one. + +```php +use Iggy\PageOrder; + +$cursor = null; +do { + $page = $client->getStreamsPage(order: PageOrder::Created, limit: 50, cursor: $cursor, name: 'orders'); + foreach ($page->items as $stream) { + echo $stream->id, ' ', $stream->name, PHP_EOL; + } + $cursor = $page->next; +} while ($cursor !== null); +``` + +- A null `order` reads in `PageOrder::Id` order, and `descending: true` reverses the order. `PageOrder::Created` sorts by creation time and then by id. Partitions and consumer groups walk by id in both orders, because their ids follow creation. +- `limit` is 1 to 1000, and a null `limit` reads 100. `name` keeps the entries whose name holds the text, case-sensitive, and is 1 to 255 bytes. A partition has no name, so `getPartitionsPage()` takes no `name`. +- A cursor is the `pg1_` text that the CLI and the HTTP API use. It holds only a position, so send it back with the same order, direction, filter and parent ids. +- A query out of range, or a cursor text that the client cannot read, throws `Invalid command` (code 3) before anything is sent. The server refuses a cursor that does not fit the query, and a partition name, with the same error. Over HTTP, these server refusals throw code 300, and the message holds the server's error. +- The argument check runs first. A `limit` that is not an integer or does not fit 32 unsigned bits throws `IggyException` with code 0. +- Each page is a separate read. An entity that someone creates or deletes during a walk can appear or not appear, so a walk is not a snapshot. `getMetadataChanges()` gives an exact copy. `getTopicsPage()` of a stream that does not exist returns an empty page without `next`. +- Pages hold `Iggy\Stream`, `Iggy\Topic`, `Iggy\Partition`, `Iggy\ConsumerGroup` or `Iggy\UserInfo` objects with readonly snake_case properties. `created_at` is in microseconds. Streams, topics and users return `options` and `derived_options` arrays like `StreamDetails`, and streams also return its three `encryption_*` properties. +- The reply of `getStream()` or `getTopic()` can pass the server cap of a little over 64 MB. Over TCP, QUIC and WebSocket, the call then throws `ReplyTooLarge` (code 97). The connection stays usable, and `getTopicsPage()` and `getPartitionsPage()` read such a stream or topic in pages. + ## Metadata Changes `getMetadataChanges()` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `next` cursor. The call needs root or the global `manage_servers` permission, and a query the server would refuse throws `Invalid command` (code 3) before anything is sent.
diff --git a/foreign/php/iggy-php.stubs.php b/foreign/php/iggy-php.stubs.php index f9f096b..e13982a 100644 --- a/foreign/php/iggy-php.stubs.php +++ b/foreign/php/iggy-php.stubs.php
@@ -302,6 +302,21 @@ public static function fromConnectionString(string $connection_string): \Iggy\Client {} /** + * Reads one page of the consumer groups of a topic. Group ids follow creation, so both + * orders walk by id. The other arguments are those of getStreamsPage(). + * + * @param mixed $stream_id + * @param mixed $topic_id + * @param \Iggy\PageOrder|null $order + * @param bool $descending + * @param mixed $limit + * @param string|null $cursor + * @param string|null $name + * @return \Iggy\ConsumerGroupsPage + */ + public function getConsumerGroupsPage(mixed $stream_id, mixed $topic_id, ?\Iggy\PageOrder $order = null, bool $descending = false, mixed $limit = null, ?string $cursor = null, ?string $name = null): \Iggy\ConsumerGroupsPage {} + + /** * Returns the offset stored on `partition_id` for a standalone consumer, or for a consumer * group when `group` is true, or null when nothing is stored. In a cluster the node of the * connection answers from its own replica, which can lag a store that just returned. @@ -335,16 +350,60 @@ public function getMetadataChanges(\Iggy\MetadataChangeStart $start, array $groups = [], mixed $since = null, mixed $until = null, mixed $limit = null): \Iggy\MetadataChanges {} /** + * Reads one page of the partitions of a topic. Partition ids follow creation, so both + * orders walk by id. The other arguments are those of getStreamsPage() except `name`, + * because a partition has no name. + * + * @param mixed $stream_id + * @param mixed $topic_id + * @param \Iggy\PageOrder|null $order + * @param bool $descending + * @param mixed $limit + * @param string|null $cursor + * @return \Iggy\PartitionsPage + */ + public function getPartitionsPage(mixed $stream_id, mixed $topic_id, ?\Iggy\PageOrder $order = null, bool $descending = false, mixed $limit = null, ?string $cursor = null): \Iggy\PartitionsPage {} + + /** * Gets a stream by id or name. * + * Over TCP, QUIC and WebSocket, a stream with too many topics for one reply throws + * ReplyTooLarge (97), and the connection stays usable. getTopicsPage() reads its topics + * page by page. + * * @param mixed $stream_id * @return \Iggy\StreamDetails|null */ public function getStream(mixed $stream_id): ?\Iggy\StreamDetails {} /** + * Reads one page of the streams. + * + * `order` is `Iggy\PageOrder::Id` when null, and `descending` reverses it. `limit` is 1 to + * 1000, 100 when null. `cursor` is the `next` of the previous page, null for the first + * page. `name` keeps the streams whose name holds the text, case-sensitive, and is 1 to + * 255 bytes. A query outside these ranges, or a cursor text that the client cannot read, + * throws `Invalid command` (code 3) before anything is sent. The server refuses a cursor + * that does not fit the query with the same error, which HTTP reports as code 300. A + * `limit` that is not an integer, or that does not fit an unsigned 32-bit integer, throws + * `IggyException` with code 0 from the argument check. + * + * @param \Iggy\PageOrder|null $order + * @param bool $descending + * @param mixed $limit + * @param string|null $cursor + * @param string|null $name + * @return \Iggy\StreamsPage + */ + public function getStreamsPage(?\Iggy\PageOrder $order = null, bool $descending = false, mixed $limit = null, ?string $cursor = null, ?string $name = null): \Iggy\StreamsPage {} + + /** * Gets a topic by stream and topic id/name. * + * Over TCP, QUIC and WebSocket, a topic with too many partitions for one reply throws + * ReplyTooLarge (97), and the connection stays usable. getPartitionsPage() reads its + * partitions page by page. + * * @param mixed $stream_id * @param mixed $topic_id * @return \Iggy\TopicDetails|null @@ -352,6 +411,33 @@ public function getTopic(mixed $stream_id, mixed $topic_id): ?\Iggy\TopicDetails {} /** + * Reads one page of the topics of a stream. A missing stream gives an empty page without + * `next`. The other arguments are those of getStreamsPage(). + * + * @param mixed $stream_id + * @param \Iggy\PageOrder|null $order + * @param bool $descending + * @param mixed $limit + * @param string|null $cursor + * @param string|null $name + * @return \Iggy\TopicsPage + */ + public function getTopicsPage(mixed $stream_id, ?\Iggy\PageOrder $order = null, bool $descending = false, mixed $limit = null, ?string $cursor = null, ?string $name = null): \Iggy\TopicsPage {} + + /** + * Reads one page of the users, and `name` matches the username. The other arguments are + * those of getStreamsPage(). + * + * @param \Iggy\PageOrder|null $order + * @param bool $descending + * @param mixed $limit + * @param string|null $cursor + * @param string|null $name + * @return \Iggy\UsersPage + */ + public function getUsersPage(?\Iggy\PageOrder $order = null, bool $descending = false, mixed $limit = null, ?string $cursor = null, ?string $name = null): \Iggy\UsersPage {} + + /** * Builds a reader of the partitions that a consumer group assigns to this member. * * The group must exist: the reader joins it, joins again after a session loss, and leaves @@ -892,6 +978,46 @@ } /** + * One consumer group of a `ConsumerGroupsPage`. + */ + class ConsumerGroup { + public readonly int $id; + + public readonly int $members_count; + + public readonly string $name; + + public readonly int $partitions_count; + + public function __construct() {} + } + + /** + * One page of the consumer groups of a topic, as `Client::getConsumerGroupsPage()` returns it. + */ + class ConsumerGroupsPage { + /** + * The consumer groups of the page, each an `Iggy\ConsumerGroup`. + * + * The items are rebuilt on each getter call, so cache the array in PHP if you read it + * more than once. + * + * @var array + */ + public readonly array $items; + + /** + * The `cursor` of the next page of the same query, null on the last page. A page can be + * empty and still have one. + * + * @var string|null + */ + public readonly ?string $next; + + public function __construct() {} + } + + /** * The offset that a consumer stored on a partition. */ class ConsumerOffsetInfo { @@ -2146,6 +2272,14 @@ } /** + * The order of a list page. Values are the HTTP API names. + */ + enum PageOrder: string { + case Id = 'id'; + case Created = 'created'; + } + + /** * One partition of a topic. */ class Partition { @@ -2294,6 +2428,31 @@ } /** + * One page of the partitions of a topic, as `Client::getPartitionsPage()` returns it. + */ + class PartitionsPage { + /** + * The partitions of the page, each an `Iggy\Partition`. + * + * The items are rebuilt on each getter call, so cache the array in PHP if you read it + * more than once. + * + * @var array + */ + public readonly array $items; + + /** + * The `cursor` of the next page of the same query, null on the last page. A page can be + * empty and still have one. + * + * @var string|null + */ + public readonly ?string $next; + + public function __construct() {} + } + + /** * Client-wide limits for active and retained mutation frames, including queued writer bytes. */ class PendingOperationsConfig { @@ -2637,6 +2796,69 @@ public function __construct() {} } + /** + * One stream of a `StreamsPage`. + */ + class Stream { + /** + * Creation time in microseconds. + * + * @var int + */ + public readonly int $created_at; + + /** + * Options the server filled in, including the read-only encryption projections. + * + * @var array + */ + public readonly array $derived_options; + + /** + * Fingerprints of the server keys that wrap the stream's key, comma-separated: one + * outside a server key rotation. Null for a plaintext stream. + * + * @var string|null + */ + public readonly ?string $encryption_kek_fingerprint; + + /** + * Fingerprint of the stream's key, 16 lowercase hex characters. Compare it with + * `Client::encryptionKeyFingerprint()` of a key you hold. Null for a plaintext stream. + * + * @var string|null + */ + public readonly ?string $encryption_key_fingerprint; + + /** + * Who chose the stream's at-rest key: `stream`, `server`, or `none` for a plaintext + * stream. A source a newer server reports is returned as its text. + * + * @var string|null + */ + public readonly ?string $encryption_key_source; + + public readonly int $id; + + public readonly int $messages_count; + + public readonly string $name; + + /** + * Options the creating client set, as option name to scalar value. Key material is + * never returned. + * + * @var array + */ + public readonly array $options; + + public readonly int $size_bytes; + + public readonly int $topics_count; + + public function __construct() {} + } + class StreamDetails { /** * Options the server filled in, including the read-only encryption projections. @@ -2702,6 +2924,71 @@ case EncryptionKekFingerprint = 'encryption_kek_fingerprint'; } + /** + * One page of the streams, as `Client::getStreamsPage()` returns it. + */ + class StreamsPage { + /** + * The streams of the page, each an `Iggy\Stream`. + * + * The items are rebuilt on each getter call, so cache the array in PHP if you read it + * more than once. + * + * @var array + */ + public readonly array $items; + + /** + * The `cursor` of the next page of the same query, null on the last page. A page can be + * empty and still have one. + * + * @var string|null + */ + public readonly ?string $next; + + public function __construct() {} + } + + /** + * One topic of a `TopicsPage`. + */ + class Topic { + /** + * Creation time in microseconds. + * + * @var int + */ + public readonly int $created_at; + + /** + * Options the server filled in from its catalog defaults. + * + * @var array + */ + public readonly array $derived_options; + + public readonly int $id; + + public readonly int $messages_count; + + public readonly string $name; + + /** + * Options the creating or updating client set, as option name to scalar value. + * Integers above `PHP_INT_MAX`, such as never-expire and unlimited + * (18446744073709551615), are decimal strings. + * + * @var array + */ + public readonly array $options; + + public readonly int $partitions_count; + + public readonly int $size_bytes; + + public function __construct() {} + } + class TopicDetails { /** * Options the server filled in from its catalog defaults. @@ -2764,6 +3051,95 @@ case LocalRetentionAge = 'local_retention_age'; case LocalRetentionSize = 'local_retention_size'; } + + /** + * One page of the topics of a stream, as `Client::getTopicsPage()` returns it. + */ + class TopicsPage { + /** + * The topics of the page, each an `Iggy\Topic`. + * + * The items are rebuilt on each getter call, so cache the array in PHP if you read it + * more than once. + * + * @var array + */ + public readonly array $items; + + /** + * The `cursor` of the next page of the same query, null on the last page. A page can be + * empty and still have one. + * + * @var string|null + */ + public readonly ?string $next; + + public function __construct() {} + } + + /** + * One user of a `UsersPage`. + */ + class UserInfo { + /** + * Creation time in microseconds. + * + * @var int + */ + public readonly int $created_at; + + /** + * Options the server filled in. + * + * @var array + */ + public readonly array $derived_options; + + public readonly int $id; + + /** + * Options the creating client set, as option name to scalar value. + * + * @var array + */ + public readonly array $options; + + /** + * `active` or `inactive`. + * + * @var string + */ + public readonly string $status; + + public readonly string $username; + + public function __construct() {} + } + + /** + * One page of the users, as `Client::getUsersPage()` returns it. + */ + class UsersPage { + /** + * The users of the page, each an `Iggy\UserInfo`. + * + * The items are rebuilt on each getter call, so cache the array in PHP if you read it + * more than once. + * + * @var array + */ + public readonly array $items; + + /** + * The `cursor` of the next page of the same query, null on the last page. A page can be + * empty and still have one. + * + * @var string|null + */ + public readonly ?string $next; + + public function __construct() {} + } } namespace Iggy\Exception {
diff --git a/foreign/php/src/client.rs b/foreign/php/src/client.rs index 660cf8a..4f24d56 100644 --- a/foreign/php/src/client.rs +++ b/foreign/php/src/client.rs
@@ -38,6 +38,10 @@ use crate::identifier::PhpIdentifier; use crate::metadata_changes::{MetadataChangeGroup, MetadataChangeStart, MetadataChanges}; use crate::options::{OptionSpec, OptionsScope, StreamOptionKey, TopicOptionKey, reset_names}; +use crate::page::{ + ConsumerGroupsPage, PageOrder, PartitionsPage, StreamsPage, TopicsPage, UsersPage, + named_page_query, page_query, +}; use crate::pending_poll::PendingPoll; use crate::poll_options::PollOptions; use crate::reader::PartitionReader; @@ -284,6 +288,10 @@ } /// Gets a stream by id or name. + /// + /// Over TCP, QUIC and WebSocket, a stream with too many topics for one reply throws + /// ReplyTooLarge (97), and the connection stays usable. getTopicsPage() reads its topics + /// page by page. pub fn get_stream(&self, stream_id: PhpIdentifier) -> PhpResult<Option<StreamDetails>> { let stream_id: Identifier = stream_id.try_into()?; let inner = self.inner.clone(); @@ -545,6 +553,10 @@ } /// Gets a topic by stream and topic id/name. + /// + /// Over TCP, QUIC and WebSocket, a topic with too many partitions for one reply throws + /// ReplyTooLarge (97), and the connection stays usable. getPartitionsPage() reads its + /// partitions page by page. pub fn get_topic( &self, stream_id: PhpIdentifier, @@ -563,6 +575,140 @@ }) } + /// Reads one page of the streams. + /// + /// `order` is `Iggy\PageOrder::Id` when null, and `descending` reverses it. `limit` is 1 to + /// 1000, 100 when null. `cursor` is the `next` of the previous page, null for the first + /// page. `name` keeps the streams whose name holds the text, case-sensitive, and is 1 to + /// 255 bytes. A query outside these ranges, or a cursor text that the client cannot read, + /// throws `Invalid command` (code 3) before anything is sent. The server refuses a cursor + /// that does not fit the query with the same error, which HTTP reports as code 300. A + /// `limit` that is not an integer, or that does not fit an unsigned 32-bit integer, throws + /// `IggyException` with code 0 from the argument check. + #[php(defaults(descending = false))] + pub fn get_streams_page( + &self, + order: Option<PageOrder>, + descending: bool, + limit: Option<&Zval>, + cursor: Option<String>, + name: Option<String>, + ) -> PhpResult<StreamsPage> { + let query = named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + runtime().block_on(async move { + inner + .get_streams_page(&query) + .await + .map(StreamsPage::from) + .map_err(to_php_exception) + }) + } + + /// Reads one page of the topics of a stream. A missing stream gives an empty page without + /// `next`. The other arguments are those of getStreamsPage(). + #[php(defaults(descending = false))] + pub fn get_topics_page( + &self, + stream_id: PhpIdentifier, + order: Option<PageOrder>, + descending: bool, + limit: Option<&Zval>, + cursor: Option<String>, + name: Option<String>, + ) -> PhpResult<TopicsPage> { + let stream_id: Identifier = stream_id.try_into()?; + let query = named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + runtime().block_on(async move { + inner + .get_topics_page(&stream_id, &query) + .await + .map(TopicsPage::from) + .map_err(to_php_exception) + }) + } + + /// Reads one page of the partitions of a topic. Partition ids follow creation, so both + /// orders walk by id. The other arguments are those of getStreamsPage() except `name`, + /// because a partition has no name. + #[php(defaults(descending = false))] + pub fn get_partitions_page( + &self, + stream_id: PhpIdentifier, + topic_id: PhpIdentifier, + order: Option<PageOrder>, + descending: bool, + limit: Option<&Zval>, + cursor: Option<String>, + ) -> PhpResult<PartitionsPage> { + let stream_id: Identifier = stream_id.try_into()?; + let topic_id: Identifier = topic_id.try_into()?; + let query = page_query(order, descending, limit, cursor)?; + let inner = self.inner.clone(); + + runtime().block_on(async move { + inner + .get_partitions_page(&stream_id, &topic_id, &query) + .await + .map(PartitionsPage::from) + .map_err(to_php_exception) + }) + } + + /// Reads one page of the consumer groups of a topic. Group ids follow creation, so both + /// orders walk by id. The other arguments are those of getStreamsPage(). + #[allow(clippy::too_many_arguments)] + #[php(defaults(descending = false))] + pub fn get_consumer_groups_page( + &self, + stream_id: PhpIdentifier, + topic_id: PhpIdentifier, + order: Option<PageOrder>, + descending: bool, + limit: Option<&Zval>, + cursor: Option<String>, + name: Option<String>, + ) -> PhpResult<ConsumerGroupsPage> { + let stream_id: Identifier = stream_id.try_into()?; + let topic_id: Identifier = topic_id.try_into()?; + let query = named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + runtime().block_on(async move { + inner + .get_consumer_groups_page(&stream_id, &topic_id, &query) + .await + .map(ConsumerGroupsPage::from) + .map_err(to_php_exception) + }) + } + + /// Reads one page of the users, and `name` matches the username. The other arguments are + /// those of getStreamsPage(). + #[php(defaults(descending = false))] + pub fn get_users_page( + &self, + order: Option<PageOrder>, + descending: bool, + limit: Option<&Zval>, + cursor: Option<String>, + name: Option<String>, + ) -> PhpResult<UsersPage> { + let query = named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + runtime().block_on(async move { + inner + .get_users_page(&query) + .await + .map(UsersPage::from) + .map_err(to_php_exception) + }) + } + /// Sends messages to a topic and returns the commit confirmations, one per /// partition the batch landed in. pub fn send_messages(
diff --git a/foreign/php/src/consumer_group.rs b/foreign/php/src/consumer_group.rs new file mode 100644 index 0000000..9f68777 --- /dev/null +++ b/foreign/php/src/consumer_group.rs
@@ -0,0 +1,61 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::sync::Arc; + +use ext_php_rs::{php_class, php_impl}; +use iggy::prelude::ConsumerGroup as RustConsumerGroup; + +/// One consumer group of a `ConsumerGroupsPage`. +#[php_class] +#[php(name = "Iggy\\ConsumerGroup")] +#[derive(Clone)] +pub struct ConsumerGroup { + // The Rust type is not Clone, and each read of the page's items copies the group. + inner: Arc<RustConsumerGroup>, +} + +impl From<RustConsumerGroup> for ConsumerGroup { + fn from(group: RustConsumerGroup) -> Self { + Self { + inner: Arc::new(group), + } + } +} + +#[php_impl] +impl ConsumerGroup { + #[php(getter)] + pub fn id(&self) -> u32 { + self.inner.id + } + + #[php(getter)] + pub fn name(&self) -> String { + self.inner.name.clone() + } + + #[php(getter, change_case = "snake_case")] + pub fn partitions_count(&self) -> u32 { + self.inner.partitions_count + } + + #[php(getter, change_case = "snake_case")] + pub fn members_count(&self) -> u32 { + self.inner.members_count + } +}
diff --git a/foreign/php/src/error.rs b/foreign/php/src/error.rs index 39e0336..862945a 100644 --- a/foreign/php/src/error.rs +++ b/foreign/php/src/error.rs
@@ -437,6 +437,17 @@ } #[test] + fn given_reply_too_large_when_classifying_should_keep_its_code_and_not_be_transient() { + let error = IggyError::ReplyTooLarge; + assert_eq!(error.as_code(), 97); + assert_eq!(error.as_string(), "reply_too_large"); + assert!(matches!( + PhpExceptionKind::from(&error), + PhpExceptionKind::Base + )); + } + + #[test] fn given_a_lost_range_when_mapping_read_error_should_expose_its_first_and_last_offset() { const PARTITION_ID: u32 = 7; const OPERATION_ID: u64 = 42;
diff --git a/foreign/php/src/lib.rs b/foreign/php/src/lib.rs index ff22eaf..e91bad6 100644 --- a/foreign/php/src/lib.rs +++ b/foreign/php/src/lib.rs
@@ -17,12 +17,14 @@ pub mod client; pub mod consumer; +pub mod consumer_group; pub mod durability; pub mod error; pub mod identifier; pub mod message_iterator; pub mod metadata_changes; pub mod options; +pub mod page; pub mod pending_poll; pub mod poll_options; pub mod reader; @@ -32,11 +34,13 @@ pub mod sensitive_parameters; pub mod stream; pub mod topic; +pub mod user; use ext_php_rs::prelude::*; use crate::client::{IggyClient, PendingOperationsConfig}; use crate::consumer::{ConsumerOffsetInfo, IggyConsumer}; +use crate::consumer_group::ConsumerGroup; use crate::error::{ AuthenticationException, ConnectionException, IggyException, NotFoundException, PendingOperationException, ReadException, TransientException, @@ -55,13 +59,17 @@ MetadataUnknownItem, MetadataUserChange, MetadataUserIdentity, MetadataUserPermissionsUpdated, }; use crate::options::{OptionSpec, OptionsScope, StreamOptionKey, TopicOptionKey}; +use crate::page::{ + ConsumerGroupsPage, PageOrder, PartitionsPage, StreamsPage, TopicsPage, UsersPage, +}; use crate::pending_poll::PendingPoll; use crate::poll_options::{AutoCommit, CommitAfter, CommitEvery, CommitPolicy, PollOptions}; use crate::reader::PartitionReader; use crate::receive_message::{Checkpoint, PolledMessages, PollingStrategy, ReceiveMessage}; use crate::send_message::{SendMessage, SendMessagesConfirmation, SendMessagesResponse}; -use crate::stream::StreamDetails; -use crate::topic::{Partition, TopicDetails}; +use crate::stream::{Stream, StreamDetails}; +use crate::topic::{Partition, Topic, TopicDetails}; +use crate::user::UserInfo; #[php_module] pub fn get_module(module: ModuleBuilder) -> ModuleBuilder { @@ -71,6 +79,7 @@ .enumeration::<StreamOptionKey>() .enumeration::<TopicOptionKey>() .enumeration::<OptionsScope>() + .enumeration::<PageOrder>() .enumeration::<CommitAfter>() .class::<CommitPolicy>() .class::<AutoCommit>() @@ -110,6 +119,15 @@ .class::<StreamDetails>() .class::<TopicDetails>() .class::<Partition>() + .class::<Stream>() + .class::<Topic>() + .class::<ConsumerGroup>() + .class::<UserInfo>() + .class::<StreamsPage>() + .class::<TopicsPage>() + .class::<PartitionsPage>() + .class::<ConsumerGroupsPage>() + .class::<UsersPage>() .class::<OptionSpec>() .class::<MetadataChanges>() .class::<MetadataChangeRecord>()
diff --git a/foreign/php/src/page.rs b/foreign/php/src/page.rs new file mode 100644 index 0000000..8a61aaf --- /dev/null +++ b/foreign/php/src/page.rs
@@ -0,0 +1,181 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::str::FromStr; + +use ext_php_rs::{exception::PhpResult, php_class, php_enum, php_impl, types::Zval}; +use iggy::prelude::{ + ConsumerGroup as RustConsumerGroup, DEFAULT_PAGE_LIMIT, NamedPageQuery, Page, PageCursor, + PageOrder as RustPageOrder, PageQuery, Partition as RustPartition, Stream as RustStream, + Topic as RustTopic, UserInfo as RustUserInfo, +}; + +use crate::client::optional_unsigned; +use crate::consumer_group::ConsumerGroup; +use crate::error::to_php_exception; +use crate::stream::Stream; +use crate::topic::{Partition, Topic}; +use crate::user::UserInfo; + +/// The order of a list page. Values are the HTTP API names. +#[php_enum] +#[php(name = "Iggy\\PageOrder")] +#[derive(Clone, Copy)] +pub enum PageOrder { + #[php(value = "id")] + Id, + #[php(value = "created")] + Created, +} + +impl From<PageOrder> for RustPageOrder { + fn from(order: PageOrder) -> Self { + match order { + PageOrder::Id => Self::Id, + PageOrder::Created => Self::Created, + } + } +} + +/// The query that a page method sends. The Rust SDK checks a query only after its +/// authentication check, so the query is checked here, and a refused one throws +/// `Invalid command` (code 3) before anything is sent, also on a client that never connected. +pub(crate) fn page_query( + order: Option<PageOrder>, + descending: bool, + limit: Option<&Zval>, + cursor: Option<String>, +) -> PhpResult<PageQuery> { + let query = PageQuery { + order: order.map(Into::into).unwrap_or_default(), + descending, + limit: optional_unsigned(limit, "limit")?.unwrap_or(DEFAULT_PAGE_LIMIT), + cursor: cursor + .as_deref() + .map(PageCursor::from_str) + .transpose() + .map_err(to_php_exception)?, + }; + query.validate().map_err(to_php_exception)?; + Ok(query) +} + +/// [`page_query`] with the name filter of the lists of named entities. +pub(crate) fn named_page_query( + order: Option<PageOrder>, + descending: bool, + limit: Option<&Zval>, + cursor: Option<String>, + name: Option<String>, +) -> PhpResult<NamedPageQuery> { + let query = NamedPageQuery { + page: page_query(order, descending, limit, cursor)?, + name, + }; + query.validate().map_err(to_php_exception)?; + Ok(query) +} + +// A PHP class cannot be generic, so each item type gets its own page class. The doc texts +// start with a space, as a `///` line does, because the stub prints them as they are. +macro_rules! list_page { + ( + $page:ident, + $php_name:literal, + $item:ident, + $rust_item:ty, + $page_doc:literal, + $items_doc:literal $(,)? + ) => { + #[doc = $page_doc] + #[php_class] + #[php(name = $php_name)] + pub struct $page { + items: Vec<$item>, + next: Option<String>, + } + + #[php_impl] + impl $page { + #[doc = $items_doc] + /// + /// The items are rebuilt on each getter call, so cache the array in PHP if you read it + /// more than once. + #[php(getter)] + pub fn items(&self) -> Vec<$item> { + self.items.clone() + } + + /// The `cursor` of the next page of the same query, null on the last page. A page can be + /// empty and still have one. + #[php(getter)] + pub fn next(&self) -> Option<String> { + self.next.clone() + } + } + + impl From<Page<$rust_item>> for $page { + fn from(page: Page<$rust_item>) -> Self { + Self { + items: page.items.into_iter().map($item::from).collect(), + next: page.next.map(|cursor| cursor.to_string()), + } + } + } + }; +} + +list_page!( + StreamsPage, + "Iggy\\StreamsPage", + Stream, + RustStream, + " One page of the streams, as `Client::getStreamsPage()` returns it.", + " The streams of the page, each an `Iggy\\Stream`.", +); +list_page!( + TopicsPage, + "Iggy\\TopicsPage", + Topic, + RustTopic, + " One page of the topics of a stream, as `Client::getTopicsPage()` returns it.", + " The topics of the page, each an `Iggy\\Topic`.", +); +list_page!( + PartitionsPage, + "Iggy\\PartitionsPage", + Partition, + RustPartition, + " One page of the partitions of a topic, as `Client::getPartitionsPage()` returns it.", + " The partitions of the page, each an `Iggy\\Partition`.", +); +list_page!( + ConsumerGroupsPage, + "Iggy\\ConsumerGroupsPage", + ConsumerGroup, + RustConsumerGroup, + " One page of the consumer groups of a topic, as `Client::getConsumerGroupsPage()` returns it.", + " The consumer groups of the page, each an `Iggy\\ConsumerGroup`.", +); +list_page!( + UsersPage, + "Iggy\\UsersPage", + UserInfo, + RustUserInfo, + " One page of the users, as `Client::getUsersPage()` returns it.", + " The users of the page, each an `Iggy\\UserInfo`.", +);
diff --git a/foreign/php/src/stream.rs b/foreign/php/src/stream.rs index eab1f23..7c1075f 100644 --- a/foreign/php/src/stream.rs +++ b/foreign/php/src/stream.rs
@@ -15,8 +15,12 @@ // specific language governing permissions and limitations // under the License. +use std::sync::Arc; + use ext_php_rs::{boxed::ZBox, exception::PhpResult, php_class, php_impl, types::ZendHashTable}; -use iggy::prelude::{HeaderKey, OptionKey, StreamDetails as RustStreamDetails}; +use iggy::prelude::{ + HeaderKey, OptionKey, ResourceOptions, Stream as RustStream, StreamDetails as RustStreamDetails, +}; use crate::options::options_array; @@ -73,10 +77,7 @@ /// stream. A source a newer server reports is returned as its text. #[php(getter, change_case = "snake_case")] pub fn encryption_key_source(&self) -> Option<String> { - self.inner - .options - .get(&HeaderKey::from(OptionKey::EncryptionKeySource)) - .and_then(|option| option.value.as_str().ok().map(str::to_owned)) + key_source_text(&self.inner.options) } /// Fingerprint of the stream's key, 16 lowercase hex characters. Compare it with @@ -90,7 +91,103 @@ /// outside a server key rotation. Null for a plaintext stream. #[php(getter, change_case = "snake_case")] pub fn encryption_kek_fingerprint(&self) -> Option<String> { - let fingerprints = self.inner.encryption_kek_fingerprints(); - (!fingerprints.is_empty()).then(|| fingerprints.join(",")) + comma_separated(&self.inner.encryption_kek_fingerprints()) } } + +/// One stream of a `StreamsPage`. +#[php_class] +#[php(name = "Iggy\\Stream")] +#[derive(Clone)] +pub struct Stream { + // The Rust type is not Clone, and each read of the page's items copies the stream. + inner: Arc<RustStream>, +} + +impl From<RustStream> for Stream { + fn from(stream: RustStream) -> Self { + Self { + inner: Arc::new(stream), + } + } +} + +#[php_impl] +impl Stream { + #[php(getter)] + pub fn id(&self) -> u32 { + self.inner.id + } + + /// Creation time in microseconds. + #[php(getter, change_case = "snake_case")] + pub fn created_at(&self) -> u64 { + self.inner.created_at.as_micros() + } + + #[php(getter)] + pub fn name(&self) -> String { + self.inner.name.clone() + } + + #[php(getter, change_case = "snake_case")] + pub fn size_bytes(&self) -> u64 { + self.inner.size.as_bytes_u64() + } + + #[php(getter, change_case = "snake_case")] + pub fn messages_count(&self) -> u64 { + self.inner.messages_count + } + + #[php(getter, change_case = "snake_case")] + pub fn topics_count(&self) -> u32 { + self.inner.topics_count + } + + /// Options the creating client set, as option name to scalar value. Key material is + /// never returned. + #[php(getter)] + pub fn options(&self) -> PhpResult<ZBox<ZendHashTable>> { + options_array(&self.inner.options, true) + } + + /// Options the server filled in, including the read-only encryption projections. + #[php(getter, change_case = "snake_case")] + pub fn derived_options(&self) -> PhpResult<ZBox<ZendHashTable>> { + options_array(&self.inner.options, false) + } + + /// Who chose the stream's at-rest key: `stream`, `server`, or `none` for a plaintext + /// stream. A source a newer server reports is returned as its text. + #[php(getter, change_case = "snake_case")] + pub fn encryption_key_source(&self) -> Option<String> { + key_source_text(&self.inner.options) + } + + /// Fingerprint of the stream's key, 16 lowercase hex characters. Compare it with + /// `Client::encryptionKeyFingerprint()` of a key you hold. Null for a plaintext stream. + #[php(getter, change_case = "snake_case")] + pub fn encryption_key_fingerprint(&self) -> Option<String> { + self.inner.encryption_key_fingerprint() + } + + /// Fingerprints of the server keys that wrap the stream's key, comma-separated: one + /// outside a server key rotation. Null for a plaintext stream. + #[php(getter, change_case = "snake_case")] + pub fn encryption_kek_fingerprint(&self) -> Option<String> { + comma_separated(&self.inner.encryption_kek_fingerprints()) + } +} + +// The SDK's encryption_key_source() parses the text and drops a source that this build does +// not know, so the getters read the text. +fn key_source_text(options: &ResourceOptions) -> Option<String> { + options + .get(&HeaderKey::from(OptionKey::EncryptionKeySource)) + .and_then(|option| option.value.as_str().ok().map(str::to_owned)) +} + +fn comma_separated(fingerprints: &[String]) -> Option<String> { + (!fingerprints.is_empty()).then(|| fingerprints.join(",")) +}
diff --git a/foreign/php/src/topic.rs b/foreign/php/src/topic.rs index 3d1e951..c89249c 100644 --- a/foreign/php/src/topic.rs +++ b/foreign/php/src/topic.rs
@@ -15,8 +15,12 @@ // specific language governing permissions and limitations // under the License. +use std::sync::Arc; + use ext_php_rs::{boxed::ZBox, exception::PhpResult, php_class, php_impl, types::ZendHashTable}; -use iggy::prelude::{Partition as RustPartition, TopicDetails as RustTopicDetails}; +use iggy::prelude::{ + Partition as RustPartition, Topic as RustTopic, TopicDetails as RustTopicDetails, +}; use crate::options::options_array; @@ -83,9 +87,75 @@ } } +/// One topic of a `TopicsPage`. +#[php_class] +#[php(name = "Iggy\\Topic")] +#[derive(Clone)] +pub struct Topic { + // The Rust type is not Clone, and each read of the page's items copies the topic. + inner: Arc<RustTopic>, +} + +impl From<RustTopic> for Topic { + fn from(topic: RustTopic) -> Self { + Self { + inner: Arc::new(topic), + } + } +} + +#[php_impl] +impl Topic { + #[php(getter)] + pub fn id(&self) -> u32 { + self.inner.id + } + + /// Creation time in microseconds. + #[php(getter, change_case = "snake_case")] + pub fn created_at(&self) -> u64 { + self.inner.created_at.as_micros() + } + + #[php(getter)] + pub fn name(&self) -> String { + self.inner.name.clone() + } + + #[php(getter, change_case = "snake_case")] + pub fn size_bytes(&self) -> u64 { + self.inner.size.as_bytes_u64() + } + + #[php(getter, change_case = "snake_case")] + pub fn messages_count(&self) -> u64 { + self.inner.messages_count + } + + #[php(getter, change_case = "snake_case")] + pub fn partitions_count(&self) -> u32 { + self.inner.partitions_count + } + + /// Options the creating or updating client set, as option name to scalar value. + /// Integers above `PHP_INT_MAX`, such as never-expire and unlimited + /// (18446744073709551615), are decimal strings. + #[php(getter)] + pub fn options(&self) -> PhpResult<ZBox<ZendHashTable>> { + options_array(&self.inner.options, true) + } + + /// Options the server filled in from its catalog defaults. + #[php(getter, change_case = "snake_case")] + pub fn derived_options(&self) -> PhpResult<ZBox<ZendHashTable>> { + options_array(&self.inner.options, false) + } +} + /// One partition of a topic. #[php_class] #[php(name = "Iggy\\Partition")] +#[derive(Clone)] pub struct Partition { pub(crate) inner: RustPartition, }
diff --git a/foreign/php/src/user.rs b/foreign/php/src/user.rs new file mode 100644 index 0000000..cb5a6db --- /dev/null +++ b/foreign/php/src/user.rs
@@ -0,0 +1,77 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::sync::Arc; + +use ext_php_rs::{boxed::ZBox, exception::PhpResult, php_class, php_impl, types::ZendHashTable}; +use iggy::prelude::UserInfo as RustUserInfo; + +use crate::options::options_array; + +/// One user of a `UsersPage`. +#[php_class] +#[php(name = "Iggy\\UserInfo")] +#[derive(Clone)] +pub struct UserInfo { + // The Rust type is not Clone, and each read of the page's items copies the user. + inner: Arc<RustUserInfo>, +} + +impl From<RustUserInfo> for UserInfo { + fn from(user: RustUserInfo) -> Self { + Self { + inner: Arc::new(user), + } + } +} + +#[php_impl] +impl UserInfo { + #[php(getter)] + pub fn id(&self) -> u32 { + self.inner.id + } + + /// Creation time in microseconds. + #[php(getter, change_case = "snake_case")] + pub fn created_at(&self) -> u64 { + self.inner.created_at.as_micros() + } + + /// `active` or `inactive`. + #[php(getter)] + pub fn status(&self) -> String { + self.inner.status.to_string() + } + + #[php(getter)] + pub fn username(&self) -> String { + self.inner.username.clone() + } + + /// Options the creating client set, as option name to scalar value. + #[php(getter)] + pub fn options(&self) -> PhpResult<ZBox<ZendHashTable>> { + options_array(&self.inner.options, true) + } + + /// Options the server filled in. + #[php(getter, change_case = "snake_case")] + pub fn derived_options(&self) -> PhpResult<ZBox<ZendHashTable>> { + options_array(&self.inner.options, false) + } +}
diff --git a/foreign/php/tests/ListPagesTest.php b/foreign/php/tests/ListPagesTest.php new file mode 100644 index 0000000..ea23a03 --- /dev/null +++ b/foreign/php/tests/ListPagesTest.php
@@ -0,0 +1,428 @@ +<?php +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +declare(strict_types=1); + +use Iggy\Client as IggyClient; +use Iggy\ConsumerGroup; +use Iggy\ConsumerGroupsPage; +use Iggy\Exception\IggyException; +use Iggy\PageOrder; +use Iggy\Partition; +use Iggy\PartitionsPage; +use Iggy\Stream; +use Iggy\StreamsPage; +use Iggy\Topic; +use Iggy\TopicsPage; +use Iggy\UserInfo; +use Iggy\UsersPage; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestDox; +use PHPUnit\Framework\TestCase; + +final class ListPagesTest extends TestCase +{ + private const UNREACHABLE_ADDRESS = '127.0.0.1:1'; + private const PAGE_LIMIT = 2; + // Ends a walk whose cursors never run out, which would otherwise hang the suite. + private const MAX_WALK_PAGES = 100; + private const STREAM_COUNT = 3; + private const PARTITION_COUNT = 3; + private const ROOT_USER_ID = 0; + private const TOPIC = 'pages-topic'; + private const QUERY_KEYS = ['order', 'descending', 'limit', 'cursor', 'name']; + // The argument check refuses these before the page rules run. + private const LIMITS_THE_ARGUMENT_CHECK_REFUSES = [-1, 4294967296, '5']; + private const ARGUMENT_ERROR_CODE = 0; + + private array $createdStreams = []; + + public static function transports(): array + { + return [ + 'tcp' => ['tcp'], + 'quic' => ['quic'], + 'http' => ['http'], + 'websocket' => ['websocket'], + ]; + } + + /** Over HTTP, the Rust SDK reports a server refusal as an HTTP error (300), not as its own code. */ + public static function binaryTransports(): array + { + return array_diff_key(self::transports(), ['http' => true]); + } + + protected function tearDown(): void + { + if ($this->createdStreams !== []) { + $client = new_client(); + foreach ($this->createdStreams as $stream) { + cleanup_stream($client, $stream); + } + } + + parent::tearDown(); + } + + #[DataProvider('transports')] + #[TestDox('Three streams come back in pages of two in id ascending, id descending and created order on $transport')] + public function testGivenThreeStreamsWhenWalkingPagesOfTwoShouldReturnThemInEachOrder(string $transport): void + { + $client = new_transport_client($transport); + $prefix = unique_name('pages-streams'); + $created = []; + foreach (range(1, self::STREAM_COUNT) as $index) { + $created[] = $this->createStream($client, "{$prefix}-{$index}"); + } + // Ids of deleted streams are reused, so the created order can differ from the id order. + $ascending = $created; + sort($ascending); + + foreach ([ + 'id ascending' => [PageOrder::Id, false, $ascending], + 'id descending' => [PageOrder::Id, true, array_reverse($ascending)], + 'created' => [PageOrder::Created, false, $created], + ] as $case => [$order, $descending, $expected]) { + $streams = self::walk(static fn (?string $cursor): StreamsPage => $client->getStreamsPage( + order: $order, + descending: $descending, + limit: self::PAGE_LIMIT, + cursor: $cursor, + name: $prefix, + )); + + assert_same($expected, self::ids($streams), $case); + foreach ($streams as $stream) { + assert_instance_of(Stream::class, $stream, $case); + $details = $client->getStream($stream->id); + assert_not_null($details, $case); + assert_same( + [ + $details->name, + $details->messages_count, + $details->topics_count, + $details->options, + $details->derived_options, + $details->encryption_key_source, + $details->encryption_key_fingerprint, + $details->encryption_kek_fingerprint, + ], + [ + $stream->name, + $stream->messages_count, + $stream->topics_count, + $stream->options, + $stream->derived_options, + $stream->encryption_key_source, + $stream->encryption_key_fingerprint, + $stream->encryption_kek_fingerprint, + ], + $case, + ); + assert_same(0, $stream->size_bytes, $case); + self::assertGreaterThan(0, $stream->created_at, $case); + } + } + } + + #[DataProvider('transports')] + #[TestDox('The partitions of a topic come back in pages of two on $transport')] + public function testGivenTopicWithThreePartitionsWhenWalkingPagesOfTwoShouldReturnEveryPartition(string $transport): void + { + $client = new_transport_client($transport); + $streamId = $this->createStream($client, unique_name('pages-partitions')); + $client->createTopic($streamId, self::TOPIC, self::PARTITION_COUNT, null, null, null, null); + + $partitions = self::walk(static fn (?string $cursor): PartitionsPage => $client->getPartitionsPage( + $streamId, + self::TOPIC, + limit: self::PAGE_LIMIT, + cursor: $cursor, + )); + + assert_count(self::PARTITION_COUNT, $partitions); + foreach ($partitions as $partition) { + assert_instance_of(Partition::class, $partition); + } + $topic = $client->getTopic($streamId, self::TOPIC); + assert_not_null($topic); + assert_same(self::ids($topic->partitions), self::ids($partitions)); + } + + #[DataProvider('transports')] + #[TestDox('A name filter keeps only the matching topic on $transport')] + public function testGivenTwoTopicsWhenFilteringByNameShouldReturnOnlyTheMatchingTopic(string $transport): void + { + $client = new_transport_client($transport); + $streamId = $this->createStream($client, unique_name('pages-topics')); + $matching = 'payments'; + $client->createTopic($streamId, 'orders', 1, null, null, null, null); + $client->createTopic($streamId, $matching, 2, null, null, null, null); + + $topics = self::walk(static fn (?string $cursor): TopicsPage => $client->getTopicsPage( + $streamId, + limit: self::PAGE_LIMIT, + cursor: $cursor, + name: 'pay', + )); + + assert_count(1, $topics); + [$topic] = $topics; + assert_instance_of(Topic::class, $topic); + $details = $client->getTopic($streamId, $matching); + assert_not_null($details); + assert_same( + [$details->id, $details->name, $details->messages_count, $details->partitions_count, $details->options, $details->derived_options], + [$topic->id, $topic->name, $topic->messages_count, $topic->partitions_count, $topic->options, $topic->derived_options], + ); + assert_same(0, $topic->size_bytes); + self::assertGreaterThan(0, $topic->created_at); + } + + #[DataProvider('transports')] + #[TestDox('A name filter finds a consumer group by its name on $transport')] + public function testGivenConsumerGroupWhenFilteringByItsNameShouldReturnIt(string $transport): void + { + $client = new_transport_client($transport); + $streamName = unique_name('pages-groups'); + $streamId = $this->createStream($client, $streamName); + $client->createTopic($streamId, self::TOPIC, 1, null, null, null, null); + $groupName = unique_name('pages-group'); + // The client has no call that only creates a group: a consumer creates it and leaves. + new_client()->consumerGroup($groupName, $streamName, self::TOPIC)->shutdown(); + + $groups = self::walk(static fn (?string $cursor): ConsumerGroupsPage => $client->getConsumerGroupsPage( + $streamId, + self::TOPIC, + limit: self::PAGE_LIMIT, + cursor: $cursor, + name: $groupName, + )); + + assert_count(1, $groups); + [$group] = $groups; + assert_instance_of(ConsumerGroup::class, $group); + assert_same([$groupName, 1], [$group->name, $group->partitions_count]); + } + + #[DataProvider('transports')] + #[TestDox('A name filter finds the root user on $transport')] + public function testGivenRootNameWhenFilteringUsersShouldReturnTheRootUser(string $transport): void + { + $client = new_transport_client($transport); + $rootName = env_or_default('IGGY_ROOT_USERNAME', 'iggy'); + + $users = self::walk(static fn (?string $cursor): UsersPage => $client->getUsersPage( + limit: self::PAGE_LIMIT, + cursor: $cursor, + name: $rootName, + )); + + $roots = []; + foreach ($users as $user) { + assert_instance_of(UserInfo::class, $user); + assert_true(str_contains($user->username, $rootName), "{$user->username} holds {$rootName}"); + if ($user->username === $rootName) { + $roots[] = $user; + } + } + assert_count(1, $roots); + assert_same([self::ROOT_USER_ID, 'active'], [$roots[0]->id, $roots[0]->status]); + } + + #[DataProvider('binaryTransports')] + #[TestDox('The server refuses an id cursor in created order, and the session goes on, on $transport')] + public function testGivenACursorTheServerCannotServeWhenReadingShouldThrowInvalidCommandAndKeepTheSession(string $transport): void + { + $client = new_transport_client($transport); + $streamName = unique_name('pages-refused'); + $streamId = $this->createStream($client, $streamName); + $idCursor = array_column(self::fixture()['cursors'], 'text', 'case')['id_seven']; + + $error = assert_throws( + static fn (): StreamsPage => $client->getStreamsPage(order: PageOrder::Created, cursor: $idCursor), + 'Invalid command', + ); + assert_same(self::invalidCommand(), $error->getCode()); + + $streams = self::walk(static fn (?string $cursor): StreamsPage => $client->getStreamsPage( + limit: self::PAGE_LIMIT, + cursor: $cursor, + name: $streamName, + )); + assert_same([$streamId], self::ids($streams)); + } + + #[TestDox('Refused cursor texts, opaque cursors and refused queries throw invalid command before any network I/O')] + public function testGivenRefusedInputsWhenReadingPagesShouldThrowInvalidCommandBeforeNetworkIo(): void + { + $client = new IggyClient(self::UNREACHABLE_ADDRESS); + $fixture = self::fixture(); + $refused = []; + foreach ($fixture['refused']['cursors'] as $vector) { + $refused["refused cursor {$vector['case']}"] = ['cursor' => $vector['text']]; + } + foreach ($fixture['opaque_cursors'] as $vector) { + $refused["opaque cursor {$vector['case']}"] = ['cursor' => $vector['text']]; + } + foreach ($fixture['refused']['queries'] as $vector) { + $refused["refused query {$vector['case']}"] = array_intersect_key($vector['input'], array_flip(self::QUERY_KEYS)); + } + + // Each request vector carries one command with its parent ids, numeric or named. + foreach ($fixture['requests'] as $request) { + foreach ($refused as $case => $override) { + if ($request['command'] === 'get_partitions' && ($override['name'] ?? null) !== null) { + continue; // getPartitionsPage() has no `name` argument. + } + $label = "{$request['command']} of {$request['case']} with {$case}"; + $error = assert_throws( + static fn () => self::readPage($client, $request['command'], [...$request['input'], ...$override]), + 'Invalid command', + ); + assert_instance_of(IggyException::class, $error, $label); + assert_same(self::invalidCommand(), $error->getCode(), $label); + } + } + } + + #[TestDox('A limit that is not an integer or does not fit 32 bits fails the argument check with code 0')] + public function testGivenALimitTheArgumentCheckRefusesWhenReadingPagesShouldThrowCodeZero(): void + { + $client = new IggyClient(self::UNREACHABLE_ADDRESS); + foreach (self::fixture()['requests'] as $request) { + foreach (self::LIMITS_THE_ARGUMENT_CHECK_REFUSES as $limit) { + $label = "{$request['command']} of {$request['case']} with limit " . var_export($limit, true); + $error = assert_throws( + static fn () => self::readPage($client, $request['command'], [...$request['input'], 'limit' => $limit]), + "'limit' must be", + ); + assert_instance_of(IggyException::class, $error, $label); + assert_same(self::ARGUMENT_ERROR_CODE, $error->getCode(), $label); + } + } + } + + #[TestDox('Request vectors and valid cursors pass validation and fail only on the transport')] + public function testGivenRequestVectorsAndValidCursorsWhenReadingPagesShouldPassValidation(): void + { + $client = new IggyClient(self::UNREACHABLE_ADDRESS); + $fixture = self::fixture(); + foreach ($fixture['requests'] as $request) { + $inputs = [$request['case'] => $request['input']]; + foreach ($fixture['cursors'] as $vector) { + $inputs["{$request['case']} with cursor {$vector['case']}"] = [...$request['input'], 'cursor' => $vector['text']]; + } + foreach ($inputs as $case => $input) { + $error = assert_throws(static fn () => self::readPage($client, $request['command'], $input)); + assert_true($error->getCode() !== self::invalidCommand(), "{$request['command']} of {$case}"); + } + } + } + + #[TestDox('PageOrder has one case per order name of the fixture')] + public function testGivenFixtureOrdersWhenReadingPageOrderShouldCoverEveryName(): void + { + $values = array_map(static fn (PageOrder $order): string => $order->value, PageOrder::cases()); + sort($values); + $expected = array_keys(self::fixture()['constants']['orders']); + sort($expected); + assert_same($expected, $values); + } + + private function createStream(IggyClient $client, string $name): int + { + $client->createStream($name); + $stream = $client->getStream($name); + assert_not_null($stream); + $this->createdStreams[] = $stream->id; + + return $stream->id; + } + + /** Reads pages until one has no next, and returns their items in reply order. */ + private static function walk(callable $read): array + { + $prefix = self::fixture()['constants']['cursor_prefix']; + $items = []; + $cursor = null; + for ($pages = 0; $pages < self::MAX_WALK_PAGES; $pages++) { + $page = $read($cursor); + $pageItems = $page->items; + self::assertLessThanOrEqual(self::PAGE_LIMIT, count($pageItems)); + array_push($items, ...$pageItems); + $cursor = $page->next; + if ($cursor === null) { + return $items; + } + self::assertStringStartsWith($prefix, $cursor); + } + + self::fail('the walk did not end within ' . self::MAX_WALK_PAGES . ' pages'); + } + + private static function ids(array $items): array + { + return array_map(static fn (object $item): int => $item->id, $items); + } + + /** Calls the page method of a fixture command with the fixture input as named arguments. */ + private static function readPage(IggyClient $client, string $command, array $input): object + { + $query = array_intersect_key($input, array_flip(self::QUERY_KEYS)); + $query['order'] = PageOrder::from($query['order']); + // getPartitionsPage() takes no `name`, so only a null one is dropped and a set one fails. + if ($command === 'get_partitions' && ($query['name'] ?? null) === null) { + unset($query['name']); + } + + return match ($command) { + 'get_streams' => $client->getStreamsPage(...$query), + 'get_topics' => $client->getTopicsPage($input['stream_id']['value'], ...$query), + 'get_partitions' => $client->getPartitionsPage( + $input['stream_id']['value'], + $input['topic_id']['value'], + ...$query, + ), + 'get_consumer_groups' => $client->getConsumerGroupsPage( + $input['stream_id']['value'], + $input['topic_id']['value'], + ...$query, + ), + 'get_users' => $client->getUsersPage(...$query), + }; + } + + private static function invalidCommand(): int + { + return self::fixture()['constants']['errors']['invalid_command']; + } + + private static function fixture(): array + { + static $fixture = null; + + return $fixture ??= json_decode( + (string) file_get_contents(__DIR__ . '/fixtures/list_pages.json'), + true, + 512, + JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING, + ); + } +}
diff --git a/foreign/php/tests/bootstrap.php b/foreign/php/tests/bootstrap.php index 57ae9f2..3077284 100644 --- a/foreign/php/tests/bootstrap.php +++ b/foreign/php/tests/bootstrap.php
@@ -228,26 +228,18 @@ $client->sendBinaryRequest(34, chr(2) . chr(strlen($username)) . $username); } -/** - * Stream id to name, from the raw GetStreams answer (201): per stream its id, created_at, - * topics_count, size, messages_count, name and the two length-prefixed option blocks. - */ +/** Stream id to name, read page by page in id order. */ function stream_list(IggyClient $client): array { - $payload = $client->sendBinaryRequest(201, ''); $streams = []; - $position = 0; - while ($position < strlen($payload)) { - $id = unpack('V', $payload, $position)[1]; - $position += 4 + 8 + 4 + 8 + 8; - $nameLength = ord($payload[$position]); - $streams[$id] = substr($payload, $position + 1, $nameLength); - $position += 1 + $nameLength; - for ($block = 0; $block < 2; $block++) { - $position += 4 + unpack('V', $payload, $position)[1]; + $cursor = null; + do { + $page = $client->getStreamsPage(cursor: $cursor); + foreach ($page->items as $stream) { + $streams[$stream->id] = $stream->name; } - } - ksort($streams); + $cursor = $page->next; + } while ($cursor !== null); return $streams; }
diff --git a/foreign/php/tests/fixtures/list_pages.json b/foreign/php/tests/fixtures/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/php/tests/fixtures/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/php/tests/fixtures/resource_options.json b/foreign/php/tests/fixtures/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/php/tests/fixtures/resource_options.json +++ b/foreign/php/tests/fixtures/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/python/Cargo.toml b/foreign/python/Cargo.toml index 96f2090..3a97891 100644 --- a/foreign/python/Cargo.toml +++ b/foreign/python/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "apache-iggy" -version = "0.10.0" +version = "0.10.1-dev1" edition = "2024" authors = ["Iggy Committers <dev@iggy.apache.org>"] license = "Apache-2.0" @@ -37,7 +37,7 @@ [dependencies] bytes = "1.12.1" futures = "0.3.34" -iggy = { path = "../../core/sdk", version = "0.12.0" } +iggy = { path = "../../core/sdk", version = "0.12.1-edge.1" } paste = "1" pyo3 = { version = "0.30.1", features = ["experimental-async"] } pyo3-async-runtimes = { version = "0.30.0", features = [
diff --git a/foreign/python/README.md b/foreign/python/README.md index e71a08d..8ddc6f8 100644 --- a/foreign/python/README.md +++ b/foreign/python/README.md
@@ -267,6 +267,43 @@ The server never returns the key, only `encryption_key_source`, `encryption_key_fingerprint` and `encryption_kek_fingerprints`. Without a key, a server with encryption enabled generates one for the stream and reports the source `"server"`. An invalid key raises `ValueError` before anything is sent, and no repr or error message contains it. +## List Pages + +`get_streams`, `get_topics`, `get_consumer_groups` and `get_users` return a whole list in id order. The list is read in pages of 1,000 items, so the result is not one consistent read. An entity that someone creates or deletes during the read can appear or not appear. + +`get_streams_page`, `get_topics_page`, `get_partitions_page`, `get_consumer_groups_page` and `get_users_page` return one page. To read the next page, call the method again with the same arguments and the `next` of the page as `cursor`. A page can be empty and still have a `next`. + +```python +import asyncio + +from apache_iggy import IggyClient, PageOrder + + +async def main(): + client = IggyClient.from_connection_string("iggy+tcp://iggy:iggy@127.0.0.1:8090") + await client.connect() + + cursor = None + while True: + page = await client.get_streams_page( + order=PageOrder.Created, name="orders", cursor=cursor + ) + for stream in page.items: + print(stream.id, stream.name) + if page.next is None: + break + cursor = page.next + + +asyncio.run(main()) +``` + +`order` selects `PageOrder.Id`, the default, or `PageOrder.Created`, and `descending=True` reverses it. `limit` sets the size of a page, from 1 to 1000, and is 100 by default. `name` keeps the entries whose name holds the text, case-sensitive. A partition has no name, so `get_partitions_page` takes no `name`. + +A cursor is the `pg1_` text that the HTTP API and the CLI use. Before it sends anything, the client refuses a cursor or a query that breaks the page rules. It raises `IggyError` with the invalid command code (3). Examples are a bad cursor text, a limit of 0 or above 1000, and a name that is empty or longer than 255 bytes. A `limit` outside the unsigned 32-bit range raises `OverflowError` instead. + +The server refuses a cursor that it cannot use, such as the cursor of another order, also with invalid command. Over HTTP, a refusal from the server raises `IggyError` with code 300 (HTTP response error), and its message holds the server error body. + ## Metadata Changes `get_metadata_changes` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `next` cursor. The call needs root or the global `manage_servers` permission. A query the server would refuse raises `IggyError` with the invalid command code before anything is sent.
diff --git a/foreign/python/apache_iggy.pyi b/foreign/python/apache_iggy.pyi index 3b3247f..7894bed 100644 --- a/foreign/python/apache_iggy.pyi +++ b/foreign/python/apache_iggy.pyi
@@ -41,6 +41,7 @@ "ConsumerGroup", "ConsumerGroupDetails", "ConsumerGroupMember", + "ConsumerGroupsPage", "ConsumerOffsetInfo", "DirectProducerConfig", "GlobalPermissions", @@ -94,11 +95,13 @@ "OptionError", "OptionKey", "OptionSpec", + "PageOrder", "Partition", "PartitionContext", "PartitionReader", "PartitionResizePolicy", "Partitioning", + "PartitionsPage", "PendingOperationError", "PendingOperationsConfig", "Permissions", @@ -120,6 +123,7 @@ "StreamDetails", "StreamOptions", "StreamPermissions", + "StreamsPage", "SystemSnapshotType", "TcpConfig", "TcpReconnectionConfig", @@ -128,11 +132,13 @@ "TopicDetails", "TopicOptions", "TopicPermissions", + "TopicsPage", "UserHeaders", "UserInfo", "UserInfoDetails", "UserOptions", "UserStatus", + "UsersPage", "WebSocketConfig", "WebSocketFramingConfig", "WebSocketReconnectionConfig", @@ -603,6 +609,23 @@ """ @typing.final +class ConsumerGroupsPage: + r""" + One page of a list, as `IggyClient.get_consumer_groups_page` returns it. + """ + @property + def items(self) -> builtins.list[ConsumerGroup]: + r""" + The items of the page, in the order of the query. + """ + @property + def next(self) -> builtins.str | None: + r""" + Pass it as `cursor`, with the same other arguments, to read the + next page. `None` on the last page. + """ + +@typing.final class ConsumerOffsetInfo: r""" The offset that a consumer stored on a partition. @@ -1376,7 +1399,11 @@ """ def get_users(self) -> collections.abc.Awaitable[list[UserInfo]]: r""" - Get the info about all the users. + Get the info about all the users, in id order. + + The list is read in pages of 1,000, so it is not one consistent read. + A user that someone creates or deletes during the read can appear or + not appear. `get_users_page` reads one page. Returns: An awaitable that resolves to `list[UserInfo]`. @@ -1384,6 +1411,29 @@ Raises: RuntimeError: If the request fails. """ + def get_users_page( + self, + *, + order: PageOrder | None = None, + descending: builtins.bool = False, + limit: builtins.int | None = None, + cursor: builtins.str | None = None, + name: builtins.str | None = None, + ) -> collections.abc.Awaitable[UsersPage]: + r""" + Reads one page of the users. `name` matches the username. + + Takes the keyword arguments of `get_streams_page`, with the same + cursor rules. + + Returns: + An awaitable that resolves to `UsersPage`. + + Raises: + OverflowError: If `limit` is outside the unsigned 32-bit range. + IggyError: As for `get_streams_page`. A user without the permission + to read the users gets the unauthorized code. + """ def create_user( self, username: builtins.str, @@ -1596,11 +1646,17 @@ r""" Gets stream by id. Returns the stream details, or `None` if the stream does not exist. - Raises `RuntimeError` on failure. + Raises `RuntimeError` on failure. Over TCP, QUIC and WebSocket, a reply + larger than the reply size limit raises `IggyError` with code 97 + (`ReplyTooLarge`). `get_topics_page` reads the topics in pages. """ def get_streams(self) -> collections.abc.Awaitable[list[Stream]]: r""" - Return all streams. + Return all streams, in id order. + + The list is read in pages of 1,000, so it is not one consistent read. + A stream that someone creates or deletes during the read can appear or + not appear. `get_streams_page` reads one page. Returns: A list of `Stream` summaries. @@ -1609,6 +1665,44 @@ RuntimeError: If the client is not authenticated, the user lacks global `read_streams` or `manage_streams` permission, or the request fails. """ + def get_streams_page( + self, + *, + order: PageOrder | None = None, + descending: builtins.bool = False, + limit: builtins.int | None = None, + cursor: builtins.str | None = None, + name: builtins.str | None = None, + ) -> collections.abc.Awaitable[StreamsPage]: + r""" + Reads one page of the streams. + + Pass the page's `next` as `cursor`, with the same other arguments, to + read the next page. The read ends at the first page whose `next` is + `None`. A page can be empty and still have a `next`. + + Args: + order: `PageOrder.Id`, the default, or `PageOrder.Created`. + descending: Read from the last item to the first. + limit: Items per page, 1 to 1000. Defaults to 100. + cursor: The `next` of the previous page, `None` for the first page. + name: Keep only the items whose name holds this text, case-sensitive. + 1 to 255 bytes. + + Returns: + An awaitable that resolves to `StreamsPage`. + + Raises: + OverflowError: If `limit` is outside the unsigned 32-bit range. + IggyError: If the request fails. A cursor or a query that breaks + the page rules raises it with the invalid command code before + anything is sent. The server refuses a cursor that it cannot + use, such as the cursor of another order, with the same code. + Over HTTP, a refusal from the server has code 300 (HTTP response + error), and its message holds the server error body. A user + without the permission to read the streams gets the + unauthorized code. + """ def update_stream( self, stream_id: builtins.str | builtins.int, @@ -1706,13 +1800,19 @@ r""" Gets topic by stream and id. Returns the topic details, or `None` if the topic does not exist. - Raises `RuntimeError` on failure. + Raises `RuntimeError` on failure. Over TCP, QUIC and WebSocket, a reply + larger than the reply size limit raises `IggyError` with code 97 + (`ReplyTooLarge`). `get_partitions_page` reads the partitions in pages. """ def get_topics( self, stream_id: builtins.str | builtins.int ) -> collections.abc.Awaitable[list[Topic]]: r""" - Get all topics in a stream. + Get all topics in a stream, in id order. + + The list is read in pages of 1,000, so it is not one consistent read. + A topic that someone creates or deletes during the read can appear or + not appear. `get_topics_page` reads one page. Args: stream_id: Stream identifier as `str | int`. @@ -1723,6 +1823,35 @@ Raises: RuntimeError: If the identifier is invalid or the request fails. """ + def get_topics_page( + self, + stream_id: builtins.str | builtins.int, + *, + order: PageOrder | None = None, + descending: builtins.bool = False, + limit: builtins.int | None = None, + cursor: builtins.str | None = None, + name: builtins.str | None = None, + ) -> collections.abc.Awaitable[TopicsPage]: + r""" + Reads one page of the topics of a stream. A missing stream gives an + empty page without `next`. + + Takes the keyword arguments of `get_streams_page`, with the same + cursor rules. + + Args: + stream_id: Stream identifier as `str | int`. + + Returns: + An awaitable that resolves to `TopicsPage`. + + Raises: + ValueError: If the identifier is invalid. + OverflowError: If `limit` is outside the unsigned 32-bit range. + IggyError: As for `get_streams_page`. A user without the permission + to read the topics gets the unauthorized code. + """ def update_topic( self, stream_id: builtins.str | builtins.int, @@ -1868,6 +1997,37 @@ `manage_topics`, or per-topic `manage_topic` permission, or the request fails. """ + def get_partitions_page( + self, + stream_id: builtins.str | builtins.int, + topic_id: builtins.str | builtins.int, + *, + order: PageOrder | None = None, + descending: builtins.bool = False, + limit: builtins.int | None = None, + cursor: builtins.str | None = None, + ) -> collections.abc.Awaitable[PartitionsPage]: + r""" + Reads one page of the partitions of a topic. + + Takes the keyword arguments of `get_streams_page` except `name`, + because a partition has no name. The cursor rules are the same. + Partition ids follow creation, so `PageOrder.Created` gives the id + order too. + + Args: + stream_id: Stream identifier as `str | int`. + topic_id: Topic identifier as `str | int`. + + Returns: + An awaitable that resolves to `PartitionsPage`. + + Raises: + ValueError: If an identifier is invalid. + OverflowError: If `limit` is outside the unsigned 32-bit range. + IggyError: As for `get_streams_page`. A user without the permission + to read the topic gets the unauthorized code. + """ def delete_segments( self, stream_id: builtins.str | builtins.int, @@ -1953,7 +2113,11 @@ topic_id: builtins.str | builtins.int, ) -> collections.abc.Awaitable[list[ConsumerGroup]]: r""" - Get all consumer groups for the specified stream and topic. + Get all consumer groups for the specified stream and topic, in id order. + + The list is read in pages of 1,000, so it is not one consistent read. + A group that someone creates or deletes during the read can appear or + not appear. `get_consumer_groups_page` reads one page. Args: stream_id: Stream identifier as `str | int`. @@ -1966,6 +2130,37 @@ ValueError: If an identifier is invalid. RuntimeError: If the request fails. """ + def get_consumer_groups_page( + self, + stream_id: builtins.str | builtins.int, + topic_id: builtins.str | builtins.int, + *, + order: PageOrder | None = None, + descending: builtins.bool = False, + limit: builtins.int | None = None, + cursor: builtins.str | None = None, + name: builtins.str | None = None, + ) -> collections.abc.Awaitable[ConsumerGroupsPage]: + r""" + Reads one page of the consumer groups of a topic. + + Takes the keyword arguments of `get_streams_page`, with the same + cursor rules. Group ids follow creation, so `PageOrder.Created` gives + the id order too. + + Args: + stream_id: Stream identifier as `str | int`. + topic_id: Topic identifier as `str | int`. + + Returns: + An awaitable that resolves to `ConsumerGroupsPage`. + + Raises: + ValueError: If an identifier is invalid. + OverflowError: If `limit` is outside the unsigned 32-bit range. + IggyError: As for `get_streams_page`. A user without the permission + to read the topic gets the unauthorized code. + """ def delete_consumer_group( self, stream_id: builtins.str | builtins.int, @@ -3860,6 +4055,16 @@ def __repr__(self) -> builtins.str: ... @typing.final +class PageOrder: + r""" + The order of a list page: `Id` by id, `Created` by creation time and then + by id. + """ + + Id: typing.ClassVar[PageOrder] + Created: typing.ClassVar[PageOrder] + +@typing.final class Partition: @property def id(self) -> builtins.int: @@ -4124,6 +4329,23 @@ """ @typing.final +class PartitionsPage: + r""" + One page of a list, as `IggyClient.get_partitions_page` returns it. + """ + @property + def items(self) -> builtins.list[Partition]: + r""" + The items of the page, in the order of the query. + """ + @property + def next(self) -> builtins.str | None: + r""" + Pass it as `cursor`, with the same other arguments, to read the + next page. `None` on the last page. + """ + +@typing.final class PendingOperationError(IggyError): r""" An operation with an unknown outcome, or a call that such an operation blocks. `operation_id` @@ -5185,6 +5407,23 @@ """ @typing.final +class StreamsPage: + r""" + One page of a list, as `IggyClient.get_streams_page` returns it. + """ + @property + def items(self) -> builtins.list[Stream]: + r""" + The items of the page, in the order of the query. + """ + @property + def next(self) -> builtins.str | None: + r""" + Pass it as `cursor`, with the same other arguments, to read the + next page. `None` on the last page. + """ + +@typing.final class SystemSnapshotType: r""" Type of system data to include in a snapshot. @@ -5645,6 +5884,23 @@ """ @typing.final +class TopicsPage: + r""" + One page of a list, as `IggyClient.get_topics_page` returns it. + """ + @property + def items(self) -> builtins.list[Topic]: + r""" + The items of the page, in the order of the query. + """ + @property + def next(self) -> builtins.str | None: + r""" + Pass it as `cursor`, with the same other arguments, to read the + next page. `None` on the last page. + """ + +@typing.final class UserHeaders(dict): r""" User headers dictionary returned by `ReceiveMessage.user_headers`. @@ -5789,6 +6045,23 @@ """ @typing.final +class UsersPage: + r""" + One page of a list, as `IggyClient.get_users_page` returns it. + """ + @property + def items(self) -> builtins.list[UserInfo]: + r""" + The items of the page, in the order of the query. + """ + @property + def next(self) -> builtins.str | None: + r""" + Pass it as `cursor`, with the same other arguments, to read the + next page. `None` on the last page. + """ + +@typing.final class WebSocketConfig: r""" Configuration for the WebSocket transport, accepted by `IggyClient(...)`.
diff --git a/foreign/python/pyproject.toml b/foreign/python/pyproject.toml index cdc3294..d0c1492 100644 --- a/foreign/python/pyproject.toml +++ b/foreign/python/pyproject.toml
@@ -22,7 +22,7 @@ [project] name = "apache-iggy" requires-python = ">=3.11" -version = "0.10.0" +version = "0.10.1.dev1" description = "Apache Iggy is the persistent message streaming platform written in Rust, supporting QUIC, TCP and HTTP transport protocols, capable of processing millions of messages per second." readme = "README.md" license = { file = "LICENSE" }
diff --git a/foreign/python/src/client.rs b/foreign/python/src/client.rs index 2c0ab60..3c17024 100644 --- a/foreign/python/src/client.rs +++ b/foreign/python/src/client.rs
@@ -47,6 +47,10 @@ MetadataChangeGroup, MetadataChangeStart, MetadataChanges, validated_query, }; use crate::options::OptionSpec as PyOptionSpec; +use crate::page::{ + ConsumerGroupsPage, PageOrder, PartitionsPage, StreamsPage, TopicsPage, UsersPage, + validated_named_page_query, validated_page_query, +}; use crate::partitioning::PyPartitioning; use crate::permissions::Permissions as PyPermissions; use crate::poll_options::PollOptions; @@ -646,7 +650,11 @@ }) } - /// Get the info about all the users. + /// Get the info about all the users, in id order. + /// + /// The list is read in pages of 1,000, so it is not one consistent read. + /// A user that someone creates or deletes during the read can appear or + /// not appear. `get_users_page` reads one page. /// /// Returns: /// An awaitable that resolves to `list[UserInfo]`. @@ -663,6 +671,41 @@ }) } + /// Reads one page of the users. `name` matches the username. + /// + /// Takes the keyword arguments of `get_streams_page`, with the same + /// cursor rules. + /// + /// Returns: + /// An awaitable that resolves to `UsersPage`. + /// + /// Raises: + /// OverflowError: If `limit` is outside the unsigned 32-bit range. + /// IggyError: As for `get_streams_page`. A user without the permission + /// to read the users gets the unauthorized code. + #[pyo3(signature = (*, order=None, descending=false, limit=None, cursor=None, name=None))] + #[gen_stub(override_return_type(type_repr="collections.abc.Awaitable[UsersPage]", imports=("collections.abc")))] + fn get_users_page<'a>( + &self, + py: Python<'a>, + #[gen_stub(override_type(type_repr = "PageOrder | None"))] order: Option<PageOrder>, + descending: bool, + #[gen_stub(override_type(type_repr = "builtins.int | None"))] limit: Option<u32>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] cursor: Option<&str>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] name: Option<String>, + ) -> PyResult<Bound<'a, PyAny>> { + let query = validated_named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + future_into_py(py, async move { + let page = inner + .get_users_page(&query) + .await + .map_err(to_runtime_error)?; + UsersPage::try_from(page) + }) + } + /// Create a new user. /// /// Args: @@ -1029,7 +1072,9 @@ /// Gets stream by id. /// Returns the stream details, or `None` if the stream does not exist. - /// Raises `RuntimeError` on failure. + /// Raises `RuntimeError` on failure. Over TCP, QUIC and WebSocket, a reply + /// larger than the reply size limit raises `IggyError` with code 97 + /// (`ReplyTooLarge`). `get_topics_page` reads the topics in pages. #[gen_stub(override_return_type(type_repr="collections.abc.Awaitable[StreamDetails | None]", imports=("collections.abc")))] fn get_stream<'a>( &self, @@ -1048,7 +1093,11 @@ }) } - /// Return all streams. + /// Return all streams, in id order. + /// + /// The list is read in pages of 1,000, so it is not one consistent read. + /// A stream that someone creates or deletes during the read can appear or + /// not appear. `get_streams_page` reads one page. /// /// Returns: /// A list of `Stream` summaries. @@ -1065,6 +1114,56 @@ }) } + /// Reads one page of the streams. + /// + /// Pass the page's `next` as `cursor`, with the same other arguments, to + /// read the next page. The read ends at the first page whose `next` is + /// `None`. A page can be empty and still have a `next`. + /// + /// Args: + /// order: `PageOrder.Id`, the default, or `PageOrder.Created`. + /// descending: Read from the last item to the first. + /// limit: Items per page, 1 to 1000. Defaults to 100. + /// cursor: The `next` of the previous page, `None` for the first page. + /// name: Keep only the items whose name holds this text, case-sensitive. + /// 1 to 255 bytes. + /// + /// Returns: + /// An awaitable that resolves to `StreamsPage`. + /// + /// Raises: + /// OverflowError: If `limit` is outside the unsigned 32-bit range. + /// IggyError: If the request fails. A cursor or a query that breaks + /// the page rules raises it with the invalid command code before + /// anything is sent. The server refuses a cursor that it cannot + /// use, such as the cursor of another order, with the same code. + /// Over HTTP, a refusal from the server has code 300 (HTTP response + /// error), and its message holds the server error body. A user + /// without the permission to read the streams gets the + /// unauthorized code. + #[pyo3(signature = (*, order=None, descending=false, limit=None, cursor=None, name=None))] + #[gen_stub(override_return_type(type_repr="collections.abc.Awaitable[StreamsPage]", imports=("collections.abc")))] + fn get_streams_page<'a>( + &self, + py: Python<'a>, + #[gen_stub(override_type(type_repr = "PageOrder | None"))] order: Option<PageOrder>, + descending: bool, + #[gen_stub(override_type(type_repr = "builtins.int | None"))] limit: Option<u32>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] cursor: Option<&str>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] name: Option<String>, + ) -> PyResult<Bound<'a, PyAny>> { + let query = validated_named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + future_into_py(py, async move { + let page = inner + .get_streams_page(&query) + .await + .map_err(to_runtime_error)?; + StreamsPage::try_from(page) + }) + } + /// Update a stream selected by name or numeric ID. /// /// A patch: only the fields passed change. The stream keeps its id, its @@ -1205,7 +1304,9 @@ /// Gets topic by stream and id. /// Returns the topic details, or `None` if the topic does not exist. - /// Raises `RuntimeError` on failure. + /// Raises `RuntimeError` on failure. Over TCP, QUIC and WebSocket, a reply + /// larger than the reply size limit raises `IggyError` with code 97 + /// (`ReplyTooLarge`). `get_partitions_page` reads the partitions in pages. #[gen_stub(override_return_type(type_repr="collections.abc.Awaitable[TopicDetails | None]", imports=("collections.abc")))] fn get_topic<'a>( &self, @@ -1226,7 +1327,11 @@ }) } - /// Get all topics in a stream. + /// Get all topics in a stream, in id order. + /// + /// The list is read in pages of 1,000, so it is not one consistent read. + /// A topic that someone creates or deletes during the read can appear or + /// not appear. `get_topics_page` reads one page. /// /// Args: /// stream_id: Stream identifier as `str | int`. @@ -1254,6 +1359,49 @@ }) } + /// Reads one page of the topics of a stream. A missing stream gives an + /// empty page without `next`. + /// + /// Takes the keyword arguments of `get_streams_page`, with the same + /// cursor rules. + /// + /// Args: + /// stream_id: Stream identifier as `str | int`. + /// + /// Returns: + /// An awaitable that resolves to `TopicsPage`. + /// + /// Raises: + /// ValueError: If the identifier is invalid. + /// OverflowError: If `limit` is outside the unsigned 32-bit range. + /// IggyError: As for `get_streams_page`. A user without the permission + /// to read the topics gets the unauthorized code. + #[pyo3(signature = (stream_id, *, order=None, descending=false, limit=None, cursor=None, name=None))] + #[allow(clippy::too_many_arguments)] + #[gen_stub(override_return_type(type_repr="collections.abc.Awaitable[TopicsPage]", imports=("collections.abc")))] + fn get_topics_page<'a>( + &self, + py: Python<'a>, + stream_id: PyIdentifier, + #[gen_stub(override_type(type_repr = "PageOrder | None"))] order: Option<PageOrder>, + descending: bool, + #[gen_stub(override_type(type_repr = "builtins.int | None"))] limit: Option<u32>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] cursor: Option<&str>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] name: Option<String>, + ) -> PyResult<Bound<'a, PyAny>> { + let stream_id = Identifier::try_from(stream_id)?; + let query = validated_named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + future_into_py(py, async move { + let page = inner + .get_topics_page(&stream_id, &query) + .await + .map_err(to_runtime_error)?; + TopicsPage::try_from(page) + }) + } + /// Update an existing topic. /// /// A patch, not a replacement: only the fields passed change, every other @@ -1484,6 +1632,52 @@ }) } + /// Reads one page of the partitions of a topic. + /// + /// Takes the keyword arguments of `get_streams_page` except `name`, + /// because a partition has no name. The cursor rules are the same. + /// Partition ids follow creation, so `PageOrder.Created` gives the id + /// order too. + /// + /// Args: + /// stream_id: Stream identifier as `str | int`. + /// topic_id: Topic identifier as `str | int`. + /// + /// Returns: + /// An awaitable that resolves to `PartitionsPage`. + /// + /// Raises: + /// ValueError: If an identifier is invalid. + /// OverflowError: If `limit` is outside the unsigned 32-bit range. + /// IggyError: As for `get_streams_page`. A user without the permission + /// to read the topic gets the unauthorized code. + #[pyo3(signature = (stream_id, topic_id, *, order=None, descending=false, limit=None, cursor=None))] + #[allow(clippy::too_many_arguments)] + #[gen_stub(override_return_type(type_repr="collections.abc.Awaitable[PartitionsPage]", imports=("collections.abc")))] + fn get_partitions_page<'a>( + &self, + py: Python<'a>, + stream_id: PyIdentifier, + topic_id: PyIdentifier, + #[gen_stub(override_type(type_repr = "PageOrder | None"))] order: Option<PageOrder>, + descending: bool, + #[gen_stub(override_type(type_repr = "builtins.int | None"))] limit: Option<u32>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] cursor: Option<&str>, + ) -> PyResult<Bound<'a, PyAny>> { + let stream_id = Identifier::try_from(stream_id)?; + let topic_id = Identifier::try_from(topic_id)?; + let query = validated_page_query(order, descending, limit, cursor)?; + let inner = self.inner.clone(); + + future_into_py(py, async move { + let page = inner + .get_partitions_page(&stream_id, &topic_id, &query) + .await + .map_err(to_runtime_error)?; + PartitionsPage::try_from(page) + }) + } + /// Delete the oldest sealed segments of a partition, including all messages /// stored in them. The active segment is never deleted, and deletion stops at /// the lowest offset any consumer or consumer group has committed on the @@ -1602,7 +1796,11 @@ }) } - /// Get all consumer groups for the specified stream and topic. + /// Get all consumer groups for the specified stream and topic, in id order. + /// + /// The list is read in pages of 1,000, so it is not one consistent read. + /// A group that someone creates or deletes during the read can appear or + /// not appear. `get_consumer_groups_page` reads one page. /// /// Args: /// stream_id: Stream identifier as `str | int`. @@ -1637,6 +1835,52 @@ }) } + /// Reads one page of the consumer groups of a topic. + /// + /// Takes the keyword arguments of `get_streams_page`, with the same + /// cursor rules. Group ids follow creation, so `PageOrder.Created` gives + /// the id order too. + /// + /// Args: + /// stream_id: Stream identifier as `str | int`. + /// topic_id: Topic identifier as `str | int`. + /// + /// Returns: + /// An awaitable that resolves to `ConsumerGroupsPage`. + /// + /// Raises: + /// ValueError: If an identifier is invalid. + /// OverflowError: If `limit` is outside the unsigned 32-bit range. + /// IggyError: As for `get_streams_page`. A user without the permission + /// to read the topic gets the unauthorized code. + #[pyo3(signature = (stream_id, topic_id, *, order=None, descending=false, limit=None, cursor=None, name=None))] + #[allow(clippy::too_many_arguments)] + #[gen_stub(override_return_type(type_repr="collections.abc.Awaitable[ConsumerGroupsPage]", imports=("collections.abc")))] + fn get_consumer_groups_page<'a>( + &self, + py: Python<'a>, + stream_id: PyIdentifier, + topic_id: PyIdentifier, + #[gen_stub(override_type(type_repr = "PageOrder | None"))] order: Option<PageOrder>, + descending: bool, + #[gen_stub(override_type(type_repr = "builtins.int | None"))] limit: Option<u32>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] cursor: Option<&str>, + #[gen_stub(override_type(type_repr = "builtins.str | None"))] name: Option<String>, + ) -> PyResult<Bound<'a, PyAny>> { + let stream_id = Identifier::try_from(stream_id)?; + let topic_id = Identifier::try_from(topic_id)?; + let query = validated_named_page_query(order, descending, limit, cursor, name)?; + let inner = self.inner.clone(); + + future_into_py(py, async move { + let page = inner + .get_consumer_groups_page(&stream_id, &topic_id, &query) + .await + .map_err(to_runtime_error)?; + ConsumerGroupsPage::try_from(page) + }) + } + /// Delete a consumer group for a stream and topic. /// /// Args: @@ -2776,6 +3020,27 @@ } #[test] + fn given_reply_too_large_when_mapping_should_keep_its_code() { + const REPLY_TOO_LARGE_CODE: u32 = 97; + Python::initialize(); + Python::attach(|py| { + let raised = to_runtime_error(IggyError::ReplyTooLarge); + assert!(raised.is_instance_of::<PyIggyError>(py)); + assert!(!raised.is_instance_of::<OptionError>(py)); + assert!(!raised.is_instance_of::<PendingOperationError>(py)); + assert_eq!( + raised + .value(py) + .getattr("code") + .unwrap() + .extract::<u32>() + .unwrap(), + REPLY_TOO_LARGE_CODE + ); + }); + } + + #[test] fn given_read_error_of_the_whole_reader_when_mapping_should_have_no_partition_or_skip() { Python::initialize(); Python::attach(|py| {
diff --git a/foreign/python/src/lib.rs b/foreign/python/src/lib.rs index 804cde5..fa56063 100644 --- a/foreign/python/src/lib.rs +++ b/foreign/python/src/lib.rs
@@ -24,6 +24,7 @@ mod identifier; mod metadata_changes; mod options; +mod page; mod partitioning; mod permissions; mod poll_options; @@ -61,6 +62,7 @@ MetadataUnknownItem, MetadataUserChange, MetadataUserIdentity, MetadataUserPermissionsUpdated, }; use options::OptionSpec; +use page::{ConsumerGroupsPage, PageOrder, PartitionsPage, StreamsPage, TopicsPage, UsersPage}; use partitioning::Partitioning; use permissions::{GlobalPermissions, Permissions, StreamPermissions, TopicPermissions}; use poll_options::{AutoCommit, CommitAfter, CommitEvery, CommitPolicy, PollOptions}; @@ -164,6 +166,12 @@ m.add_class::<TopicPermissions>()?; m.add_class::<SnapshotCompression>()?; m.add_class::<SystemSnapshotType>()?; + m.add_class::<PageOrder>()?; + m.add_class::<StreamsPage>()?; + m.add_class::<TopicsPage>()?; + m.add_class::<PartitionsPage>()?; + m.add_class::<ConsumerGroupsPage>()?; + m.add_class::<UsersPage>()?; m.add_class::<MetadataChanges>()?; m.add_class::<MetadataChangeRecord>()?; m.add_class::<MetadataCurrentItem>()?;
diff --git a/foreign/python/src/page.rs b/foreign/python/src/page.rs new file mode 100644 index 0000000..616bee4 --- /dev/null +++ b/foreign/python/src/page.rs
@@ -0,0 +1,372 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use iggy::prelude::{ + ConsumerGroup as RustConsumerGroup, NamedPageQuery, Page, PageCursor, + PageOrder as RustPageOrder, PageQuery, Partition as RustPartition, Stream as RustStream, + Topic as RustTopic, UserInfo as RustUserInfo, +}; +use pyo3::prelude::*; +use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pyclass_enum}; +use std::str::FromStr; + +use crate::client::to_runtime_error; +use crate::consumer::ConsumerGroup; +use crate::event_loop::attach_unless_exiting; +use crate::stream::Stream; +use crate::topic::{Partition, Topic}; +use crate::user::UserInfo; + +/// The order of a list page: `Id` by id, `Created` by creation time and then +/// by id. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[gen_stub_pyclass_enum] +#[pyclass(eq, frozen, hash, from_py_object)] +pub enum PageOrder { + Id, + Created, +} + +impl From<PageOrder> for RustPageOrder { + fn from(order: PageOrder) -> Self { + match order { + PageOrder::Id => Self::Id, + PageOrder::Created => Self::Created, + } + } +} + +/// The query of a page method. A bad cursor or query fails here, at the call, +/// so every transport raises the same invalid command code before any I/O. +pub(crate) fn validated_page_query( + order: Option<PageOrder>, + descending: bool, + limit: Option<u32>, + cursor: Option<&str>, +) -> PyResult<PageQuery> { + let defaults = PageQuery::default(); + let query = PageQuery { + order: order.map_or(defaults.order, Into::into), + descending, + limit: limit.unwrap_or(defaults.limit), + cursor: cursor + .map(PageCursor::from_str) + .transpose() + .map_err(to_runtime_error)?, + }; + query.validate().map_err(to_runtime_error)?; + Ok(query) +} + +/// [`validated_page_query`] with the name filter of the lists of named +/// entities. +pub(crate) fn validated_named_page_query( + order: Option<PageOrder>, + descending: bool, + limit: Option<u32>, + cursor: Option<&str>, + name: Option<String>, +) -> PyResult<NamedPageQuery> { + let query = NamedPageQuery { + page: validated_page_query(order, descending, limit, cursor)?, + name, + }; + query.validate().map_err(to_runtime_error)?; + Ok(query) +} + +macro_rules! list_page { + ($page:ident, $item:ident, $rust_item:ty, $method:literal) => { + #[doc = concat!("One page of a list, as `IggyClient.", $method, "` returns it.")] + #[gen_stub_pyclass] + #[pyclass(frozen)] + pub struct $page { + /// The items of the page, in the order of the query. + #[pyo3(get)] + items: Vec<Py<$item>>, + /// Pass it as `cursor`, with the same other arguments, to read the + /// next page. `None` on the last page. + #[pyo3(get)] + next: Option<String>, + } + + impl TryFrom<Page<$rust_item>> for $page { + type Error = PyErr; + + fn try_from(page: Page<$rust_item>) -> PyResult<Self> { + let items = attach_unless_exiting(|py| { + page.items + .into_iter() + .map(|item| Py::new(py, $item::from(item))) + .collect() + })?; + Ok(Self { + items, + next: page.next.map(|cursor| cursor.to_string()), + }) + } + } + }; +} + +list_page!(StreamsPage, Stream, RustStream, "get_streams_page"); +list_page!(TopicsPage, Topic, RustTopic, "get_topics_page"); +list_page!( + PartitionsPage, + Partition, + RustPartition, + "get_partitions_page" +); +list_page!( + ConsumerGroupsPage, + ConsumerGroup, + RustConsumerGroup, + "get_consumer_groups_page" +); +list_page!(UsersPage, UserInfo, RustUserInfo, "get_users_page"); + +#[cfg(test)] +mod tests { + use super::*; + use iggy::prelude::{Identifier, IggyError}; + use iggy_binary_protocol::primitives::page::WirePageQuery; + use iggy_binary_protocol::requests::consumer_groups::GetConsumerGroupsRequest; + use iggy_binary_protocol::requests::partitions::GetPartitionsRequest; + use iggy_binary_protocol::requests::streams::GetStreamsRequest; + use iggy_binary_protocol::requests::topics::GetTopicsRequest; + use iggy_binary_protocol::requests::users::GetUsersRequest; + use iggy_binary_protocol::responses::PageResponse; + use iggy_binary_protocol::responses::consumer_groups::ConsumerGroupResponse; + use iggy_binary_protocol::responses::streams::{StreamResponse, TopicResponse}; + use iggy_binary_protocol::responses::topics::PartitionResponse; + use iggy_binary_protocol::responses::users::UserResponse; + use iggy_binary_protocol::{WireDecode, WireEncode, WireIdentifier}; + use iggy_common::wire_conversions::{identifier_to_wire, page_from_wire}; + use pyo3::PyClass; + use serde_json::Value; + + use crate::client::PyIggyError; + use crate::identifier::PyIdentifier; + + const FIXTURE: &str = include_str!("../tests/fixtures/list_pages.json"); + + #[test] + fn given_request_vectors_when_building_queries_should_encode_fixture_bytes() { + let fixture = fixture(); + for vector in vectors(&fixture["requests"]) { + let input = &vector["input"]; + let page = WirePageQuery::try_from(&query(input).expect("query is accepted")) + .expect("query encodes"); + let stream_id = || parent(&input["stream_id"]); + let topic_id = || parent(&input["topic_id"]); + let request = match vector["command"].as_str().expect("command") { + "get_streams" => GetStreamsRequest { page }.to_bytes(), + "get_users" => GetUsersRequest { page }.to_bytes(), + "get_topics" => GetTopicsRequest { + stream_id: stream_id(), + page, + } + .to_bytes(), + "get_partitions" => GetPartitionsRequest { + stream_id: stream_id(), + topic_id: topic_id(), + page, + } + .to_bytes(), + "get_consumer_groups" => GetConsumerGroupsRequest { + stream_id: stream_id(), + topic_id: topic_id(), + page, + } + .to_bytes(), + command => panic!("unknown command {command}"), + }; + assert_eq!( + request.to_vec(), + decode_hex(&vector["request_hex"]), + "{}", + vector["case"] + ); + } + } + + #[test] + fn given_response_vectors_when_converting_pages_should_expose_next_and_items() { + Python::initialize(); + let fixture = fixture(); + Python::attach(|py| { + for vector in vectors(&fixture["responses"]) { + let case = vector["case"].as_str().expect("case"); + let reply = decode_hex(&vector["response_hex"]); + let (page, name) = match vector["command"].as_str().expect("command") { + "get_streams" => ( + converted::<StreamResponse, _, StreamsPage>( + py, + &reply, + RustStream::try_from, + ), + Some("name"), + ), + "get_topics" => ( + converted::<TopicResponse, _, TopicsPage>(py, &reply, RustTopic::try_from), + Some("name"), + ), + "get_partitions" => ( + converted::<PartitionResponse, _, PartitionsPage>(py, &reply, |item| { + Ok(RustPartition::from(item)) + }), + None, + ), + "get_consumer_groups" => ( + converted::<ConsumerGroupResponse, _, ConsumerGroupsPage>( + py, + &reply, + |item| Ok(RustConsumerGroup::from(item)), + ), + Some("name"), + ), + "get_users" => ( + converted::<UserResponse, _, UsersPage>(py, &reply, RustUserInfo::try_from), + Some("username"), + ), + command => panic!("unknown command {command}"), + }; + + let next: Option<String> = page + .getattr("next") + .and_then(|next| next.extract()) + .expect("next"); + assert_eq!(next.as_deref(), vector["next"].as_str(), "{case}"); + let items = page.getattr("items").expect("items"); + let expected = vector["items"].as_array().expect("items"); + assert_eq!(items.len().expect("length"), expected.len(), "{case}"); + for (item, expected) in items.try_iter().expect("items iterate").zip(expected) { + let item = item.expect("item"); + let id: u64 = item.getattr("id").and_then(|id| id.extract()).expect("id"); + assert_eq!(Some(id), expected["id"].as_u64(), "{case}"); + let item_name = name.map(|attribute| { + item.getattr(attribute) + .and_then(|name| name.extract::<String>()) + .expect("name") + }); + assert_eq!(item_name.as_deref(), expected["name"].as_str(), "{case}"); + } + } + }); + } + + #[test] + fn given_refused_cursors_and_queries_when_building_queries_should_raise_invalid_command() { + Python::initialize(); + let fixture = fixture(); + let invalid_command = fixture["constants"]["errors"]["invalid_command"].as_u64(); + let cursors = vectors(&fixture["refused"]["cursors"]) + .iter() + .chain(vectors(&fixture["opaque_cursors"])); + Python::attach(|py| { + for vector in cursors { + let case = vector["case"].as_str().expect("case"); + let refused = validated_page_query(None, false, None, vector["text"].as_str()) + .expect_err(case); + assert_eq!(Some(code(py, &refused)), invalid_command, "{case}"); + } + for vector in vectors(&fixture["refused"]["queries"]) { + let case = vector["case"].as_str().expect("case"); + let refused = query(&vector["input"]).expect_err(case); + assert_eq!(Some(code(py, &refused)), invalid_command, "{case}"); + } + }); + } + + /// The query of a fixture input, through the function the page methods of + /// the named lists use. A partitions input has no name, so its query + /// encodes the page block of the partitions page method. + fn query(input: &Value) -> PyResult<NamedPageQuery> { + let order = match input["order"].as_str().expect("order") { + "id" => PageOrder::Id, + "created" => PageOrder::Created, + order => panic!("unknown order {order}"), + }; + validated_named_page_query( + Some(order), + input["descending"].as_bool().expect("descending"), + input["limit"] + .as_u64() + .map(|limit| u32::try_from(limit).expect("u32 limit")), + input["cursor"].as_str(), + input["name"].as_str().map(str::to_owned), + ) + } + + /// A parent id of a request, through the conversion the page methods use. + fn parent(id: &Value) -> WireIdentifier { + let id = match id["kind"].as_str().expect("identifier kind") { + "numeric" => PyIdentifier::Int( + id["value"] + .as_u64() + .and_then(|value| u32::try_from(value).ok()) + .expect("u32 id"), + ), + "named" => PyIdentifier::String(id["value"].as_str().expect("name").to_owned()), + kind => panic!("unknown identifier kind {kind}"), + }; + identifier_to_wire(&Identifier::try_from(id).expect("identifier")).expect("wire id") + } + + /// A reply decoded and converted as the page methods do it. + fn converted<'py, W, R, P>( + py: Python<'py>, + reply: &[u8], + item: impl FnMut(W) -> Result<R, IggyError>, + ) -> Bound<'py, PyAny> + where + W: WireDecode, + P: PyClass + Into<PyClassInitializer<P>> + TryFrom<Page<R>, Error = PyErr>, + { + let (wire, consumed) = PageResponse::<W>::decode(reply).expect("reply decodes"); + assert_eq!(consumed, reply.len()); + let page = page_from_wire(wire, item).expect("items convert"); + Bound::new(py, P::try_from(page).expect("page converts")) + .expect("page wraps") + .into_any() + } + + fn code(py: Python<'_>, error: &PyErr) -> u64 { + assert!(error.is_instance_of::<PyIggyError>(py)); + error + .value(py) + .getattr("code") + .and_then(|code| code.extract()) + .expect("code") + } + + fn fixture() -> Value { + serde_json::from_str(FIXTURE).expect("fixture parses") + } + + fn vectors(section: &Value) -> &Vec<Value> { + section.as_array().expect("vector list") + } + + fn decode_hex(text: &Value) -> Vec<u8> { + let text = text.as_str().expect("hex text"); + (0..text.len()) + .step_by(2) + .map(|index| u8::from_str_radix(&text[index..index + 2], 16).expect("hex byte")) + .collect() + } +}
diff --git a/foreign/python/tests/fixtures/list_pages.json b/foreign/python/tests/fixtures/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/python/tests/fixtures/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/python/tests/fixtures/resource_options.json b/foreign/python/tests/fixtures/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/python/tests/fixtures/resource_options.json +++ b/foreign/python/tests/fixtures/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/python/tests/test_list_pages.py b/foreign/python/tests/test_list_pages.py new file mode 100644 index 0000000..33f5e17 --- /dev/null +++ b/foreign/python/tests/test_list_pages.py
@@ -0,0 +1,293 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +""" +Tests for reading the list commands one page at a time. + +The server cases run once per transport through `transport_client`. Other +tests share the server, so each case filters by a name of its own. A page can +hold fewer items than its limit and still have a `next`, so each case reads +every page of a query and never expects a page count. The vector cases read +the fixture the Rust encoders generated and need no server. +""" + +import functools +import json +from pathlib import Path + +import pytest + +from apache_iggy import IggyClient, IggyError, PageOrder, TopicOptions + +from .utils import unique_credentials + +FIXTURE = json.loads( + (Path(__file__).parent / "fixtures" / "list_pages.json").read_text() +) +INVALID_COMMAND = FIXTURE["constants"]["errors"]["invalid_command"] +DEFAULT_LIMIT = FIXTURE["constants"]["default_limit"] +# Over HTTP the SDK reports a refusal it has no typed error for as this code, +# with the error body of the server in the message. +HTTP_RESPONSE_ERROR = 300 +HTTP_TRANSPORT = "http" +ID_CURSOR = next( + vector["text"] for vector in FIXTURE["cursors"] if vector["case"] == "id_seven" +) +UNIQUE_NAME_BYTES = 32 +SMALL_PAGE = 2 +STREAMS_COUNT = 3 +PARTITIONS_COUNT = 3 +TOPIC = "events" +OTHER_NAME = "other" +RESERVED_CHARACTERS = " a+b&c=d %e#f/?" +NO_SERVER_ADDRESS = "127.0.0.1:1" +TRANSPORT_SCHEMES = ("tcp", "quic", "http", "ws") +LIMITS_OUTSIDE_U32 = (-1, 2**32) +PARENT_ID = 1 + + +@pytest.mark.usefixtures("iggy_client") +class TestListPages: + """Page reads on every transport.""" + + @pytest.mark.asyncio + async def test_given_three_streams_when_walking_pages_of_two_should_read_them_in_each_order( # noqa: E501 + self, transport_client: IggyClient, unique_name + ): + """Pages of at most two streams cannot hold all three in one page.""" + name = unique_name(min_bytes=UNIQUE_NAME_BYTES, max_bytes=UNIQUE_NAME_BYTES) + streams = [ + await transport_client.create_stream(f"{name}-{index}") + for index in range(STREAMS_COUNT) + ] + by_id = sorted(stream.id for stream in streams) + by_created = [ + stream.id + for stream in sorted( + streams, key=lambda stream: (stream.created_at, stream.id) + ) + ] + read = transport_client.get_streams_page + + assert await walk_ids(read, limit=SMALL_PAGE, name=name) == by_id + assert ( + await walk_ids(read, limit=SMALL_PAGE, name=name, descending=True) + == by_id[::-1] + ) + assert ( + await walk_ids(read, limit=SMALL_PAGE, name=name, order=PageOrder.Created) + == by_created + ) + + @pytest.mark.asyncio + async def test_given_topic_with_three_partitions_when_reading_pages_of_two_should_return_them_by_id( # noqa: E501 + self, transport_client: IggyClient, unique_name + ): + """The cursors lead through every partition in both directions.""" + stream = await transport_client.create_stream(unique_name()) + await transport_client.create_topic( + stream.id, TOPIC, TopicOptions(partitions_count=PARTITIONS_COUNT) + ) + read = functools.partial(transport_client.get_partitions_page, stream.id, TOPIC) + ids = list(range(PARTITIONS_COUNT)) + + assert await walk_ids(read, limit=SMALL_PAGE) == ids + assert await walk_ids(read, limit=SMALL_PAGE, descending=True) == ids[::-1] + + @pytest.mark.asyncio + async def test_given_a_name_filter_when_reading_topics_groups_and_users_should_keep_only_matching_names( # noqa: E501 + self, transport_client: IggyClient, unique_name + ): + """Only the entries whose name holds the filter text come back.""" + name, password = unique_credentials(unique_name) + topic = f"{name}-topic" + stream = await transport_client.create_stream(f"{name}-stream") + await transport_client.create_topic(stream.id, topic) + await transport_client.create_topic(stream.id, OTHER_NAME) + await transport_client.create_consumer_group(stream.id, topic, f"{name}-group") + await transport_client.create_consumer_group(stream.id, topic, OTHER_NAME) + user = await transport_client.create_user(name, password) + try: + topics = await walk( + functools.partial(transport_client.get_topics_page, stream.id), + name=name, + ) + groups = await walk( + functools.partial( + transport_client.get_consumer_groups_page, stream.id, topic + ), + name=name, + ) + users = await walk(transport_client.get_users_page, name=name) + finally: + await transport_client.delete_user(user.id) + + assert [found.name for found in topics] == [topic] + assert [found.name for found in groups] == [f"{name}-group"] + assert [found.username for found in users] == [name] + + @pytest.mark.asyncio + async def test_given_a_name_with_reserved_characters_when_filtering_streams_should_match_it_exactly( # noqa: E501 + self, transport_client: IggyClient, unique_name + ): + """The HTTP server decodes the query as a form, so each character must arrive escaped.""" # noqa: E501 + name = unique_name(min_bytes=UNIQUE_NAME_BYTES, max_bytes=UNIQUE_NAME_BYTES) + stream = await transport_client.create_stream(f"{name}{RESERVED_CHARACTERS}") + + found = await walk_ids(transport_client.get_streams_page, name=stream.name) + + assert found == [stream.id] + + @pytest.mark.asyncio + async def test_given_a_cursor_the_server_cannot_use_when_reading_should_refuse_it_and_keep_working( # noqa: E501 + self, + transport_client: IggyClient, + unique_name, + request: pytest.FixtureRequest, + ): + """An id cursor in a creation walk is refused. + + Over HTTP the refusal has the HTTP response error code, and its error + body holds the server code. + """ + assert isinstance(request.node, pytest.Function) + transport = request.node.callspec.params["transport_client"] + code = HTTP_RESPONSE_ERROR if transport == HTTP_TRANSPORT else INVALID_COMMAND + stream = await transport_client.create_stream(unique_name()) + + with pytest.raises(IggyError) as refusal: + await transport_client.get_streams_page( + order=PageOrder.Created, cursor=ID_CURSOR + ) + assert refusal.value.code == code + assert server_code(refusal.value) == INVALID_COMMAND + + found = await walk_ids(transport_client.get_streams_page, name=stream.name) + assert found == [stream.id] + + +class TestListPagesVectors: + """Page reads on a client that never connects.""" + + @pytest.mark.unit + @pytest.mark.parametrize("scheme", TRANSPORT_SCHEMES) + def test_given_refused_and_opaque_cursor_texts_when_reading_should_raise_before_network_io( # noqa: E501 + self, scheme: str + ): + """A client that never connects proves the refusal happens before I/O.""" + client = never_connected(scheme) + for vector in FIXTURE["refused"]["cursors"] + FIXTURE["opaque_cursors"]: + for read in page_reads(client): + with pytest.raises(IggyError, match="Invalid command") as refusal: + read(cursor=vector["text"]) + assert refusal.value.code == INVALID_COMMAND, vector["case"] + + @pytest.mark.unit + @pytest.mark.parametrize("scheme", TRANSPORT_SCHEMES) + def test_given_refused_query_vectors_when_reading_should_raise_before_network_io( # noqa: E501 + self, scheme: str + ): + """A limit or a name out of range fails at the call.""" + client = never_connected(scheme) + for vector in FIXTURE["refused"]["queries"]: + for read in page_reads(client, vector["input"]): + with pytest.raises(IggyError, match="Invalid command") as refusal: + read(**page_arguments(vector["input"])) + assert refusal.value.code == INVALID_COMMAND, vector["case"] + + @pytest.mark.unit + def test_given_a_limit_outside_the_u32_range_when_reading_should_raise_overflow_error( # noqa: E501 + self, + ): + """The limit fails in the argument conversion, as in `create_partitions`.""" + client = IggyClient(NO_SERVER_ADDRESS) + for limit in LIMITS_OUTSIDE_U32: + for read in page_reads(client): + with pytest.raises(OverflowError): + read(limit=limit) + + @pytest.mark.unit + @pytest.mark.asyncio + async def test_given_request_vectors_when_reading_should_pass_validation(self): + """Accepted queries get past validation and fail only on the transport.""" + client = IggyClient(NO_SERVER_ADDRESS) + for vector in FIXTURE["requests"]: + for read in page_reads(client, vector["input"]): + with pytest.raises(IggyError) as failure: + await read(**page_arguments(vector["input"])) + assert failure.value.code != INVALID_COMMAND, vector["case"] + + +async def walk(read_page, **query) -> list: + """The items of every page of a query, read until a page has no `next`.""" + items = [] + cursor: str | None = None + while True: + page = await read_page(**query, cursor=cursor) + assert len(page.items) <= query.get("limit", DEFAULT_LIMIT) + items.extend(page.items) + cursor = page.next + if cursor is None: + return items + + +async def walk_ids(read_page, **query) -> list[int]: + """The ids of every page of a query.""" + return [item.id for item in await walk(read_page, **query)] + + +def server_code(error: IggyError) -> int: + """The code of a server refusal, read from the HTTP error body when needed.""" + if error.code != HTTP_RESPONSE_ERROR: + return error.code + return json.loads(str(error).split("body: ", 1)[1])["id"] + + +def never_connected(scheme: str) -> IggyClient: + """A client of the transport, for an address that has no server.""" + return IggyClient.from_connection_string( + f"iggy+{scheme}://iggy:iggy@{NO_SERVER_ADDRESS}" + ) + + +def page_reads(client: IggyClient, query: dict | None = None): + """Each page method that takes `query`, with the parent ids it needs. + + `get_partitions_page` takes no `name`, so a query with a name skips it. + """ + named = ( + client.get_streams_page, + functools.partial(client.get_topics_page, PARENT_ID), + functools.partial(client.get_consumer_groups_page, PARENT_ID, PARENT_ID), + client.get_users_page, + ) + if query is not None and query["name"] is not None: + return named + return (*named, functools.partial(client.get_partitions_page, PARENT_ID, PARENT_ID)) + + +def page_arguments(query: dict) -> dict: + """The keyword arguments of a fixture query input, without a null name.""" + arguments = { + "order": getattr(PageOrder, query["order"].title()), + "descending": query["descending"], + "limit": query["limit"], + "cursor": query["cursor"], + } + if query["name"] is not None: + arguments["name"] = query["name"] + return arguments
diff --git a/foreign/python/uv.lock b/foreign/python/uv.lock index 05a50bd..4e58c9e 100644 --- a/foreign/python/uv.lock +++ b/foreign/python/uv.lock
@@ -11,7 +11,7 @@ [[package]] name = "apache-iggy" -version = "0.10.0" +version = "0.10.1.dev1" source = { editable = "." } [package.optional-dependencies]
diff --git a/foreign/swift/README.md b/foreign/swift/README.md index aea1729..562a408 100644 --- a/foreign/swift/README.md +++ b/foreign/swift/README.md
@@ -166,6 +166,32 @@ The server stores it wrapped and never returns it: reads report `encryptionKeySource`, `encryptionKeyFingerprint`, and `encryptionKekFingerprints`, and `EncryptionKey.fingerprint(_:)` computes the fingerprint of a key to compare. Without a key, a server with encryption enabled generates one for the stream. +### List pages + +`getStreams()`, `getTopics(streamID:)`, `getConsumerGroups(streamID:topicID:)` and `getUsers()` return a whole list. Each of them reads the list in pages of at most 1,000 items, so the result is not one consistent read. An entity that someone creates or deletes during the read can appear or not appear. The read keeps the sign-in it started with, and one request timeout covers every page. If the server answers with the cursor it was sent, the read fails with `invalidCommand`. + +`getStreamsPage(_:)`, `getTopicsPage(streamID:query:)`, `getPartitionsPage(streamID:topicID:query:)`, `getConsumerGroupsPage(streamID:topicID:query:)` and `getUsersPage(_:)` return one page. To read the next page, send the same query with the `next` of the page as its `cursor`. A page can be empty and still have a `next`: + +```swift +func printStreams(_ client: IggyClient) async throws { + var query = NamedPageQuery() + while true { + let page = try await client.getStreamsPage(query) + for stream in page.items { + print(stream.id, stream.name) + } + guard let next = page.next else { + return + } + query.page.cursor = next + } +} +``` + +A `PageQuery` holds `order`, `descending`, `limit` and `cursor`. `order` selects `.id` or `.created`, and `descending` reverses it. The stream, topic, consumer group and user page methods take a `NamedPageQuery`, which holds a `PageQuery` in `page` and an optional `name`. `name` keeps the entries whose name holds the text, case-sensitive. The partitions page method takes a `PageQuery`, which has no name. + +The client refuses a query that breaks the page rules with `invalidCommand`, before it sends anything. Examples are a limit outside 1 to 1000 and a name that is empty or longer than 255 bytes. A `PageCursor` prints as the `pg1_` text form that the HTTP API and the CLI use, and `PageCursor(text:)` reads it back. The client does not read the bytes of a cursor. The server refuses a cursor that it cannot use, also with `invalidCommand`. + ### Metadata changes `getMetadataChanges(_:)` reads the node's change log: one record per public result of a committed metadata operation, such as a stream created, a topic renamed, a user's permissions changed, or a session closed. A mirror keeps a cursor, asks for the records after it, and stores the returned `next` cursor. The call needs root or the global `manageServers` permission: @@ -562,7 +588,7 @@ cargo run --manifest-path Tools/golden-vectors/Cargo.toml -- Tests/IggyTests/Fixtures/golden.json ``` -The resource options tests compare against `Tests/IggyTests/Fixtures/resource_options.json`, the fixture every SDK shares, generated by `core/common/examples/resource_options_fixtures.rs`. Never edit the copy. The metadata changes tests do the same with `Tests/IggyTests/Fixtures/metadata_changes.json`, generated by `core/common/examples/metadata_changes_fixtures.rs`. +The resource options tests compare against `Tests/IggyTests/Fixtures/resource_options.json`, the fixture every SDK shares, generated by `core/common/examples/resource_options_fixtures.rs`. Never edit the copy. The metadata changes tests do the same with `Tests/IggyTests/Fixtures/metadata_changes.json`, generated by `core/common/examples/metadata_changes_fixtures.rs`. The list page tests do the same with `Tests/IggyTests/Fixtures/list_pages.json`, generated by `core/common/examples/list_pages_fixtures.rs`. The metadata changes scenario that churns the change log past its capacity runs only when `IGGY_METADATA_CHANGE_LOG_RESOURCE_CAPACITY` is set for both the server and the test run, for example to 64.
diff --git a/foreign/swift/Sources/Iggy/Client/IggyClient+Resources.swift b/foreign/swift/Sources/Iggy/Client/IggyClient+Resources.swift index d6c8aaa..1b71898 100644 --- a/foreign/swift/Sources/Iggy/Client/IggyClient+Resources.swift +++ b/foreign/swift/Sources/Iggy/Client/IggyClient+Resources.swift
@@ -30,11 +30,20 @@ return body.isEmpty ? nil : try Responses.streamDetails(body[...]) } - /// Every stream. + /// Every stream, read in pages of ``PageQuery/maxLimit`` in id order. The + /// pages are separate reads, so a stream that someone creates or deletes + /// during the read can appear or not appear. The read keeps the sign-in it + /// started with, and one request timeout covers every page. If the server + /// answers with the cursor it was sent, the read fails with + /// ``IggyErrorCode/invalidCommand``. public func getStreams() async throws -> [StreamInfo] { - let lineage = try await requireAuthenticated() - let body = try await send(.getStreams, lineage: lineage) - return body.isEmpty ? [] : try Responses.streams(body[...]) + try await readWholeList(.getStreams, item: Responses.stream(from:)) { try Requests.listPage(query: $0) } + } + + /// One page of the streams. A query that breaks a page rule fails with + /// ``IggyErrorCode/invalidCommand`` before anything is sent. + public func getStreamsPage(_ query: NamedPageQuery = NamedPageQuery()) async throws -> Page<StreamInfo> { + try await listPage(.getStreams, Requests.listPage(query: query), item: Responses.stream(from:)) } /// Creates a stream and returns it. A key in ``StreamCreateOptions/encryptionKey`` @@ -88,11 +97,22 @@ return details } - /// Every topic of a stream. + /// Every topic of a stream, read in pages of ``PageQuery/maxLimit`` in id + /// order. The pages are separate reads, so a topic that someone creates or + /// deletes during the read can appear or not appear. The read keeps the + /// sign-in it started with, and one request timeout covers every page. A + /// stream that does not exist has no topics. If someone deletes the stream + /// between two pages, the read fails with + /// ``IggyErrorCode/streamIdNotFound``. If the server answers with the + /// cursor it was sent, the read fails with ``IggyErrorCode/invalidCommand``. public func getTopics(streamID: Identifier) async throws -> [Topic] { - let lineage = try await requireAuthenticated() - let body = try await send(.getTopics, Requests.identifierOnly(streamID), lineage: lineage) - return body.isEmpty ? [] : try Responses.topics(body[...]) + try await readWholeList(.getTopics, item: Responses.topic(from:)) { try Requests.listPage(streamID, query: $0) } + } + + /// One page of the topics of a stream. A query that breaks a page rule + /// fails with ``IggyErrorCode/invalidCommand`` before anything is sent. + public func getTopicsPage(streamID: Identifier, query: NamedPageQuery = NamedPageQuery()) async throws -> Page<Topic> { + try await listPage(.getTopics, Requests.listPage(streamID, query: query), item: Responses.topic(from:)) } /// Creates a topic and returns it. Every knob rides `options`; an absent @@ -145,6 +165,12 @@ core.groupState.invalidateTopicDiscovery() } + /// One page of the partitions of a topic. A query that breaks a page rule + /// fails with ``IggyErrorCode/invalidCommand`` before anything is sent. + public func getPartitionsPage(streamID: Identifier, topicID: Identifier, query: PageQuery = PageQuery()) async throws -> Page<Partition> { + try await listPage(.getPartitions, Requests.listPage(streamID, topicID, query: query), item: Responses.partition(from:)) + } + /// Removes the oldest `count` closed segments of a partition. public func deleteSegments(streamID: Identifier, topicID: Identifier, partitionID: UInt32, count: UInt32) async throws { let lineage = try await requireAuthenticated() @@ -163,11 +189,23 @@ return body.isEmpty ? nil : try Responses.consumerGroupDetails(body[...]) } - /// Every consumer group of a topic. + /// Every consumer group of a topic, read in pages of + /// ``PageQuery/maxLimit`` in id order. The pages are separate reads, so a + /// group that someone creates or deletes during the read can appear or not + /// appear. The read keeps the sign-in it started with, and one request + /// timeout covers every page. If the server answers with the cursor it was + /// sent, the read fails with ``IggyErrorCode/invalidCommand``. public func getConsumerGroups(streamID: Identifier, topicID: Identifier) async throws -> [ConsumerGroup] { - let lineage = try await requireAuthenticated() - let body = try await send(.getConsumerGroups, Requests.streamAndTopic(streamID, topicID), lineage: lineage) - return body.isEmpty ? [] : try Responses.consumerGroups(body[...]) + try await readWholeList(.getConsumerGroups, item: Responses.consumerGroup(from:)) { try Requests.listPage(streamID, topicID, query: $0) } + } + + /// One page of the consumer groups of a topic. A query that breaks a page + /// rule fails with ``IggyErrorCode/invalidCommand`` before anything is + /// sent. + public func getConsumerGroupsPage( + streamID: Identifier, topicID: Identifier, query: NamedPageQuery = NamedPageQuery() + ) async throws -> Page<ConsumerGroup> { + try await listPage(.getConsumerGroups, Requests.listPage(streamID, topicID, query: query), item: Responses.consumerGroup(from:)) } /// Creates a consumer group and returns it. @@ -211,11 +249,20 @@ return body.isEmpty ? nil : try Responses.userDetails(body[...]) } - /// Every user. + /// Every user, read in pages of ``PageQuery/maxLimit`` in id order. The + /// pages are separate reads, so a user that someone creates or deletes + /// during the read can appear or not appear. The read keeps the sign-in it + /// started with, and one request timeout covers every page. If the server + /// answers with the cursor it was sent, the read fails with + /// ``IggyErrorCode/invalidCommand``. public func getUsers() async throws -> [UserInfo] { - let lineage = try await requireAuthenticated() - let body = try await send(.getUsers, lineage: lineage) - return body.isEmpty ? [] : try Responses.users(body[...]) + try await readWholeList(.getUsers, item: Responses.user(from:)) { try Requests.listPage(query: $0) } + } + + /// One page of the users. A query that breaks a page rule fails with + /// ``IggyErrorCode/invalidCommand`` before anything is sent. + public func getUsersPage(_ query: NamedPageQuery = NamedPageQuery()) async throws -> Page<UserInfo> { + try await listPage(.getUsers, Requests.listPage(query: query), item: Responses.user(from:)) } /// Creates a user and returns it. @@ -280,3 +327,46 @@ _ = try await send(.deletePersonalAccessToken, try Requests.nameOnly(name), lineage: lineage) } } + +// MARK: - List pages + +extension IggyClient { + /// Reads the whole list that `code` answers one page at a time, in + /// ascending id order and in pages of ``PageQuery/maxLimit``, until a page + /// has no next cursor. The walk is one call: it keeps the lineage it + /// started with, and one request timeout covers every page. A page can be + /// empty and still have a next cursor. A next that equals the cursor + /// just sent can never end the walk, so it fails as a malformed reply. + func readWholeList<Item: Sendable & Hashable>( + _ code: CommandCode, item: (inout ByteReader) throws -> Item, payload: (PageQuery) throws -> [UInt8] + ) async throws -> [Item] { + let deadline = ContinuousClock.now + core.configuration.requestTimeout + let lineage = try await requireAuthenticated(within: deadline) + var query = PageQuery(limit: PageQuery.maxLimit) + var items: [Item] = [] + while true { + let page = try await listPage(code, try payload(query), lineage: lineage, deadline: deadline, item: item) + items += page.items + guard let next = page.next else { + return items + } + guard next != query.cursor else { + throw IggyError(.invalidCommand, context: "the server answered the page cursor it was sent") + } + query.cursor = next + } + } + + /// One page of the list that `code` answers. `captured` is the lineage + /// and `limit` the deadline that the call started with, so every page of + /// a walk is refused once the caller signed in or out, and the walk keeps + /// one budget. Nil takes the current lineage and a full request timeout, + /// for a call of this one page. + func listPage<Item: Sendable & Hashable>( + _ code: CommandCode, _ payload: [UInt8], lineage captured: UInt64? = nil, deadline limit: ContinuousClock.Instant? = nil, + item: (inout ByteReader) throws -> Item + ) async throws -> Page<Item> { + let lineage = try await requireAuthenticated(under: captured, within: limit) + return try Responses.page(try await send(code, payload, lineage: lineage, deadline: limit)[...], item: item) + } +}
diff --git a/foreign/swift/Sources/Iggy/Client/IggyClient.swift b/foreign/swift/Sources/Iggy/Client/IggyClient.swift index 6823a9a..7233d60 100644 --- a/foreign/swift/Sources/Iggy/Client/IggyClient.swift +++ b/foreign/swift/Sources/Iggy/Client/IggyClient.swift
@@ -274,9 +274,10 @@ // MARK: Internals shared by the domain extensions /// One request of a call that started under `lineage`, or, for a call - /// of this one request, under the lineage it is sent in. - func send(_ code: CommandCode, _ payload: [UInt8] = [], lineage: UInt64? = nil) async throws -> [UInt8] { - try await core.exchange(code: code.rawValue, payload: payload, lineage: lineage) + /// of this one request, under the lineage it is sent in. `deadline` caps + /// the request timeout for a call with a budget of its own. + func send(_ code: CommandCode, _ payload: [UInt8] = [], lineage: UInt64? = nil, deadline: ContinuousClock.Instant? = nil) async throws -> [UInt8] { + try await core.exchange(code: code.rawValue, payload: payload, deadline: deadline, lineage: lineage) } /// Fails unless the client is signed in, and returns the lineage the @@ -291,8 +292,8 @@ /// `captured`, such as a producer send: once the caller signed in or out /// since, the call is refused as unauthenticated before anything of it is /// written. - func requireAuthenticated(under captured: UInt64?) async throws -> UInt64 { - let started = try await requireAuthenticated() + func requireAuthenticated(under captured: UInt64?, within limit: ContinuousClock.Instant? = nil) async throws -> UInt64 { + let started = try await requireAuthenticated(within: limit) guard let captured else { return started }
diff --git a/foreign/swift/Sources/Iggy/Errors/IggyErrorCode.swift b/foreign/swift/Sources/Iggy/Errors/IggyErrorCode.swift index 3931b21..ebc7eac 100644 --- a/foreign/swift/Sources/Iggy/Errors/IggyErrorCode.swift +++ b/foreign/swift/Sources/Iggy/Errors/IggyErrorCode.swift
@@ -103,6 +103,7 @@ case producerUnknown = 94 case producerPartitionRequired = 95 case tieredReadFailed = 96 + case replyTooLarge = 97 case clientNotFound = 100 case invalidClientId = 101 case connectionClosed = 206 @@ -377,6 +378,7 @@ case .producerUnknown: "producer_unknown" case .producerPartitionRequired: "producer_partition_required" case .tieredReadFailed: "tiered_read_failed" + case .replyTooLarge: "reply_too_large" case .clientNotFound: "client_not_found" case .invalidClientId: "invalid_client_id" case .connectionClosed: "connection_closed"
diff --git a/foreign/swift/Sources/Iggy/Iggy.swift b/foreign/swift/Sources/Iggy/Iggy.swift index 967d541..9f8a0d4 100644 --- a/foreign/swift/Sources/Iggy/Iggy.swift +++ b/foreign/swift/Sources/Iggy/Iggy.swift
@@ -20,5 +20,5 @@ /// Name of this SDK as reported to the server. public static let sdkName = "swift-sdk" /// Version of this SDK as reported to the server and named by its `v<version>` release tag. - public static let sdkVersion = "0.2.0" + public static let sdkVersion = "0.2.1-edge.1" }
diff --git a/foreign/swift/Sources/Iggy/Models/Page.swift b/foreign/swift/Sources/Iggy/Models/Page.swift new file mode 100644 index 0000000..94e5345 --- /dev/null +++ b/foreign/swift/Sources/Iggy/Models/Page.swift
@@ -0,0 +1,143 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +/// The order of a list page. The raw value is its code on the wire. +public enum PageOrder: UInt8, Sendable, Hashable, CaseIterable { + /// The numeric ids. + case id = 0 + /// The creation order. Entities created at the same time keep the order + /// of their ids. Partitions and consumer groups walk by id in this order + /// too, because their ids follow creation. + case created = 1 +} + +/// The position after which the next page of a list starts. +/// +/// Send it back as it came, with the query that returned it: it holds no +/// order, direction, filter or parent. Only the server reads its bytes, so the +/// client keeps them unchanged. ``description``, `pg1_` followed by unpadded +/// Base64url of the bytes, is the text form that the HTTP API and the CLI use, +/// and ``init(text:)`` reads it back. +public struct PageCursor: Sendable, Hashable, CustomStringConvertible { + public static let textPrefix = "pg1_" + /// The most bytes of a cursor: its length on the wire is one byte. + public static let maxSize = Int(UInt8.max) + static let maxTextLength = textPrefix.utf8.count + (maxSize * 4 + 2) / 3 + + let bytes: [UInt8] + + /// Parses the `pg1_` text form. Fails with + /// ``IggyErrorCode/invalidCommand`` for any text but the prefix and + /// canonical unpadded Base64url of 1 to ``maxSize`` bytes, and the error + /// never repeats the text. The bytes are not checked: the server refuses a + /// cursor that it cannot use. + public init(text: String) throws { + guard text.utf8.count <= Self.maxTextLength, let bytes = Base64URL.decode(text, prefix: Self.textPrefix), let cursor = PageCursor(bytes: bytes) + else { + throw IggyError(.invalidCommand, context: "not a page cursor") + } + self = cursor + } + + /// A cursor of 1 to ``maxSize`` bytes, nil for any other count. A reply + /// marks its last page with a next of no bytes. + init?(bytes: [UInt8]) { + guard (1...Self.maxSize).contains(bytes.count) else { + return nil + } + self.bytes = bytes + } + + /// The `pg1_` text form. + public var description: String { + Self.textPrefix + Base64URL.encode(bytes) + } +} + +/// One page request of a list command. The defaults ask for the first page in +/// ascending id order, with ``defaultLimit`` items. The partitions page takes +/// this type, which has no name. The other lists take a ``NamedPageQuery``. +public struct PageQuery: Sendable, Hashable { + /// Items per page when the caller does not say. + public static let defaultLimit: UInt32 = 100 + /// The most items one page returns. + public static let maxLimit: UInt32 = 1000 + + public var order: PageOrder + /// Reverses ``order``. + public var descending: Bool + /// The most items of the page, 1 to ``maxLimit``. + public var limit: UInt32 + /// The ``Page/next`` of the previous page, nil for the first page. + public var cursor: PageCursor? + + public init(order: PageOrder = .id, descending: Bool = false, limit: UInt32 = defaultLimit, cursor: PageCursor? = nil) { + self.order = order + self.descending = descending + self.limit = limit + self.cursor = cursor + } + + /// The page rules that the server applies, checked before anything is + /// sent. Fails with ``IggyErrorCode/invalidCommand`` when the limit is + /// outside 1 to ``maxLimit``. + public func validate() throws { + guard (1...Self.maxLimit).contains(limit) else { + throw IggyError(.invalidCommand, context: "limit must be 1 to \(Self.maxLimit), got \(limit)") + } + } +} + +/// One page request of a list whose entries have a name: streams, topics, +/// consumer groups and users. It adds a name filter to ``page``. +public struct NamedPageQuery: Sendable, Hashable { + /// The most bytes of a name filter. + public static let maxNameSize = Identifier.maxNameLength + + public var page: PageQuery + /// Keeps only the entries whose name holds this text, case-sensitive. Nil + /// keeps every entry. + public var name: String? + + public init(page: PageQuery = PageQuery(), name: String? = nil) { + self.page = page + self.name = name + } + + /// The rules of ``PageQuery/validate()``, checked before anything is + /// sent. Also fails with ``IggyErrorCode/invalidCommand`` when the name is + /// empty or longer than ``maxNameSize`` bytes. + public func validate() throws { + try page.validate() + if let name, !(1...Self.maxNameSize).contains(name.utf8.count) { + throw IggyError(.invalidCommand, context: "name must be 1 to \(Self.maxNameSize) bytes, got \(name.utf8.count)") + } + } +} + +/// One page of a list. A page can be short or empty and still have a +/// ``next``. +public struct Page<Item: Sendable & Hashable>: Sendable, Hashable { + public var items: [Item] + /// The cursor of the next page, nil on the last page. + public var next: PageCursor? + + public init(items: [Item], next: PageCursor?) { + self.items = items + self.next = next + } +}
diff --git a/foreign/swift/Sources/Iggy/Protocol/CommandCode.swift b/foreign/swift/Sources/Iggy/Protocol/CommandCode.swift index 7145f68..4c34731 100644 --- a/foreign/swift/Sources/Iggy/Protocol/CommandCode.swift +++ b/foreign/swift/Sources/Iggy/Protocol/CommandCode.swift
@@ -70,6 +70,7 @@ // 304 was update_topic and 305 purge_topic. The server keeps both retired. case createPartitions = 402 case deletePartitions = 403 + case getPartitions = 404 case deleteSegments = 503 case getConsumerGroup = 600 case getConsumerGroups = 601 @@ -126,6 +127,7 @@ case .deleteTopic: "topic.delete" case .createPartitions: "partition.create" case .deletePartitions: "partition.delete" + case .getPartitions: "partition.list" case .deleteSegments: "segment.delete" case .getConsumerGroup: "consumer_group.get" case .getConsumerGroups: "consumer_group.list"
diff --git a/foreign/swift/Sources/Iggy/Protocol/ProtocolVersion.swift b/foreign/swift/Sources/Iggy/Protocol/ProtocolVersion.swift index eb87018..37bb298 100644 --- a/foreign/swift/Sources/Iggy/Protocol/ProtocolVersion.swift +++ b/foreign/swift/Sources/Iggy/Protocol/ProtocolVersion.swift
@@ -32,7 +32,7 @@ /// The protocol version this SDK implements: the version of the /// `iggy_binary_protocol` crate it was ported from. The golden fixture /// carries the crate's value and a test fails when the two diverge. - public static let current = ProtocolVersion(major: 0, minor: 12, patch: 2) + public static let current = ProtocolVersion(major: 0, minor: 12, patch: 3) public var major: UInt32 { packed >> 20 } public var minor: UInt32 { (packed >> 10) & 0x3FF }
diff --git a/foreign/swift/Sources/Iggy/Protocol/Requests.swift b/foreign/swift/Sources/Iggy/Protocol/Requests.swift index 32ed0cc..f42cb13 100644 --- a/foreign/swift/Sources/Iggy/Protocol/Requests.swift +++ b/foreign/swift/Sources/Iggy/Protocol/Requests.swift
@@ -452,6 +452,40 @@ writer.write(token) return writer.bytes } + + // MARK: List pages + + /// A list request: the parent identifiers, then the page block + /// `[order:u8][descending:u8][limit:u32][cursor_len:u8][cursor][name_len:u8][name]`, + /// where a length of 0 means no cursor or no name. A ``PageQuery`` sends a + /// name length of 0. A query that breaks a page rule fails with + /// ``IggyErrorCode/invalidCommand``, so both lengths fit their byte. + static func listPage(_ parents: Identifier..., query: PageQuery) throws -> [UInt8] { + try query.validate() + return try listPage(parents, query, name: nil) + } + + static func listPage(_ parents: Identifier..., query: NamedPageQuery) throws -> [UInt8] { + try query.validate() + return try listPage(parents, query.page, name: query.name) + } + + private static func listPage(_ parents: [Identifier], _ page: PageQuery, name: String?) throws -> [UInt8] { + var writer = ByteWriter() + for parent in parents { + try parent.encode(into: &writer) + } + writer.write(page.order.rawValue) + writer.write(page.descending) + writer.write(page.limit) + let cursor = page.cursor?.bytes ?? [] + writer.write(UInt8(cursor.count)) + writer.write(cursor) + let name = name ?? "" + writer.write(UInt8(name.utf8.count)) + writer.write(name) + return writer.bytes + } } /// Validates a wire name and returns it, so the length prefix can never
diff --git a/foreign/swift/Sources/Iggy/Protocol/Responses.swift b/foreign/swift/Sources/Iggy/Protocol/Responses.swift index ada1a24..5d931d0 100644 --- a/foreign/swift/Sources/Iggy/Protocol/Responses.swift +++ b/foreign/swift/Sources/Iggy/Protocol/Responses.swift
@@ -64,16 +64,6 @@ } } - static func streams(_ body: ArraySlice<UInt8>) throws -> [StreamInfo] { - try decode(body) { reader in - var streams: [StreamInfo] = [] - while !reader.isAtEnd { - streams.append(try stream(from: &reader)) - } - return streams - } - } - // MARK: Topics static func topic(from reader: inout ByteReader) throws -> Topic { @@ -125,18 +115,6 @@ } } - static func topics(_ body: ArraySlice<UInt8>) throws -> [Topic] { - try decode(body) { reader in - let count = try reader.readUInt32() - var topics: [Topic] = [] - for _ in 0..<count { - topics.append(try topic(from: &reader)) - } - topics.sort { $0.id < $1.id } - return topics - } - } - // MARK: Consumer groups static func consumerGroup(from reader: inout ByteReader) throws -> ConsumerGroup { @@ -165,16 +143,6 @@ } } - static func consumerGroups(_ body: ArraySlice<UInt8>) throws -> [ConsumerGroup] { - try decode(body) { reader in - var groups: [ConsumerGroup] = [] - while !reader.isAtEnd { - groups.append(try consumerGroup(from: &reader)) - } - return groups - } - } - static func consumerGroupAssignment(_ body: ArraySlice<UInt8>) throws -> ConsumerGroupAssignment { try decode(body) { reader in let generation = try reader.readUInt64() @@ -273,16 +241,6 @@ } } - static func users(_ body: ArraySlice<UInt8>) throws -> [UserInfo] { - try decode(body) { reader in - var users: [UserInfo] = [] - while !reader.isAtEnd { - users.append(try user(from: &reader)) - } - return users - } - } - struct LoginRegister { let userID: UInt32 let session: UInt64 @@ -429,6 +387,32 @@ } } + // MARK: List pages + + /// Decodes the reply of a list command, `[next_len:u8][next][count:u32][item]*`, + /// with the item decoder of its command. A body short of `count` items, or + /// with bytes after them, is refused. A next of no bytes marks the last + /// page. Any other next keeps its bytes as they came, because only the + /// server reads them. + static func page<Item: Sendable & Hashable>(_ body: ArraySlice<UInt8>, item: (inout ByteReader) throws -> Item) throws -> Page<Item> { + try decode(body) { reader in + let nextLength = Int(try reader.readUInt8()) + let next = PageCursor(bytes: Array(try reader.readBytes(nextLength))) + let count = try reader.readCount() + var items: [Item] = [] + // A server sends at most maxLimit items, so a larger count does + // not size the allocation. + items.reserveCapacity(min(count, Int(PageQuery.maxLimit))) + for _ in 0..<count { + items.append(try item(&reader)) + } + guard reader.isAtEnd else { + throw WireError.validation("\(reader.remaining) trailing bytes after a page") + } + return Page(items: items, next: next) + } + } + // MARK: Metadata changes /// Decodes a `GetMetadataChanges` reply:
diff --git a/foreign/swift/Tests/IggyE2ETests/ListPagesE2ETests.swift b/foreign/swift/Tests/IggyE2ETests/ListPagesE2ETests.swift new file mode 100644 index 0000000..a8f5a66 --- /dev/null +++ b/foreign/swift/Tests/IggyE2ETests/ListPagesE2ETests.swift
@@ -0,0 +1,127 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import Iggy +import Testing + +/// List pages against a live server. Other suites run on the same server, so +/// every check filters by the names of this test and walks until the last +/// page instead of counting pages. +@Suite("List pages", requiresServer) +struct ListPagesE2ETests { + /// Cursor texts of `core/common/fixtures/list_pages.json`. Both texts are + /// valid, so only the server can refuse them. + static let idSevenCursor = "pg1_AQcAAAAAAAAA" + static let unknownKindCursor = "pg1_AwcAAAAAAAAA" + + @Test func givenThreeStreamsWhenReadingPagesOfTwoShouldReturnEachOnceInTheOrderAsked() async throws { + try await E2EEnvironment.withSession { session in + let client = session.client + let prefix = E2EEnvironment.uniqueName("swift-pages") + var created: [StreamDetails] = [] + for suffix in ["a", "b", "c"] { + let name = "\(prefix)-\(suffix)" + await session.track(stream: try Identifier(named: name)) + created.append(try await client.createStream(name: name)) + } + // A create takes the lowest free id, so a delete of another test + // can give a later stream a lower id. + let ascending = created.map(\.id).sorted() + let byCreation = created.sorted { ($0.createdAt, $0.id) < ($1.createdAt, $1.id) }.map(\.id) + let walks: [(order: PageOrder, descending: Bool, expected: [UInt32])] = [ + (.id, false, ascending), (.id, true, ascending.reversed()), (.created, false, byCreation), + ] + for walk in walks { + let query = PageQuery(order: walk.order, descending: walk.descending, limit: 2) + let streams = try await Self.walk(query) { try await client.getStreamsPage(NamedPageQuery(page: $0, name: prefix)) } + #expect(streams.map(\.id) == walk.expected, "\(walk.order), descending \(walk.descending)") + } + let listed = Set(try await client.getStreams().map(\.id)) + #expect(Set(created.map(\.id)).isSubset(of: listed)) + } + } + + @Test func givenTopicWithThreePartitionsWhenReadingPagesOfTwoShouldReturnEachPartitionOnce() async throws { + try await E2EEnvironment.withSession { session in + let scratch = try await session.scratchTopic(partitions: 3) + let partitions = try await Self.walk(PageQuery(limit: 2)) { + try await session.client.getPartitionsPage(streamID: scratch.stream, topicID: scratch.topic, query: $0) + } + #expect(partitions.map(\.id) == [0, 1, 2]) + } + } + + @Test func givenTopicGroupAndUserWhenFilteringByNameShouldReturnOnlyTheMatch() async throws { + try await E2EEnvironment.withSession { session in + let client = session.client + let scratch = try await session.scratchTopic(partitions: 1) + let topic = try await client.createTopic(streamID: scratch.stream, name: "sensor-readings", options: TopicCreateOptions(partitionsCount: 1)) + let group = try await client.createConsumerGroup(streamID: scratch.stream, topicID: scratch.topic, name: "billing") + _ = try await client.createConsumerGroup(streamID: scratch.stream, topicID: scratch.topic, name: "audit") + + let topics = try await Self.walk(PageQuery()) { + try await client.getTopicsPage(streamID: scratch.stream, query: NamedPageQuery(page: $0, name: "sensor")) + } + #expect(topics.map(\.id) == [topic.id]) + let groups = try await Self.walk(PageQuery()) { + try await client.getConsumerGroupsPage(streamID: scratch.stream, topicID: scratch.topic, query: NamedPageQuery(page: $0, name: "bill")) + } + #expect(groups.map(\.id) == [group.id]) + + let username = String(E2EEnvironment.uniqueName("swift-pages-user").prefix(50)) + let user = try await client.createUser(username: username, password: "pages-secret") + do { + let users = try await Self.walk(PageQuery()) { try await client.getUsersPage(NamedPageQuery(page: $0, name: username)) } + #expect(users.map(\.id) == [user.id]) + } catch { + try? await client.deleteUser(Identifier(numeric: user.id)) + throw error + } + try await client.deleteUser(Identifier(numeric: user.id)) + } + } + + @Test func givenPagesTheServerCannotServeWhenReadingShouldRefuseThemAsInvalidCommand() async throws { + try await E2EEnvironment.withSession { session in + let client = session.client + let scratch = try await session.scratchTopic(partitions: 1) + let unknownKind = try PageCursor(text: Self.unknownKindCursor) + await expectIggyError(.invalidCommand) { _ = try await client.getStreamsPage(NamedPageQuery(page: PageQuery(cursor: unknownKind))) } + let idCursor = try PageCursor(text: Self.idSevenCursor) + await expectIggyError(.invalidCommand) { _ = try await client.getStreamsPage(NamedPageQuery(page: PageQuery(order: .created, cursor: idCursor))) } + // The refusals keep the session. + #expect(try await client.getPartitionsPage(streamID: scratch.stream, topicID: scratch.topic).items.map(\.id) == [0]) + #expect(await client.state == .authenticated) + } + } + + /// Reads pages from `first` until a page has no next cursor. No page holds + /// more items than the limit of the query. + static func walk<Item: Sendable & Hashable>(_ first: PageQuery, _ readPage: (PageQuery) async throws -> Page<Item>) async throws -> [Item] { + var query = first + var items: [Item] = [] + while true { + let page = try await readPage(query) + #expect(page.items.count <= Int(query.limit)) + items += page.items + guard let next = page.next else { + return items + } + query.cursor = next + } + } +}
diff --git a/foreign/swift/Tests/IggyTests/ErrorCodeTests.swift b/foreign/swift/Tests/IggyTests/ErrorCodeTests.swift index 37b8122..fc6d2bb 100644 --- a/foreign/swift/Tests/IggyTests/ErrorCodeTests.swift +++ b/foreign/swift/Tests/IggyTests/ErrorCodeTests.swift
@@ -31,6 +31,9 @@ #expect(IggyErrorCode(rawValue: 96) == .tieredReadFailed) #expect(IggyErrorCode.tieredReadFailed.name == "tiered_read_failed") #expect(IggyError(wireCode: 96).code == .tieredReadFailed) + #expect(IggyErrorCode(rawValue: 97) == .replyTooLarge) + #expect(IggyErrorCode.replyTooLarge.name == "reply_too_large") + #expect(IggyError(wireCode: 97).code == .replyTooLarge) #expect(IggyErrorCode(rawValue: 1009) == .streamIdNotFound) #expect(IggyErrorCode(rawValue: 2010) == .topicIdNotFound) #expect(IggyErrorCode(rawValue: 2022) == .partitionsLimitReached)
diff --git a/foreign/swift/Tests/IggyTests/Fixtures/golden.json b/foreign/swift/Tests/IggyTests/Fixtures/golden.json index 7c781d5..ef2dad7 100644 --- a/foreign/swift/Tests/IggyTests/Fixtures/golden.json +++ b/foreign/swift/Tests/IggyTests/Fixtures/golden.json
@@ -1,6 +1,6 @@ { - "protocol_version": 12290, - "protocol_version_min": 12290, + "protocol_version": 12291, + "protocol_version_min": 12291, "no_assigned_partition": 4294967294, "resync_required_partition": 4294967295, "xxh3_64": { @@ -723,6 +723,7 @@ "94": "producer_unknown", "95": "producer_partition_required", "96": "tiered_read_failed", + "97": "reply_too_large", "100": "client_not_found", "101": "invalid_client_id", "206": "connection_closed", @@ -936,7 +937,7 @@ "polling.next": "050000000000000000", "polling.offset.100": "016400000000000000", "polling.timestamp.1700000000000": "020068e5cf8b010000", - "request.bind_session": "023000000973776966742d73646b05302e322e3001000000000000000000000000000000640000000000000078000000000000005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a", + "request.bind_session": "033000000973776966742d73646b0c302e322e312d656467652e3101000000000000000000000000000000640000000000000078000000000000005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a", "request.change_password": "010401000000086f6c642d706173730c6e65772d706173732d313233", "request.create_consumer_group": "01040100000001040200000003677270", "request.create_partitions": "01040100000001040200000005000000", @@ -961,24 +962,25 @@ "request.get_clients": "", "request.get_cluster_metadata": "", "request.get_consumer_group": "020873747265616d2d310207746f7069632d31020767726f75702d31", - "request.get_consumer_groups": "010401000000010402000000", + "request.get_consumer_groups": "0104010000000104020000000000640000000000", "request.get_consumer_offset": "01020b6d792d636f6e73756d6572020873747265616d2d310207746f7069632d310100000000", "request.get_me": "", "request.get_metadata_changes": "02d7931c6e2a8f4b0d00000000000000005b1000000000000059f3d1b0e8c6a4f20000000000000000010000000100f0bd010941060000f40100000202010000", "request.get_partition_route": "01040a00000002066f726465727305000000", + "request.get_partitions": "020673747265616d0205746f7069630001e80300000901020000000000000000", "request.get_personal_access_tokens": "", "request.get_snapshot": "02020105", "request.get_stats": "", "request.get_stream": "02096d792d73747265616d", - "request.get_streams": "", + "request.get_streams": "0000640000000000", "request.get_topic": "02096d792d73747265616d02086d792d746f706963", - "request.get_topics": "01042a000000", + "request.get_topics": "01042a000000010114000000110200e090663c1306000700000000000000036f7264", "request.get_user": "01042a000000", - "request.get_users": "", + "request.get_users": "0000e80300000000", "request.join_consumer_group": "010401000000010402000000010403000000", "request.leave_consumer_group": "010401000000010402000000020167", - "request.login_register": "023000000973776966742d73646b05302e322e305a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a0469676779046967677900000000", - "request.login_register_with_pat": "023000000973776966742d73646b05302e322e305a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a107061742d61626331323364656634353600000000", + "request.login_register": "033000000973776966742d73646b0c302e322e312d656467652e315a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a0469676779046967677900000000", + "request.login_register_with_pat": "033000000973776966742d73646b0c302e322e312d656467652e315a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a107061742d61626331323364656634353600000000", "request.logout_user": "", "request.ping": "", "request.poll_messages": "0101040100000001040a00000001041400000001050000000164000000000000003200000001", @@ -1006,17 +1008,18 @@ "response.describe_options": "040000000c7365676d656e745f73697a650c000800000000000040000000000c0000005365676d656e742073697a650a6475726162696c69747902000a0000007265706c696361746564000000000e6d6573736167655f6578706972790c0308000000ffffffffffffffff000000000e656e6372797074696f6e5f6b657901140000000000000000", "response.fetch_messages": "020000000100000000000000290000000000000001000000030000000000000009000000000000000c000000000000002a000000000000003501000002000000590000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000290000000000000064401e18240a060000401e18240a06003501000000000000bd2d787d3cdb745c010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008e5ca59edbbdbfb90100000000000000000000000000000000000000000000000000000005000000000000000000000068656c6c6f", "response.get_clients": "010000000a000000010e0000003132372e302e302e313a38303830020000000200000014000000020d00000031302e302e302e313a3630303003000000", - "response.get_consumer_groups": "0100000004000000020000000767726f75702d610200000004000000000000000767726f75702d62", + "response.get_consumer_groups": "00020000000100000004000000020000000767726f75702d610200000004000000000000000767726f75702d62", "response.get_metadata_changes": "000001d7931c6e2a8f4b0d00000000000000001f0f00000000000000000000000000005e1000000000000001d7931c6e2a8f4b0d00000000000000005b1000000000000059f3d1b0e8c6a4f20000000000000000010000000001000000191000000000000000000000653d9e8b03f7c1a500000000000000001900be0109410600010000000001012700000003000000191000000000000040d2bf01094106000974656c656d65747279000000000000000000000000000000", + "response.get_partitions": "09010200000000000000030000000000000000e090663c13060002000000630000000000000000040000000000006400000000000000000000000000000000000000000000000000000000000000030001020200010100000001e090663c1306000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003010200000200000002e090663c13060003000000070000000000000000020000000000000800000000000000000000000000000000000000000000000000000000000000030200010102", "response.get_personal_access_tokens": "07746f6b656e2d6100e090663c13060007746f6b656e2d620000000000000000", "response.get_stream": "0100000000e090663c130600020000000008000000000000c800000000000000096d792d73747265616d000000009e000000021a000000656e6372797074696f6e5f6b656b5f66696e6765727072696e740221000000333965346630663935633336393363372c64353564343739383239626332393336021a000000656e6372797074696f6e5f6b65795f66696e6765727072696e740210000000383434316533383533386362666135370215000000656e6372797074696f6e5f6b65795f736f75726365020600000073747265616d0100000000e090663c130600030000000010000000000000640000000000000007746f7069632d615b000000020a0000006475726162696c6974790209000000706572736973746564020e0000006d6573736167655f6578706972790c0800000000a0e3d08c000000020c0000007365676d656e745f73697a650c080000000000004000000000430000000215000000636f6d7072657373696f6e5f616c676f726974686d02040000006e6f6e65020e0000006d61785f746f7069635f73697a650c08000000ffffffffffffffff0200000000e090663c130600030000000010000000000000640000000000000007746f7069632d625b000000020a0000006475726162696c6974790209000000706572736973746564020e0000006d6573736167655f6578706972790c0800000000a0e3d08c000000020c0000007365676d656e745f73697a650c080000000000004000000000430000000215000000636f6d7072657373696f6e5f616c676f726974686d02040000006e6f6e65020e0000006d61785f746f7069635f73697a650c08000000ffffffffffffffff", - "response.get_streams": "0100000000e090663c130600020000000008000000000000c800000000000000096d792d73747265616d000000009e000000021a000000656e6372797074696f6e5f6b656b5f66696e6765727072696e740221000000333965346630663935633336393363372c64353564343739383239626332393336021a000000656e6372797074696f6e5f6b65795f66696e6765727072696e740210000000383434316533383533386362666135370215000000656e6372797074696f6e5f6b65795f736f75726365020600000073747265616d0200000000e090663c130600000000000008000000000000c800000000000000096d792d73747265616d000000009e000000021a000000656e6372797074696f6e5f6b656b5f66696e6765727072696e740221000000333965346630663935633336393363372c64353564343739383239626332393336021a000000656e6372797074696f6e5f6b65795f66696e6765727072696e740210000000383434316533383533386362666135370215000000656e6372797074696f6e5f6b65795f736f75726365020600000073747265616d", + "response.get_streams": "09010200000000000000020000000100000000e090663c130600020000000008000000000000c800000000000000096d792d73747265616d000000009e000000021a000000656e6372797074696f6e5f6b656b5f66696e6765727072696e740221000000333965346630663935633336393363372c64353564343739383239626332393336021a000000656e6372797074696f6e5f6b65795f66696e6765727072696e740210000000383434316533383533386362666135370215000000656e6372797074696f6e5f6b65795f736f75726365020600000073747265616d0200000000e090663c130600000000000008000000000000c800000000000000096d792d73747265616d000000009e000000021a000000656e6372797074696f6e5f6b656b5f66696e6765727072696e740221000000333965346630663935633336393363372c64353564343739383239626332393336021a000000656e6372797074696f6e5f6b65795f66696e6765727072696e740210000000383434316533383533386362666135370215000000656e6372797074696f6e5f6b65795f736f75726365020600000073747265616d", "response.get_topic": "0100000000e090663c1306000300000000100000000000006400000000000000086d792d746f7069635b000000020a0000006475726162696c6974790209000000706572736973746564020e0000006d6573736167655f6578706972790c0800000000a0e3d08c000000020c0000007365676d656e745f73697a650c080000000000004000000000430000000215000000636f6d7072657373696f6e5f616c676f726974686d02040000006e6f6e65020e0000006d61785f746f7069635f73697a650c08000000ffffffffffffffff0000000000e090663c13060002000000630000000000000000040000000000006400000000000000000000000000000000000000000000000000000000000000030001020200010100000001e090663c1306000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003010200000200000002e090663c13060003000000070000000000000000020000000000000800000000000000000000000000000000000000000000000000000000000000030200010102", - "response.get_topics": "020000000100000000e090663c1306000300000000100000000000006400000000000000066576656e74735b000000020a0000006475726162696c6974790209000000706572736973746564020e0000006d6573736167655f6578706972790c0800000000a0e3d08c000000020c0000007365676d656e745f73697a650c080000000000004000000000430000000215000000636f6d7072657373696f6e5f616c676f726974686d02040000006e6f6e65020e0000006d61785f746f7069635f73697a650c08000000ffffffffffffffff0200000000e090663c1306000300000000100000000000006400000000000000046c6f67735b000000020a0000006475726162696c6974790209000000706572736973746564020e0000006d6573736167655f6578706972790c0800000000a0e3d08c000000020c0000007365676d656e745f73697a650c080000000000004000000000430000000215000000636f6d7072657373696f6e5f616c676f726974686d02040000006e6f6e65020e0000006d61785f746f7069635f73697a650c08000000ffffffffffffffff", - "response.get_topics.empty": "00000000", - "response.get_users": "0100000000e090663c130600010561646d696e000000000000000002000000c8000000000000000205616c6963650000000000000000", + "response.get_topics": "110200e090663c1306000200000000000000020000000100000000e090663c1306000300000000100000000000006400000000000000066576656e74735b000000020a0000006475726162696c6974790209000000706572736973746564020e0000006d6573736167655f6578706972790c0800000000a0e3d08c000000020c0000007365676d656e745f73697a650c080000000000004000000000430000000215000000636f6d7072657373696f6e5f616c676f726974686d02040000006e6f6e65020e0000006d61785f746f7069635f73697a650c08000000ffffffffffffffff0200000000e090663c1306000300000000100000000000006400000000000000046c6f67735b000000020a0000006475726162696c6974790209000000706572736973746564020e0000006d6573736167655f6578706972790c0800000000a0e3d08c000000020c0000007365676d656e745f73697a650c080000000000004000000000430000000215000000636f6d7072657373696f6e5f616c676f726974686d02040000006e6f6e65020e0000006d61785f746f7069635f73697a650c08000000ffffffffffffffff", + "response.get_topics.empty": "0000000000", + "response.get_users": "00020000000100000000e090663c130600010561646d696e000000000000000002000000c8000000000000000205616c6963650000000000000000", "response.identity": "2a000000", - "response.login_register": "2a00000064000000000000000230000006302e31312e30", + "response.login_register": "2a00000064000000000000000330000006302e31312e30", "response.partition_route": "07000000000000000a00000000000000030000000400000002", "response.poll_messages": "07000000660000000000000003000000000000000000000000000000000000000000000000000000070000000000000064000000000000008813000000000000e8030000000000006e01000000000000f576a2492e1328b302000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000fa7fe16d19356ec20b00000000000000000000000000000000000000000000000000000001000000000000000000000061b7f159184e9d8ac20c000000000000000000000000000000010000000a0000000c0000000100000000000000000000006202010000006b020100000076070000000000000066000000000000007017000000000000d00700000000000031010000000000006739773bc7d38608010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009377fb7d5180f51e0d00000000000000000000000000000000000000000000000000000001000000000000000000000063", "response.poll_messages.empty": "00000000000000000000000000000000000000000000000000000000000000000000000000000000", @@ -1033,8 +1036,8 @@ "response.user_details.no_permissions": "0100000000e090663c130600010561646d696e000000000000000000000000", "stream_key.fingerprint": "8441e38538cbfa57", "user_headers.sample": "0207000000617474656d70740b0400000003000000020800000074726163652d69640203000000616263", - "version_info": "023000000973776966742d73646b05302e322e30", - "vsr.eviction.incompatible_protocol": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001032547698badcfeefcdab89674523010230000002300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e", + "version_info": "033000000973776966742d73646b0c302e322e312d656467652e31", + "vsr.eviction.incompatible_protocol": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001032547698badcfeefcdab89674523010330000003300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e", "vsr.eviction.stale_client": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001032547698badcfeefcdab89674523010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d", "vsr.reply.committed": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0100000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001032547698badcfeefcdab896745230100000000000000000c0000000000000000000000000000000700000000000000800000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000", "vsr.reply.denied": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000020000000000000029000000000000000000000000000000000000000000000000000000000000000000000000000000",
diff --git a/foreign/swift/Tests/IggyTests/Fixtures/list_pages.json b/foreign/swift/Tests/IggyTests/Fixtures/list_pages.json new file mode 100644 index 0000000..4c97b84 --- /dev/null +++ b/foreign/swift/Tests/IggyTests/Fixtures/list_pages.json
@@ -0,0 +1,781 @@ +{ + "schema_version": 1, + "generated_by": "core/common/examples/list_pages_fixtures.rs", + "conventions": { + "cursor_text": "A cursor text is cursor_prefix and then the cursor bytes as unpadded Base64url. The unused bits of the last character are zero. A client refuses a text that does not encode back to the same text, and a text of 0 bytes or of more than max_cursor_bytes bytes.", + "errors": "The server answers invalid_command to a page block that it cannot read or serve. Examples are a cursor of an unknown kind or length, a cursor whose kind does not fit the order, and a name filter on GetPartitions. reply_too_large is new in this protocol version. The server answers it in place of a GetClients reply, or of a reply to a read of streams, topics, partitions, consumer groups, users, tokens, options, stats or cluster metadata, whose frame is above the reply size cap. A page reply stays far below that cap.", + "hex": "Every *_hex field is lowercase hex without separators. request_hex is the command payload without framing, and response_hex is the reply payload.", + "http_query": "http_query holds the page keys and their text values that a client sends to the HTTP list route. A request with limit or cursor gets one page. A request without both gets the whole list as a bare JSON array, in the order of its order and descending keys and filtered by its name key. The partitions route always answers a page.", + "identifiers": "stream_id and topic_id are {kind, value}: kind numeric with a u32 value, or kind named with a string value. They are null for a command that has no such field.", + "items": "items hold the id and the name of each item of the page, in reply order. A partition has no name.", + "name": "A name is UTF-8 text of 1 to max_name_bytes bytes. Its length on the wire counts bytes, not characters. GetPartitions has no name filter, so its query has no name and its page block has a name length of 0. The server refuses a GetPartitions page block with a name.", + "next": "A client sends the next of a page as the cursor of the next request, with the same other fields. A page can be empty and still have a next. A walk ends at the first page without a next.", + "opaque_cursors": "A client that encodes the wire format itself does not read the bytes of a cursor. It keeps the bytes of every opaque_cursors entry and of every opaque_responses next. It sends them as it got them, and the server refuses them with invalid_command. The Rust SDK and the SDKs that wrap it read the bytes, so they refuse these cursors and replies.", + "refused": "A client refuses every text of refused.cursors, every input of refused.queries before it sends a request, and every body of refused.responses. An input with a name is a query of a list with a name filter.", + "walk": "Over TCP, QUIC and WebSocket, a list method that returns a whole list walks the pages with order id, ascending and limit max_limit. Over HTTP, it reads the route without limit and cursor, which answers the whole list as a bare JSON array." + }, + "constants": { + "codes": { + "get_consumer_groups": 601, + "get_partitions": 404, + "get_streams": 201, + "get_topics": 301, + "get_users": 32 + }, + "orders": { + "created": 1, + "id": 0 + }, + "cursor_prefix": "pg1_", + "max_cursor_bytes": 255, + "default_limit": 100, + "max_limit": 1000, + "max_name_bytes": 255, + "errors": { + "invalid_command": 3, + "reply_too_large": 97 + } + }, + "cursors": [ + { + "case": "id_seven", + "text": "pg1_AQcAAAAAAAAA", + "hex": "010700000000000000" + }, + { + "case": "id_distinct_bytes", + "text": "pg1_AQECAwQFBgcI", + "hex": "010102030405060708" + }, + { + "case": "id_url_safe_characters", + "text": "pg1_AQD_-AAAAAAA", + "hex": "0100fff80000000000" + }, + { + "case": "created_distinct_bytes", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg", + "hex": "0211121314151617182122232425262728" + } + ], + "opaque_cursors": [ + { + "case": "kind_zero", + "text": "pg1_AAcAAAAAAAAA", + "hex": "000700000000000000" + }, + { + "case": "unknown_kind", + "text": "pg1_AwcAAAAAAAAA", + "hex": "030700000000000000" + }, + { + "case": "created_kind_with_the_id_length", + "text": "pg1_AgcAAAAAAAAA", + "hex": "020700000000000000" + }, + { + "case": "id_kind_with_the_created_length", + "text": "pg1_ARESExQVFhcYISIjJCUmJyg", + "hex": "0111121314151617182122232425262728" + }, + { + "case": "one_byte", + "text": "pg1_AQ", + "hex": "01" + }, + { + "case": "most_bytes", + "text": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "hex": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" + } + ], + "requests": [ + { + "case": "streams_first_page", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_whole_list_walk", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1000, + "cursor": null, + "name": null + }, + "request_hex": "0000e80300000000", + "http_query": { + "descending": "false", + "limit": "1000", + "order": "id" + } + }, + { + "case": "streams_created_descending_one_item", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 1, + "cursor": null, + "name": null + }, + "request_hex": "0101010000000000", + "http_query": { + "descending": "true", + "limit": "1", + "order": "created" + } + }, + { + "case": "streams_after_id_cursor", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": "pg1_AQECAwQFBgcI", + "name": null + }, + "request_hex": "0000640000000901010203040506070800", + "http_query": { + "cursor": "pg1_AQECAwQFBgcI", + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "streams_created_after_cursor_with_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 20, + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "name": "ord" + }, + "request_hex": "010114000000110211121314151617182122232425262728036f7264", + "http_query": { + "cursor": "pg1_AhESExQVFhcYISIjJCUmJyg", + "descending": "true", + "limit": "20", + "name": "ord", + "order": "created" + } + }, + { + "case": "streams_multi_byte_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "café-注文-📦" + }, + "request_hex": "0000640000000011636166c3a92de6b3a8e696872df09f93a6", + "http_query": { + "descending": "false", + "limit": "100", + "name": "café-注文-📦", + "order": "id" + } + }, + { + "case": "streams_longest_name", + "command": "get_streams", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa" + }, + "request_hex": "00006400000000ffc3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a9c3a961", + "http_query": { + "descending": "false", + "limit": "100", + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééa", + "order": "id" + } + }, + { + "case": "users_first_page", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "users_created_after_cursor_with_name", + "command": "get_users", + "input": { + "stream_id": null, + "topic_id": null, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "name": "adm" + }, + "request_hex": "010064000000110200e090663c13060001000000000000000361646d", + "http_query": { + "cursor": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "descending": "false", + "limit": "100", + "name": "adm", + "order": "created" + } + }, + { + "case": "topics_numeric_stream_first_page", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "topics_named_stream_created_descending_with_name", + "command": "get_topics", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": null, + "order": "created", + "descending": true, + "limit": 50, + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "name": "sens" + }, + "request_hex": "02066f7264657273010132000000110209e090663c13060003000000000000000473656e73", + "http_query": { + "cursor": "pg1_AgngkGY8EwYAAwAAAAAAAAA", + "descending": "true", + "limit": "50", + "name": "sens", + "order": "created" + } + }, + { + "case": "partitions_numeric_ids_first_page", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "partitions_named_ids_descending_after_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 1000, + "cursor": "pg1_AecDAAAAAAAA", + "name": null + }, + "request_hex": "02066f726465727302066576656e74730001e80300000901e70300000000000000", + "http_query": { + "cursor": "pg1_AecDAAAAAAAA", + "descending": "true", + "limit": "1000", + "order": "id" + } + }, + { + "case": "partitions_created_order_after_id_cursor", + "command": "get_partitions", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "created", + "descending": false, + "limit": 100, + "cursor": "pg1_AQcAAAAAAAAA", + "name": null + }, + "request_hex": "0104070000000104030000000100640000000901070000000000000000", + "http_query": { + "cursor": "pg1_AQcAAAAAAAAA", + "descending": "false", + "limit": "100", + "order": "created" + } + }, + { + "case": "consumer_groups_numeric_ids_first_page", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "numeric", + "value": 7 + }, + "topic_id": { + "kind": "numeric", + "value": 3 + }, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": null + }, + "request_hex": "0104070000000104030000000000640000000000", + "http_query": { + "descending": "false", + "limit": "100", + "order": "id" + } + }, + { + "case": "consumer_groups_named_ids_descending_with_name", + "command": "get_consumer_groups", + "input": { + "stream_id": { + "kind": "named", + "value": "orders" + }, + "topic_id": { + "kind": "named", + "value": "events" + }, + "order": "id", + "descending": true, + "limit": 100, + "cursor": "pg1_AQMAAAAAAAAA", + "name": "bill" + }, + "request_hex": "02066f726465727302066576656e7473000164000000090103000000000000000462696c6c", + "http_query": { + "cursor": "pg1_AQMAAAAAAAAA", + "descending": "true", + "limit": "100", + "name": "bill", + "order": "id" + } + } + ], + "responses": [ + { + "case": "streams_with_next", + "command": "get_streams", + "response_hex": "09010400000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQQAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_created_order_with_next", + "command": "get_streams", + "response_hex": "110205e090663c1306000100000000000000020000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d657500000000000000000100000005e090663c1306000200000000100000000000006400000000000000066f72646572730000000000000000", + "next": "pg1_AgXgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 4, + "name": "payments-eu" + }, + { + "id": 1, + "name": "orders" + } + ] + }, + { + "case": "streams_empty_with_next", + "command": "get_streams", + "response_hex": "0901e80300000000000000000000", + "next": "pg1_AegDAAAAAAAA", + "items": [] + }, + { + "case": "streams_empty_last_page", + "command": "get_streams", + "response_hex": "0000000000", + "next": null, + "items": [] + }, + { + "case": "topics_last_page", + "command": "get_topics", + "response_hex": "00020000000100000000e090663c1306000300000000080000000000003200000000000000066576656e747300000000000000000200000000e090663c13060003000000000800000000000032000000000000000f73656e736f722d72656164696e67730000000000000000", + "next": null, + "items": [ + { + "id": 1, + "name": "events" + }, + { + "id": 2, + "name": "sensor-readings" + } + ] + }, + { + "case": "topics_created_descending_with_next", + "command": "get_topics", + "response_hex": "110200e090663c1306000100000000000000020000000300000009e090663c130600030000000008000000000000320000000000000005617564697400000000000000000100000000e090663c1306000300000000080000000000003200000000000000066576656e74730000000000000000", + "next": "pg1_AgDgkGY8EwYAAQAAAAAAAAA", + "items": [ + { + "id": 3, + "name": "audit" + }, + { + "id": 1, + "name": "events" + } + ] + }, + { + "case": "partitions_with_next", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000010100", + "next": "pg1_AQEAAAAAAAAA", + "items": [ + { + "id": 0, + "name": null + }, + { + "id": 1, + "name": null + } + ] + }, + { + "case": "partitions_descending_last_page", + "command": "get_partitions", + "response_hex": "00020000000100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000003000102020001", + "next": null, + "items": [ + { + "id": 1, + "name": null + }, + { + "id": 0, + "name": null + } + ] + }, + { + "case": "consumer_groups_with_next", + "command": "get_consumer_groups", + "response_hex": "09010300000000000000020000000100000003000000010000000762696c6c696e670300000003000000010000000c616e616c79746963732d6575", + "next": "pg1_AQMAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "billing" + }, + { + "id": 3, + "name": "analytics-eu" + } + ] + }, + { + "case": "users_with_next", + "command": "get_users", + "response_hex": "09010200000000000000020000000100000000e090663c13060001046967677900000000000000000200000001e090663c1306000109616c6963652d6f70730000000000000000", + "next": "pg1_AQIAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "iggy" + }, + { + "id": 2, + "name": "alice-ops" + } + ] + }, + { + "case": "users_created_descending_last_page", + "command": "get_users", + "response_hex": "00020000000200000001e090663c1306000109616c6963652d6f707300000000000000000100000000e090663c1306000104696767790000000000000000", + "next": null, + "items": [ + { + "id": 2, + "name": "alice-ops" + }, + { + "id": 1, + "name": "iggy" + } + ] + } + ], + "opaque_responses": [ + { + "case": "streams_with_unknown_cursor_kind", + "command": "get_streams", + "response_hex": "09030700000000000000020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AwcAAAAAAAAA", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + }, + { + "case": "streams_with_most_cursor_bytes", + "command": "get_streams", + "response_hex": "ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff020000000100000005e090663c1306000200000000100000000000006400000000000000066f726465727300000000000000000400000000e090663c13060002000000001000000000000064000000000000000b7061796d656e74732d65750000000000000000", + "next": "pg1_AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4_QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1-f4CBgoOEhYaHiImKi4yNjo-QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr_AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3-Dh4uPk5ebn6Onq6-zt7u_w8fLz9PX29_j5-vv8_f7_", + "items": [ + { + "id": 1, + "name": "orders" + }, + { + "id": 4, + "name": "payments-eu" + } + ] + } + ], + "refused": { + "cursors": [ + { + "case": "empty", + "text": "" + }, + { + "case": "missing_prefix", + "text": "AQcAAAAAAAAA" + }, + { + "case": "other_prefix", + "text": "mc1_AQcAAAAAAAAA" + }, + { + "case": "later_version_prefix", + "text": "pg2_AQcAAAAAAAAA" + }, + { + "case": "upper_case_prefix", + "text": "PG1_AQcAAAAAAAAA" + }, + { + "case": "padded", + "text": "pg1_AhESExQVFhcYISIjJCUmJyg=" + }, + { + "case": "standard_alphabet", + "text": "pg1_AQD/+AAAAAAA" + }, + { + "case": "character_outside_the_alphabet", + "text": "pg1_AQcAAAAAAAA*" + }, + { + "case": "trailing_newline", + "text": "pg1_AQcAAAAAAAAA\n" + }, + { + "case": "unused_bit_set", + "text": "pg1_AgkAAAAAAAAAAwAAAAAAAAB" + }, + { + "case": "no_bytes", + "text": "pg1_" + }, + { + "case": "more_than_max_cursor_bytes", + "text": "pg1_WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWg" + } + ], + "queries": [ + { + "case": "limit_zero", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 0, + "cursor": null, + "name": null + } + }, + { + "case": "limit_above_max_limit", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 1001, + "cursor": null, + "name": null + } + }, + { + "case": "empty_name", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "" + } + }, + { + "case": "name_above_max_name_bytes", + "input": { + "stream_id": null, + "topic_id": null, + "order": "id", + "descending": false, + "limit": 100, + "cursor": null, + "name": "éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé" + } + } + ], + "responses": [ + { + "case": "empty_body", + "command": "get_streams", + "response_hex": "" + }, + { + "case": "truncated_count", + "command": "get_topics", + "response_hex": "000200" + }, + { + "case": "truncated_next", + "command": "get_users", + "response_hex": "110211121314" + }, + { + "case": "count_above_items", + "command": "get_consumer_groups", + "response_hex": "00020000000100000003000000010000000762696c6c696e67" + }, + { + "case": "count_of_u32_max", + "command": "get_consumer_groups", + "response_hex": "00ffffffff0100000003000000010000000762696c6c696e67" + }, + { + "case": "truncated_item", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a000000000000000101" + }, + { + "case": "trailing_bytes", + "command": "get_partitions", + "response_hex": "09010100000000000000020000000000000000e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a00000000000000030001020200010100000001e090663c13060001000000630000000000000000040000000000006400000000000000010000000000000000000000000000002a0000000000000001010000" + } + ] + } +}
diff --git a/foreign/swift/Tests/IggyTests/Fixtures/resource_options.json b/foreign/swift/Tests/IggyTests/Fixtures/resource_options.json index 8a2e7d1..ccda484 100644 --- a/foreign/swift/Tests/IggyTests/Fixtures/resource_options.json +++ b/foreign/swift/Tests/IggyTests/Fixtures/resource_options.json
@@ -16,18 +16,18 @@ }, "constants": { "protocol_version": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "protocol_version_min": { - "packed": 12290, - "text": "0.12.2", + "packed": 12291, + "text": "0.12.3", "major": 0, "minor": 12, - "patch": 2 + "patch": 3 }, "command_codes": { "create_stream": {
diff --git a/foreign/swift/Tests/IggyTests/ListPagesTests.swift b/foreign/swift/Tests/IggyTests/ListPagesTests.swift new file mode 100644 index 0000000..6063779 --- /dev/null +++ b/foreign/swift/Tests/IggyTests/ListPagesTests.swift
@@ -0,0 +1,440 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import Testing + +@testable import Iggy + +/// The list page contract that every SDK shares, checked against +/// `Fixtures/list_pages.json` from the Rust codecs. This SDK has no HTTP +/// transport, so `http_query` is left out. +@Suite("List pages match the shared fixture") +struct ListPagesFixtureTests { + let fixture = ListPagesFixture.shared + + @Test func givenFixtureWhenLoadingShouldHoldEveryVectorGroupForEveryCommand() { + #expect(fixture.schemaVersion == 1) + let groups = [ + fixture.cursors.count, fixture.opaqueCursors.count, fixture.requests.count, fixture.responses.count, fixture.opaqueResponses.count, + fixture.refused.cursors.count, fixture.refused.queries.count, fixture.refused.responses.count, + ] + #expect(groups.allSatisfy { $0 > 0 }, "\(groups)") + #expect(Set(fixture.requests.map(\.command)) == Set(listCommands.keys)) + #expect(Set(fixture.responses.map(\.command)) == Set(listCommands.keys)) + } + + @Test func givenFixtureConstantsWhenComparingPublicTypesShouldMatchCodesOrdersAndLimits() { + let constants = fixture.constants + #expect(constants.codes == listCommands.mapValues(\.rawValue)) + for (name, code) in constants.codes { + #expect(ConsensusOperation.forCode(code) == .nonReplicated, "\(name)") + } + #expect(constants.orders == pageOrders.mapValues(\.rawValue)) + #expect(Set(pageOrders.values) == Set(PageOrder.allCases)) + #expect(PageCursor.textPrefix == constants.cursorPrefix) + #expect(PageCursor.maxSize == constants.maxCursorBytes) + #expect(PageQuery.defaultLimit == constants.defaultLimit) + #expect(PageQuery().limit == constants.defaultLimit) + #expect(PageQuery.maxLimit == constants.maxLimit) + #expect(NamedPageQuery.maxNameSize == constants.maxNameBytes) + let errors = ["invalid_command": IggyErrorCode.invalidCommand, "reply_too_large": .replyTooLarge] + #expect(constants.errors == errors.mapValues(\.rawValue)) + #expect(errors.allSatisfy { $0.key == $0.value.name }) + } + + /// The client checks only the text of a cursor, so the opaque cursors that + /// the server refuses parse too. + @Test func givenCursorVectorsWhenParsingShouldKeepTheirBytesAndText() throws { + for vector in fixture.cursors + fixture.opaqueCursors { + let cursor = try PageCursor(text: vector.text) + #expect(cursor.description == vector.text, "\(vector.name)") + #expect(cursor.bytes == [UInt8](hex: vector.hex), "\(vector.name)") + #expect(PageCursor(bytes: [UInt8](hex: vector.hex)) == cursor, "\(vector.name)") + } + } + + /// Each page method sends the code of its command and the request bytes, + /// and reads the reply with the item decoder of its command. + @Test func givenRequestVectorsWhenReadingPagesShouldSendTheRequestBytesAndDecodeTheReply() async throws { + var replies: [UInt32: ListPagesFixture.Response] = [:] + for vector in fixture.responses { + let code = try #require(listCommands[vector.command], "\(vector.command)").rawValue + replies[code] = replies[code] ?? vector + } + let scripted = replies + let server = try await FakeVSRServer.started() + defer { Task { await server.stop() } } + await server.respond { request in + if let code = request.code, let reply = scripted[code] { + return .ok([UInt8](hex: reply.responseHex)) + } + return FakeVSRServer.defaultReply(request, address: server.address) + } + let client = try await connectedClient(server) + + for vector in fixture.requests { + let code = try #require(listCommands[vector.command], "\(vector.command)") + let ids = try await readPage( + client, code, query: try namedPageQuery(vector.input), streamID: vector.input.streamID?.identifier, topicID: vector.input.topicID?.identifier) + #expect(ids == scripted[code.rawValue]?.items.map(\.id), "\(vector.name)") + let sent = await server.requests.last { $0.code == code.rawValue } + #expect(sent?.payload == [UInt8](hex: vector.requestHex), "\(vector.name)") + #expect(sent?.operation == .nonReplicated, "\(vector.name)") + } + await client.shutdown() + } + + @Test func givenResponseVectorsWhenDecodingShouldReachTheNextTextAndTheItemsInReplyOrder() throws { + for vector in fixture.responses + fixture.opaqueResponses { + let page = try decodePage(vector.command, [UInt8](hex: vector.responseHex)) + #expect(page.next == vector.next, "\(vector.name)") + #expect(page.items == vector.items, "\(vector.name)") + } + } + + @Test func givenOpaqueNextWhenSendingItBackShouldKeepItsBytes() throws { + for vector in fixture.opaqueResponses { + let reply = [UInt8](hex: vector.responseHex) + let next = try #require(try Responses.page(reply[...], item: Responses.stream(from:)).next, "\(vector.name)") + // The block of a first page, with the [next_len][next] of the + // reply as its [cursor_len][cursor] and no name. + let replyNext = reply.prefix(1 + Int(reply[0])) + let expected = [PageOrder.id.rawValue, 0] + PageQuery.defaultLimit.littleEndianBytes + replyNext + [0] + #expect(try Requests.listPage(query: PageQuery(cursor: next)) == expected, "\(vector.name)") + } + } + + @Test func givenRefusedCursorTextWhenParsingShouldRefuseWithoutRepeatingTheText() { + for vector in fixture.refused.cursors { + do { + _ = try PageCursor(text: vector.text) + Issue.record("\(vector.name) parsed") + } catch let error as IggyError { + #expect(error.code == .invalidCommand, "\(vector.name)") + #expect(vector.text.isEmpty || !String(reflecting: error).contains(vector.text), "\(vector.name)") + } catch { + Issue.record("\(vector.name): \(error)") + } + } + } + + @Test func givenRefusedQueriesWhenReadingAPageShouldRefuseBeforeSendingAnything() async throws { + let server = try await FakeVSRServer.started() + defer { Task { await server.stop() } } + let client = try await connectedClient(server) + for vector in fixture.refused.queries { + let query = try namedPageQuery(vector.input) + #expect(throws: IggyError(.invalidCommand), "\(vector.name)") { try query.validate() } + if query.name == nil { + #expect(throws: IggyError(.invalidCommand), "\(vector.name)") { try query.page.validate() } + } + // The partitions page takes a PageQuery, which has no name. + for code in listCommands.values where code != .getPartitions || query.name == nil { + await expectCode(.invalidCommand) { + _ = try await readPage(client, code, query: query, streamID: ListPagesTests.streamID, topicID: ListPagesTests.topicID) + } + } + } + let codes = Set(listCommands.values.map(\.rawValue)) + #expect(await server.requests.allSatisfy { $0.code.map { !codes.contains($0) } ?? true }) + await client.shutdown() + } + + @Test func givenRefusedResponsesWhenDecodingShouldRefuseAsMalformed() { + for vector in fixture.refused.responses { + #expect(throws: IggyError(.invalidCommand), "\(vector.name)") { try decodePage(vector.command, [UInt8](hex: vector.responseHex)) } + } + } +} + +/// The Swift codecs and the client on their own: replies the fixture does not +/// hold, the cursor text form, the page rules, and the walk of the whole-list +/// methods through a scripted server. +@Suite("List page codecs and client", .serialized) +struct ListPagesTests { + static let streamID: Identifier = 1 + static let topicID: Identifier = 2 + /// Each page of the timeout test answers after 0.6 of the request + /// timeout, so one page fits a timeout and two pages do not. + static let requestTimeout: Duration = .seconds(2) + static let pageDelay: Duration = .milliseconds(1200) + /// One item of each whole list, as the Rust encoders wrote it. Each item + /// starts with its id. + static let itemVectors: [CommandCode: String] = [ + .getStreams: "response.stream", .getTopics: "response.topic_header", .getConsumerGroups: "response.consumer_group", .getUsers: "response.user", + ] + + let fixture = ListPagesFixture.shared + + @Test func givenResponseVectorsWhenCutShouldRefuseAsMalformed() { + for vector in fixture.responses + fixture.opaqueResponses { + let reply = [UInt8](hex: vector.responseHex) + for length in 0..<reply.count { + #expect(throws: IggyError(.invalidCommand), "\(vector.name) cut to \(length) bytes") { + try decodePage(vector.command, Array(reply.prefix(length))) + } + } + } + } + + @Test func givenAnyCursorBytesWhenPrintingAndParsingTheTextShouldRoundTrip() throws { + var generator = SystemRandomNumberGenerator() + for length in 1...PageCursor.maxSize { + let bytes = (0..<length).map { _ in UInt8.random(in: .min ... .max, using: &generator) } + let cursor = try #require(PageCursor(bytes: bytes), "\(length)") + #expect(cursor.description.utf8.count <= PageCursor.maxTextLength, "\(length)") + #expect(try PageCursor(text: cursor.description) == cursor, "\(length)") + } + #expect(PageCursor(bytes: []) == nil) + #expect(PageCursor(bytes: Array(repeating: 0, count: PageCursor.maxSize + 1)) == nil) + } + + @Test func givenPageRulesWhenValidatingShouldRefuseOnlyBrokenQueries() throws { + // A name counts bytes: 127 two-byte characters and one letter fill it. + let longestName = String(repeating: "é", count: NamedPageQuery.maxNameSize / 2) + "a" + #expect(longestName.utf8.count == NamedPageQuery.maxNameSize) + for page in [PageQuery(), PageQuery(limit: 1), PageQuery(limit: PageQuery.maxLimit), PageQuery(order: .created, descending: true)] { + try page.validate() + try NamedPageQuery(page: page, name: longestName).validate() + } + for page in [PageQuery(limit: 0), PageQuery(limit: PageQuery.maxLimit + 1)] { + #expect(throws: IggyError(.invalidCommand), "\(page)") { try page.validate() } + #expect(throws: IggyError(.invalidCommand), "\(page)") { try NamedPageQuery(page: page).validate() } + } + for name in ["", longestName + "a"] { + #expect(throws: IggyError(.invalidCommand), "\(name.utf8.count) bytes") { try NamedPageQuery(name: name).validate() } + } + } + + /// The middle page is empty and still has a next cursor, so a walk that + /// stops on an empty page loses the last items. + @Test(arguments: [CommandCode.getStreams, .getTopics, .getConsumerGroups, .getUsers]) + func givenThreePagesWhenReadingTheWholeListShouldFollowEveryNextAndKeepEveryItem(_ command: CommandCode) async throws { + let item = GoldenFixture.shared.bytes(try #require(Self.itemVectors[command])) + let cursors = [try #require(PageCursor.id(1)), try #require(PageCursor.id(2))] + let replies = [ + FakeVSRServer.pageBody(next: cursors[0].bytes, items: [entry(item, id: 1)]), + FakeVSRServer.pageBody(next: cursors[1].bytes), + FakeVSRServer.pageBody(items: [entry(item, id: 2), entry(item, id: 3)]), + ] + let server = try await scriptedServer(command, replies) + defer { Task { await server.stop() } } + let client = try await connectedClient(server) + + #expect(try await wholeList(client, command) == [1, 2, 3]) + let sent = await server.requests.filter { $0.code == command.rawValue }.map(\.payload) + let expected = try [nil, cursors[0], cursors[1]].map { try request(command, PageQuery(limit: PageQuery.maxLimit, cursor: $0)) } + #expect(sent == expected) + await client.shutdown() + } + + /// The third reply is a last page, so a walk that misses the repeat ends + /// and fails the test instead of hanging it. + @Test(arguments: [CommandCode.getStreams, .getTopics, .getConsumerGroups, .getUsers]) + func givenANextThatRepeatsTheCursorSentWhenReadingTheWholeListShouldRefuseAsMalformed(_ command: CommandCode) async throws { + let cursor = try #require(PageCursor.id(1)) + let repeated = FakeVSRServer.pageBody(next: cursor.bytes) + let server = try await scriptedServer(command, [repeated, repeated, FakeVSRServer.pageBody()]) + defer { Task { await server.stop() } } + let client = try await connectedClient(server) + + await expectCode(.invalidCommand) { _ = try await wholeList(client, command) } + let sent = await server.requests.filter { $0.code == command.rawValue }.map(\.payload) + let expected = try [nil, cursor].map { try request(command, PageQuery(limit: PageQuery.maxLimit, cursor: $0)) } + #expect(sent == expected) + await client.shutdown() + } + + /// The caller signs in while the first page is in flight. The walk keeps + /// the sign-in it started with, so the next page is not sent under the + /// new one. The second reply is a last page, so a walk that sends it + /// returns a list instead of failing. + @Test(arguments: [CommandCode.getStreams, .getTopics, .getConsumerGroups, .getUsers]) + func givenACallerSignInDuringTheFirstPageWhenReadingTheWholeListShouldRefuseTheNextPageAsUnauthenticated(_ command: CommandCode) async throws { + let cursor = try #require(PageCursor.id(1)) + let released = Locked(false) + let server = try await scriptedServer(command, [FakeVSRServer.pageBody(next: cursor.bytes), FakeVSRServer.pageBody()]) { + _ = await eventually { released.withLock { $0 } } + } + defer { Task { await server.stop() } } + let client = try await connectedClient(server) + let lineage = await client.operationLineage + + let walk = Task { try await wholeList(client, command) } + #expect(await eventually { await pageRequests(server, command) == 1 }) + let signIn = Task { try await client.login(username: "iggy", password: "iggy") } + #expect(await eventually { await client.operationLineage != lineage }) + released.withLock { $0 = true } + + await expectCode(.unauthenticated) { _ = try await walk.value } + _ = try await signIn.value + #expect(await pageRequests(server, command) == 1) + await client.shutdown() + } + + /// One request timeout covers the whole walk, so the second page fails + /// although each page alone answers within a timeout. The second reply + /// is a last page, so a walk with a timeout per page returns a list. + /// Every whole list shares this walk, so one list keeps the suite short. + @Test(arguments: [CommandCode.getStreams]) + func givenPagesThatTogetherOutlastTheRequestTimeoutWhenReadingTheWholeListShouldFailAsNotAccepted(_ command: CommandCode) async throws { + let cursor = try #require(PageCursor.id(1)) + let server = try await scriptedServer(command, [FakeVSRServer.pageBody(next: cursor.bytes), FakeVSRServer.pageBody()]) { + try? await Task.sleep(for: Self.pageDelay) + } + defer { Task { await server.stop() } } + let client = try await connectedClient(server, requestTimeout: Self.requestTimeout) + + await expectCode(.transientNotAccepted) { _ = try await wholeList(client, command) } + #expect(await pageRequests(server, command) == 2) + await client.shutdown() + } + + // MARK: Helpers + + /// A server that answers the requests of `command` with `replies` in + /// turn, each once `beforeReply` returns, and with the last reply once + /// they run out. + func scriptedServer( + _ command: CommandCode, _ replies: [[UInt8]], beforeReply: @escaping @Sendable () async -> Void = {} + ) async throws -> FakeVSRServer { + let served = Locked(0) + let server = try await FakeVSRServer.started() + await server.respond { request in + guard request.code == command.rawValue else { + return FakeVSRServer.defaultReply(request, address: server.address) + } + let index = served.withLock { count in + defer { count += 1 } + return count + } + await beforeReply() + return .ok(replies[min(index, replies.count - 1)]) + } + return server + } + + func pageRequests(_ server: FakeVSRServer, _ command: CommandCode) async -> Int { + await server.requests.filter { $0.code == command.rawValue }.count + } + + /// `item` with its leading id replaced by `id`. + func entry(_ item: [UInt8], id: UInt32) -> [UInt8] { + let idBytes = id.littleEndianBytes + var entry = item + entry.replaceSubrange(0..<idBytes.count, with: idBytes) + return entry + } + + func request(_ command: CommandCode, _ query: PageQuery) throws -> [UInt8] { + switch command { + case .getTopics: + return try Requests.listPage(Self.streamID, query: query) + case .getConsumerGroups: + return try Requests.listPage(Self.streamID, Self.topicID, query: query) + default: + return try Requests.listPage(query: query) + } + } + + func wholeList(_ client: IggyClient, _ command: CommandCode) async throws -> [UInt32] { + switch command { + case .getStreams: + return try await client.getStreams().map(\.id) + case .getTopics: + return try await client.getTopics(streamID: Self.streamID).map(\.id) + case .getConsumerGroups: + return try await client.getConsumerGroups(streamID: Self.streamID, topicID: Self.topicID).map(\.id) + case .getUsers: + return try await client.getUsers().map(\.id) + default: + Issue.record("\(command) has no whole-list method") + return [] + } + } +} + +private let listCommands: [String: CommandCode] = [ + "get_users": .getUsers, "get_streams": .getStreams, "get_topics": .getTopics, "get_partitions": .getPartitions, "get_consumer_groups": .getConsumerGroups, +] + +private let pageOrders: [String: PageOrder] = ["id": .id, "created": .created] + +/// A client of `server`, connected and signed in. +private func connectedClient(_ server: FakeVSRServer, requestTimeout: Duration = .seconds(30)) async throws -> IggyClient { + var configuration = ClientConfiguration(address: server.address, autoLogin: .usernamePassword(username: "iggy", password: "iggy")) + configuration.connectTimeout = .seconds(2) + configuration.requestTimeout = requestTimeout + configuration.heartbeatInterval = .seconds(60) + let client = IggyClient(configuration: configuration, connector: NIOConnector(), logger: testLogger) + try await client.connect() + return client +} + +private func namedPageQuery(_ input: ListPagesFixture.Input) throws -> NamedPageQuery { + let page = PageQuery( + order: try #require(pageOrders[input.order], "\(input.order)"), descending: input.descending, limit: input.limit, + cursor: try input.cursor.map { try PageCursor(text: $0) }) + return NamedPageQuery(page: page, name: input.name) +} + +/// Reads one page with the page method of `code` and returns the ids of its +/// items. The partitions page takes only the ``PageQuery`` of `query`, so its +/// query must have no name. Only the lists of topics, partitions and consumer +/// groups need a parent. +private func readPage( + _ client: IggyClient, _ code: CommandCode, query: NamedPageQuery, streamID: Identifier? = nil, topicID: Identifier? = nil +) async throws -> [UInt32] { + switch code { + case .getStreams: + return try await client.getStreamsPage(query).items.map(\.id) + case .getTopics: + return try await client.getTopicsPage(streamID: try #require(streamID), query: query).items.map(\.id) + case .getPartitions: + try #require(query.name == nil, "a partitions query has no name") + return try await client.getPartitionsPage(streamID: try #require(streamID), topicID: try #require(topicID), query: query.page).items.map(\.id) + case .getConsumerGroups: + return try await client.getConsumerGroupsPage(streamID: try #require(streamID), topicID: try #require(topicID), query: query).items.map(\.id) + case .getUsers: + return try await client.getUsersPage(query).items.map(\.id) + default: + Issue.record("\(code) is not a list command") + return [] + } +} + +/// The next text and the items of a reply, in the form of the fixture. +private func decodePage(_ command: String, _ body: [UInt8]) throws -> (next: String?, items: [ListPagesFixture.Item]) { + func view<Item: Sendable & Hashable>(_ page: Page<Item>, _ item: (Item) -> ListPagesFixture.Item) -> (next: String?, items: [ListPagesFixture.Item]) { + (page.next?.description, page.items.map(item)) + } + switch command { + case "get_streams": + return view(try Responses.page(body[...], item: Responses.stream(from:))) { .init(id: $0.id, name: $0.name) } + case "get_topics": + return view(try Responses.page(body[...], item: Responses.topic(from:))) { .init(id: $0.id, name: $0.name) } + case "get_partitions": + return view(try Responses.page(body[...], item: Responses.partition(from:))) { .init(id: $0.id, name: nil) } + case "get_consumer_groups": + return view(try Responses.page(body[...], item: Responses.consumerGroup(from:))) { .init(id: $0.id, name: $0.name) } + case "get_users": + return view(try Responses.page(body[...], item: Responses.user(from:))) { .init(id: $0.id, name: $0.username) } + default: + Issue.record("unknown command \(command)") + return (nil, []) + } +}
diff --git a/foreign/swift/Tests/IggyTests/ResourceOptionsTests.swift b/foreign/swift/Tests/IggyTests/ResourceOptionsTests.swift index 6e0922d..9f72a71 100644 --- a/foreign/swift/Tests/IggyTests/ResourceOptionsTests.swift +++ b/foreign/swift/Tests/IggyTests/ResourceOptionsTests.swift
@@ -242,7 +242,8 @@ #expect(stream.encryptionKeyFingerprint == expected.encryptionKeyFingerprint, "\(vector.name)") #expect(stream.encryptionKekFingerprints == expected.encryptionKekFingerprints, "\(vector.name)") #expect(neverReturned.isDisjoint(with: stream.options.keys), "\(vector.name)") - let listed = try #require(try Responses.streams([UInt8](hex: vector.responseHex)[...]).first) + var listReader = ByteReader([UInt8](hex: vector.responseHex)) + let listed = try Responses.stream(from: &listReader) #expect(listed.options == stream.options) #expect(listed.encryptionKeySource == stream.encryptionKeySource) #expect(listed.encryptionKeyFingerprint == stream.encryptionKeyFingerprint)
diff --git a/foreign/swift/Tests/IggyTests/ResponseVectorTests.swift b/foreign/swift/Tests/IggyTests/ResponseVectorTests.swift index d4b64bb..a3d8022 100644 --- a/foreign/swift/Tests/IggyTests/ResponseVectorTests.swift +++ b/foreign/swift/Tests/IggyTests/ResponseVectorTests.swift
@@ -81,11 +81,13 @@ expectSampleTopic(details.topics[0], id: 1, name: "topic-a") expectSampleTopic(details.topics[1], id: 2, name: "topic-b") - let streams = try Responses.streams(body("response.get_streams")) - #expect(streams.map(\.id) == [1, 2]) - #expect(streams.map(\.topicsCount) == [2, 0]) - #expect(streams.allSatisfy { $0.options == details.options && $0.encryptionKeySource == .stream }) - #expect(try Responses.streams([]).isEmpty) + let streams = try Responses.page(body("response.get_streams"), item: Responses.stream(from:)) + #expect(streams.items.map(\.id) == [1, 2]) + #expect(streams.items.map(\.topicsCount) == [2, 0]) + #expect(streams.items.allSatisfy { $0.options == details.options && $0.encryptionKeySource == .stream }) + #expect(streams.next == PageCursor.id(2)) + // Every list reply is a page, so an empty body is malformed. + #expect(throws: IggyError(.invalidCommand)) { try Responses.page([], item: Responses.stream(from:)) } } @Test func topics() throws { @@ -115,9 +117,14 @@ #expect(fencedPartitions[2].messagesCount == 8) #expect(fencedPartitions[2].members == [2, 0, 1]) - let topics = try Responses.topics(body("response.get_topics")) - #expect(topics.map(\.name) == ["events", "logs"]) - #expect(try Responses.topics(body("response.get_topics.empty")).isEmpty) + let topics = try Responses.page(body("response.get_topics"), item: Responses.topic(from:)) + #expect(topics.items.map(\.name) == ["events", "logs"]) + #expect(topics.next == PageCursor.created(at: createdAt.microseconds, id: 2)) + #expect(try Responses.page(body("response.get_topics.empty"), item: Responses.topic(from:)) == Page(items: [], next: nil)) + + let partitions = try Responses.page(body("response.get_partitions"), item: Responses.partition(from:)) + #expect(partitions.items == details.partitions) + #expect(partitions.next == PageCursor.id(2)) } @Test func partitionNodeLists() throws { @@ -173,9 +180,10 @@ #expect(details.partitionsCount == 6) #expect(details.members.map(\.partitions) == [[0, 1, 2], [3, 4, 5]]) - let groups = try Responses.consumerGroups(body("response.get_consumer_groups")) - #expect(groups.map(\.name) == ["group-a", "group-b"]) - #expect(groups.map(\.membersCount) == [2, 0]) + let groups = try Responses.page(body("response.get_consumer_groups"), item: Responses.consumerGroup(from:)) + #expect(groups.items.map(\.name) == ["group-a", "group-b"]) + #expect(groups.items.map(\.membersCount) == [2, 0]) + #expect(groups.next == nil) let assignment = try Responses.consumerGroupAssignment(body("response.sync_consumer_group")) #expect(assignment == ConsumerGroupAssignment(generation: 7, partitions: [0, 2, 4])) @@ -260,10 +268,11 @@ let plain = try Responses.userDetails(body("response.user_details.no_permissions")) #expect(plain.permissions == nil) - let users = try Responses.users(body("response.get_users")) - #expect(users.map(\.username) == ["admin", "alice"]) - #expect(users.map(\.status) == [.active, .inactive]) - #expect(users.allSatisfy { $0.options.isEmpty }) + let users = try Responses.page(body("response.get_users"), item: Responses.user(from:)) + #expect(users.items.map(\.username) == ["admin", "alice"]) + #expect(users.items.map(\.status) == [.active, .inactive]) + #expect(users.items.allSatisfy { $0.options.isEmpty }) + #expect(users.next == nil) } @Test func loginAndIdentity() throws {
diff --git a/foreign/swift/Tests/IggyTests/Support/FakeVSRServer.swift b/foreign/swift/Tests/IggyTests/Support/FakeVSRServer.swift index 618b96f..04b1bef 100644 --- a/foreign/swift/Tests/IggyTests/Support/FakeVSRServer.swift +++ b/foreign/swift/Tests/IggyTests/Support/FakeVSRServer.swift
@@ -300,6 +300,19 @@ return writer.bytes } + /// A list reply, `[next_len:u8][next][count:u32][item]*`. A next of no + /// bytes marks the last page. + static func pageBody(next: [UInt8] = [], items: [[UInt8]] = []) -> [UInt8] { + var writer = ByteWriter() + writer.write(UInt8(next.count)) + writer.write(next) + writer.write(UInt32(items.count)) + for item in items { + writer.write(item) + } + return writer.bytes + } + /// A topic with three partitions, 0 to 2, under `contexts`. static func topicBody(contexts: [PartitionContext]) -> [UInt8] { precondition(contexts.count == 3, "the golden topic header names three partitions") @@ -420,6 +433,8 @@ return .ok(polledBody(partitionID: 0, context: routeContext)) case .fetchMessages: return .ok(fetchedBody([])) + case .getStreams, .getTopics, .getPartitions, .getConsumerGroups, .getUsers: + return .ok(pageBody()) case .cancelDeferredRequest: return .stall default:
diff --git a/foreign/swift/Tests/IggyTests/Support/ListPagesFixture.swift b/foreign/swift/Tests/IggyTests/Support/ListPagesFixture.swift new file mode 100644 index 0000000..b514202 --- /dev/null +++ b/foreign/swift/Tests/IggyTests/Support/ListPagesFixture.swift
@@ -0,0 +1,205 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +import Foundation + +@testable import Iggy + +/// The cross-SDK list page fixture, generated by +/// `core/common/examples/list_pages_fixtures.rs` from the real Rust codecs and +/// copied byte for byte into every SDK. Never edit the copy. Each vector group +/// is a required key, so a renamed group fails the load instead of reading as +/// empty. +struct ListPagesFixture: Decodable, Sendable { + static let shared: ListPagesFixture = { + let url = Bundle.module.url(forResource: "list_pages", withExtension: "json", subdirectory: "Fixtures")! + return try! JSONDecoder().decode(ListPagesFixture.self, from: Data(contentsOf: url)) + }() + + struct Constants: Decodable, Sendable { + let codes: [String: UInt32] + let orders: [String: UInt8] + let cursorPrefix: String + let maxCursorBytes: Int + let defaultLimit: UInt32 + let maxLimit: UInt32 + let maxNameBytes: Int + let errors: [String: UInt32] + + enum CodingKeys: String, CodingKey { + case codes, orders, errors + case cursorPrefix = "cursor_prefix" + case maxCursorBytes = "max_cursor_bytes" + case defaultLimit = "default_limit" + case maxLimit = "max_limit" + case maxNameBytes = "max_name_bytes" + } + } + + struct Cursor: Decodable, Sendable { + let name: String + let text: String + let hex: String + + enum CodingKeys: String, CodingKey { + case name = "case" + case text, hex + } + } + + /// A stream or topic id: `kind` numeric with a `UInt32` value, or named + /// with a string value. + struct ParentID: Decodable, Sendable { + let identifier: Identifier + + enum CodingKeys: String, CodingKey { + case kind, value + } + + init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + switch try container.decode(String.self, forKey: .kind) { + case "numeric": + identifier = Identifier(numeric: try container.decode(UInt32.self, forKey: .value)) + case "named": + identifier = try Identifier(named: try container.decode(String.self, forKey: .value)) + case let kind: + throw DecodingError.dataCorruptedError(forKey: .kind, in: container, debugDescription: "unknown identifier kind \(kind)") + } + } + } + + struct Input: Decodable, Sendable { + let streamID: ParentID? + let topicID: ParentID? + let order: String + let descending: Bool + let limit: UInt32 + let cursor: String? + let name: String? + + enum CodingKeys: String, CodingKey { + case order, descending, limit, cursor, name + case streamID = "stream_id" + case topicID = "topic_id" + } + } + + struct Request: Decodable, Sendable { + let name: String + let command: String + let input: Input + let requestHex: String + + enum CodingKeys: String, CodingKey { + case name = "case" + case command, input + case requestHex = "request_hex" + } + } + + struct Item: Decodable, Sendable, Equatable { + let id: UInt32 + /// Nil for a partition, which has no name. + let name: String? + } + + struct Response: Decodable, Sendable { + let name: String + let command: String + let responseHex: String + let next: String? + let items: [Item] + + enum CodingKeys: String, CodingKey { + case name = "case" + case command, next, items + case responseHex = "response_hex" + } + } + + struct RefusedCursor: Decodable, Sendable { + let name: String + let text: String + + enum CodingKeys: String, CodingKey { + case name = "case" + case text + } + } + + struct RefusedQuery: Decodable, Sendable { + let name: String + let input: Input + + enum CodingKeys: String, CodingKey { + case name = "case" + case input + } + } + + struct RefusedResponse: Decodable, Sendable { + let name: String + let command: String + let responseHex: String + + enum CodingKeys: String, CodingKey { + case name = "case" + case command + case responseHex = "response_hex" + } + } + + struct Refused: Decodable, Sendable { + let cursors: [RefusedCursor] + let queries: [RefusedQuery] + let responses: [RefusedResponse] + } + + let schemaVersion: Int + let constants: Constants + let cursors: [Cursor] + let opaqueCursors: [Cursor] + let requests: [Request] + let responses: [Response] + let opaqueResponses: [Response] + let refused: Refused + + enum CodingKeys: String, CodingKey { + case constants, cursors, requests, responses, refused + case schemaVersion = "schema_version" + case opaqueCursors = "opaque_cursors" + case opaqueResponses = "opaque_responses" + } +} + +/// Cursors as the server writes them, for tests that script replies. The +/// client itself never reads the bytes of a cursor. +extension PageCursor { + static let idKind: UInt8 = 1 + static let createdKind: UInt8 = 2 + + /// `[kind:u8][id:u64]`, a position in id order. + static func id(_ id: UInt64) -> PageCursor? { + PageCursor(bytes: [idKind] + id.littleEndianBytes) + } + + /// `[kind:u8][created_at:u64][id:u64]`, a position in creation order. + static func created(at createdAt: UInt64, id: UInt64) -> PageCursor? { + PageCursor(bytes: [createdKind] + createdAt.littleEndianBytes + id.littleEndianBytes) + } +}
diff --git a/foreign/swift/Tests/IggyTests/WireVectorTests.swift b/foreign/swift/Tests/IggyTests/WireVectorTests.swift index 9bb0339..952d2c6 100644 --- a/foreign/swift/Tests/IggyTests/WireVectorTests.swift +++ b/foreign/swift/Tests/IggyTests/WireVectorTests.swift
@@ -61,7 +61,7 @@ try Requests.createStream(name: "test-stream", options: try OptionsBlock.encode(sampleOptions)) == golden.bytes("request.create_stream.options")) #expect(try encode(5) == golden.bytes("request.delete_stream")) #expect(try encode("my-stream") == golden.bytes("request.get_stream")) - #expect(golden.bytes("request.get_streams").isEmpty) + #expect(try Requests.listPage(query: PageQuery()) == golden.bytes("request.get_streams")) let key = Data((0..<UInt8(EncryptionKey.length)).map { $0 }) #expect( try Requests.createStream(name: "test-stream", options: StreamCreateOptions(encryptionKey: key).encode()) @@ -76,7 +76,9 @@ == golden.bytes("request.create_topic")) #expect(try Requests.streamAndTopic(1, 5) == golden.bytes("request.delete_topic")) #expect(try Requests.streamAndTopic("my-stream", "my-topic") == golden.bytes("request.get_topic")) - #expect(try encode(42) == golden.bytes("request.get_topics")) + let topicsQuery = NamedPageQuery( + page: PageQuery(order: .created, descending: true, limit: 20, cursor: PageCursor.created(at: 1_710_000_000_000_000, id: 7)), name: "ord") + #expect(try Requests.listPage(42, query: topicsQuery) == golden.bytes("request.get_topics")) let update = TopicUpdateOptions(name: "updated-topic", messageExpiry: .after(.seconds(604_800)), reset: [.maxTopicSize]) #expect(try Requests.updateResource(.topic(stream: 1, topic: 2), update.toPatch()) == golden.bytes("request.update_resource.topic")) // Reset names travel in byte order, whatever order they were named in. @@ -90,13 +92,15 @@ #expect(try Requests.partitions(streamID: 1, topicID: 2, partitionsCount: 5) == golden.bytes("request.create_partitions")) #expect(try Requests.partitions(streamID: "stream", topicID: "topic", partitionsCount: 2) == golden.bytes("request.delete_partitions")) #expect(try Requests.deleteSegments(streamID: 1, topicID: 2, partitionID: 3, segmentsCount: 10) == golden.bytes("request.delete_segments")) + let partitionsQuery = PageQuery(descending: true, limit: PageQuery.maxLimit, cursor: PageCursor.id(2)) + #expect(try Requests.listPage("stream", "topic", query: partitionsQuery) == golden.bytes("request.get_partitions")) } @Test func consumerGroups() throws { #expect(try Requests.createConsumerGroup(streamID: 1, topicID: 2, name: "grp") == golden.bytes("request.create_consumer_group")) #expect(try Requests.consumerGroup(streamID: 1, topicID: 2, groupID: 3) == golden.bytes("request.delete_consumer_group")) #expect(try Requests.consumerGroup(streamID: "stream-1", topicID: "topic-1", groupID: "group-1") == golden.bytes("request.get_consumer_group")) - #expect(try Requests.streamAndTopic(1, 2) == golden.bytes("request.get_consumer_groups")) + #expect(try Requests.listPage(1, 2, query: PageQuery()) == golden.bytes("request.get_consumer_groups")) #expect(try Requests.consumerGroup(streamID: 1, topicID: 2, groupID: 3) == golden.bytes("request.join_consumer_group")) #expect(try Requests.consumerGroup(streamID: 1, topicID: 2, groupID: "g") == golden.bytes("request.leave_consumer_group")) #expect(try Requests.consumerGroup(streamID: "stream-1", topicID: "topic-1", groupID: "group-1") == golden.bytes("request.sync_consumer_group")) @@ -160,7 +164,8 @@ == golden.bytes("request.create_user.no_permissions")) #expect(try encode("old-user") == golden.bytes("request.delete_user")) #expect(try encode(42) == golden.bytes("request.get_user")) - #expect(golden.bytes("request.get_users").isEmpty) + // The first page of the walk that the whole-list methods do. + #expect(try Requests.listPage(query: PageQuery(limit: PageQuery.maxLimit)) == golden.bytes("request.get_users")) #expect( try Requests.updateResource(.user(1), UserUpdateOptions(username: "new-name", status: .inactive).toPatch()) == golden.bytes("request.update_resource.user"))
diff --git a/foreign/swift/Tools/golden-vectors/src/main.rs b/foreign/swift/Tools/golden-vectors/src/main.rs index 5e87f53..330aa54 100644 --- a/foreign/swift/Tools/golden-vectors/src/main.rs +++ b/foreign/swift/Tools/golden-vectors/src/main.rs
@@ -41,6 +41,9 @@ WireMetadataChangePhase, WireMetadataChangeStatus, WireStreamBody, WireStreamKey, }; use iggy_binary_protocol::primitives::options::WireOptions; +use iggy_binary_protocol::primitives::page::{ + MAX_PAGE_LIMIT, WirePageCursor, WirePageOrder, WirePageQuery, +}; use iggy_binary_protocol::primitives::partition_history::PartitionContext; use iggy_binary_protocol::primitives::permissions::{ WireGlobalPermissions, WirePermissions, WireStreamPermissions, WireTopicPermissions, @@ -54,7 +57,7 @@ MIN_DEFERRED_POLL_MAX_BYTES, PollMessagesRequest, RawMessage, SendMessagesEncoder, }; use iggy_binary_protocol::requests::partitions::{ - CreatePartitionsRequest, DeletePartitionsRequest, + CreatePartitionsRequest, DeletePartitionsRequest, GetPartitionsRequest, }; use iggy_binary_protocol::requests::personal_access_tokens::*; use iggy_binary_protocol::requests::segments::DeleteSegmentsRequest; @@ -65,12 +68,13 @@ }; use iggy_binary_protocol::requests::users::login_register::BindSecret; use iggy_binary_protocol::requests::users::*; +use iggy_binary_protocol::responses::PageResponse; use iggy_binary_protocol::responses::clients::{ ClientDetailsResponse, ClientResponse, ConsumerGroupInfoResponse, GetClientsResponse, }; use iggy_binary_protocol::responses::consumer_groups::{ ConsumerGroupDetailsResponse, ConsumerGroupMemberResponse, ConsumerGroupResponse, - GetConsumerGroupsResponse, SyncConsumerGroupResponse, + SyncConsumerGroupResponse, }; use iggy_binary_protocol::responses::consumer_offsets::ConsumerOffsetResponse; use iggy_binary_protocol::responses::messages::{ @@ -81,19 +85,15 @@ use iggy_binary_protocol::responses::personal_access_tokens::{ GetPersonalAccessTokensResponse, PersonalAccessTokenResponse, RawPersonalAccessTokenResponse, }; -use iggy_binary_protocol::responses::streams::{ - GetStreamResponse, GetStreamsResponse, StreamResponse, TopicHeader, -}; +use iggy_binary_protocol::responses::streams::{GetStreamResponse, StreamResponse, TopicResponse}; use iggy_binary_protocol::responses::system::get_stats::{CacheMetricEntry, StatsResponse}; use iggy_binary_protocol::responses::system::{ ClusterMetadataResponse, ClusterNodeResponse, DescribeOptionsResponse, GetMetadataChangesResponse, OptionDescriptor, WireMetadataChangeRecord, }; -use iggy_binary_protocol::responses::topics::{ - GetTopicResponse, GetTopicsResponse, PartitionResponse, -}; +use iggy_binary_protocol::responses::topics::{GetTopicResponse, PartitionResponse}; use iggy_binary_protocol::responses::users::{ - GetUsersResponse, IdentityResponse, LoginRegisterResponse, UserDetailsResponse, UserResponse, + IdentityResponse, LoginRegisterResponse, UserDetailsResponse, UserResponse, }; use iggy_binary_protocol::{ AckLevel, ClientVersionInfo, IGGY_PROTOCOL_VERSION, IGGY_PROTOCOL_VERSION_MIN, WireConsumer, @@ -329,8 +329,8 @@ bytes } -fn topic_header(id: u32, name_value: &str) -> TopicHeader { - TopicHeader { +fn topic_response(id: u32, name_value: &str) -> TopicResponse { + TopicResponse { id, created_at: 1_710_000_000_000_000, partitions_count: 3, @@ -514,7 +514,13 @@ stream_id: named("my-stream"), }, ); - add(&mut vectors, "request.get_streams", &GetStreamsRequest); + add( + &mut vectors, + "request.get_streams", + &GetStreamsRequest { + page: WirePageQuery::default(), + }, + ); add( &mut vectors, "request.update_resource.stream", @@ -561,6 +567,16 @@ "request.get_topics", &GetTopicsRequest { stream_id: numeric(42), + page: WirePageQuery { + order: WirePageOrder::Created, + descending: true, + limit: 20, + cursor: Some(WirePageCursor::Created { + created_at: 1_710_000_000_000_000, + id: 7, + }), + name: Some(name("ord")), + }, }, ); let topic_update = update_resource( @@ -616,6 +632,20 @@ ); add( &mut vectors, + "request.get_partitions", + &GetPartitionsRequest { + stream_id: named("stream"), + topic_id: named("topic"), + page: WirePageQuery { + descending: true, + limit: MAX_PAGE_LIMIT, + cursor: Some(WirePageCursor::Id(2)), + ..WirePageQuery::default() + }, + }, + ); + add( + &mut vectors, "request.delete_segments", &DeleteSegmentsRequest { stream_id: numeric(1), @@ -657,6 +687,7 @@ &GetConsumerGroupsRequest { stream_id: numeric(1), topic_id: numeric(2), + page: WirePageQuery::default(), }, ); add( @@ -903,7 +934,17 @@ user_id: numeric(42), }, ); - add(&mut vectors, "request.get_users", &GetUsersRequest); + // The first page of the walk that the list methods do. + add( + &mut vectors, + "request.get_users", + &GetUsersRequest { + page: WirePageQuery { + limit: MAX_PAGE_LIMIT, + ..WirePageQuery::default() + }, + }, + ); add( &mut vectors, "request.update_resource.user", @@ -1325,20 +1366,21 @@ "response.get_stream", &GetStreamResponse { stream: stream_response(1, 2), - topics: vec![topic_header(1, "topic-a"), topic_header(2, "topic-b")], + topics: vec![topic_response(1, "topic-a"), topic_response(2, "topic-b")], }, ); add( &mut vectors, "response.get_streams", - &GetStreamsResponse { - streams: vec![stream_response(1, 2), stream_response(2, 0)], + &PageResponse { + items: vec![stream_response(1, 2), stream_response(2, 0)], + next: Some(WirePageCursor::Id(2)), }, ); add( &mut vectors, "response.topic_header", - &topic_header(5, "events"), + &topic_response(5, "events"), ); let partitions = vec![ PartitionResponse { @@ -1379,21 +1421,36 @@ &mut vectors, "response.get_topic", &GetTopicResponse { - topic: topic_header(1, "my-topic"), - partitions, + topic: topic_response(1, "my-topic"), + partitions: partitions.clone(), + }, + ); + add( + &mut vectors, + "response.get_partitions", + &PageResponse { + items: partitions, + next: Some(WirePageCursor::Id(2)), }, ); add( &mut vectors, "response.get_topics", - &GetTopicsResponse { - topics: vec![topic_header(1, "events"), topic_header(2, "logs")], + &PageResponse { + items: vec![topic_response(1, "events"), topic_response(2, "logs")], + next: Some(WirePageCursor::Created { + created_at: 1_710_000_000_000_000, + id: 2, + }), }, ); add( &mut vectors, "response.get_topics.empty", - &GetTopicsResponse { topics: vec![] }, + &PageResponse::<TopicResponse> { + items: vec![], + next: None, + }, ); add( &mut vectors, @@ -1432,8 +1489,8 @@ add( &mut vectors, "response.get_consumer_groups", - &GetConsumerGroupsResponse { - groups: vec![ + &PageResponse { + items: vec![ ConsumerGroupResponse { id: 1, partitions_count: 4, @@ -1447,6 +1504,7 @@ name: name("group-b"), }, ], + next: None, }, ); add( @@ -1551,8 +1609,8 @@ add( &mut vectors, "response.get_users", - &GetUsersResponse { - users: vec![ + &PageResponse { + items: vec![ user, UserResponse { id: 2, @@ -1563,6 +1621,7 @@ derived_options: WireOptions::empty(), }, ], + next: None, }, ); add(
diff --git a/gateways/kafka/Cargo.toml b/gateways/kafka/Cargo.toml index 6a4ccfe..9f236e0 100644 --- a/gateways/kafka/Cargo.toml +++ b/gateways/kafka/Cargo.toml
@@ -17,7 +17,7 @@ [package] name = "iggy-gateway-kafka" -version = "0.2.1-edge.1" +version = "0.2.1-edge.2" description = "Kafka wire protocol gateway foundation for Apache Iggy" edition = "2024" license = "Apache-2.0"