You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by hg...@apache.org on 2026/10/19 17:05:41 UTC
(iggy) 01/19: feat(sdk)!: activate partition routing and recovery
This is an automated email from the ASF dual-hosted git repository.
hubcio pushed a commit to branch feat/sdk-partition-routing
in repository https://gitbox.apache.org/repos/asf/iggy.git
commit 5cf2dd18647402147857ece441e885b8229a8fce
Author: Hubert Gruszecki <h....@gmail.com>
AuthorDate: Mon Oct 19 11:53:53 2026 +0200
feat(sdk)!: activate partition routing and recovery
Partition-aware components were not active across transports, and
uncertain writes lacked a consistent application recovery path.
Activate shared session owners, partition lanes and multiplexed
replica links across Rust and native SDKs. Retain frozen mutations for
explicit resolve or abandon with configurable count and byte limits.
End uncertain progress polls without replaying them.
Require committed receipt proof before releasing uncertain lanes.
Preserve that proof through server reply rewrites and route offset
reads through partition-primary history gates.
Preserve FIFO admission, frozen payloads and one operation deadline
across safe retries and recovery. Refresh session credentials across
replica links and release retained buffers at their owning session.
BREAKING CHANGE: Require fresh IGGY-BOUND-GRANTS-3 storage and
matching servers and SDKs. ReplyHeader byte 220 is the
committed-result marker; value 1 proves a committed result.
Retire commands 103, 104 and 123, remove producer retry configuration,
and update binding recovery/error APIs. VsrSessionControl drops
refresh_session_password and refresh_session_username. Direct C++
bridge calls require a per-call ErrorInfo argument. Node
Client.destroy() now aborts in-flight requests immediately, a sign-in
that reaches no endpoint rejects with NotConnectedError, and consumer
stream factories sign in at creation.
Relates to #4436. Continues the multi-leader routing work from #4506.
Placement and rebalancing will be raised as next PR.
---
.github/actions/cpp-bazel/pre-merge/action.yml | 3 +-
.../features/step_definitions/background_steps.cpp | 3 +-
.../features/step_definitions/messaging_steps.cpp | 13 +-
.../step_definitions/raw_command_steps.cpp | 3 +-
bdd/go/go.mod | 1 -
bdd/go/go.sum | 2 -
core/binary_protocol/src/codes.rs | 13 +-
core/binary_protocol/src/consensus/header.rs | 43 +-
core/binary_protocol/src/consensus/reply_result.rs | 37 +-
core/binary_protocol/src/dispatch.rs | 8 +-
core/binary_protocol/src/responses/messages/mod.rs | 2 -
.../src/responses/messages/poll_routing.rs | 104 -
core/common/src/lib.rs | 7 +
core/common/src/traits/binary_impls/messages.rs | 409 +-
core/common/src/traits/binary_impls/mod.rs | 12 +-
.../traits/binary_impls/personal_access_tokens.rs | 52 +-
core/common/src/traits/binary_impls/users.rs | 63 +-
core/common/src/traits/binary_transport.rs | 201 +-
core/common/src/traits/client.rs | 48 +-
core/common/src/traits/message_client.rs | 4 +-
core/common/src/traits/mod.rs | 2 +-
core/common/src/types/configuration/mod.rs | 1 +
.../configuration/pending_operations_config.rs | 145 +
.../quic_config/quic_client_config.rs | 6 +-
.../quic_config/quic_client_config_builder.rs | 14 +-
.../quic_config/quic_client_reconnection_config.rs | 10 +-
.../quic_config/quic_connection_string_options.rs | 23 +-
.../configuration/tcp_config/tcp_client_config.rs | 6 +-
.../tcp_config/tcp_client_config_builder.rs | 14 +-
.../tcp_config/tcp_client_reconnection_config.rs | 46 +-
.../tcp_config/tcp_connection_string_options.rs | 23 +-
.../websocket_config/websocket_client_config.rs | 8 +-
.../websocket_client_config_builder.rs | 14 +-
.../websocket_client_reconnection_config.rs | 18 +-
.../websocket_connection_string_options.rs | 18 +-
core/common/src/types/identifier/mod.rs | 12 +
core/connectors/runtime/src/main.rs | 2 +
core/connectors/runtime/src/manager/source.rs | 3 +-
core/connectors/runtime/src/source.rs | 278 +-
core/connectors/sdk/README.md | 2 +
core/consensus/src/client_table.rs | 56 +-
core/consensus/src/plane_helpers.rs | 14 +-
.../tests/cluster/client_table_restart.rs | 48 +-
.../tests/cluster/failover_client_continuity.rs | 62 +-
.../tests/cluster/fast_primary_rejoin.rs | 28 +-
.../tests/cluster/partition_primary_routing.rs | 329 +-
.../data_integrity/verify_after_server_restart.rs | 8 +-
.../verify_consumer_group_partition_assignment.rs | 4 +
.../server/scenarios/authentication_scenario.rs | 37 +-
.../scenarios/reconnect_after_restart_scenario.rs | 1 -
.../stale_client_consumer_group_scenario.rs | 63 +-
core/integration/tests/server/unknown_code_vsr.rs | 22 +-
core/metadata/src/impls/metadata.rs | 414 +-
core/metadata/src/stm/user.rs | 2 +-
core/partitions/src/iggy_partition.rs | 13 +-
core/sdk/README.md | 69 +-
core/sdk/src/binary/mod.rs | 190 +
core/sdk/src/client_provider.rs | 3 +
core/sdk/src/client_wrappers/binary_client.rs | 17 -
core/sdk/src/client_wrappers/client_wrapper.rs | 61 +
core/sdk/src/client_wrappers/connection_info.rs | 6 +-
core/sdk/src/clients/binary_cluster.rs | 2 +-
core/sdk/src/clients/binary_consumer_group.rs | 38 +-
core/sdk/src/clients/binary_consumer_offset.rs | 24 +-
core/sdk/src/clients/binary_message.rs | 39 +-
core/sdk/src/clients/binary_partitions.rs | 12 +-
.../src/clients/binary_personal_access_tokens.rs | 54 +-
core/sdk/src/clients/binary_segments.rs | 6 +-
core/sdk/src/clients/binary_streams.rs | 14 +-
core/sdk/src/clients/binary_system.rs | 18 +-
core/sdk/src/clients/binary_topics.rs | 26 +-
core/sdk/src/clients/binary_users.rs | 71 +-
core/sdk/src/clients/client.rs | 166 +-
core/sdk/src/clients/client_builder.rs | 22 +-
core/sdk/src/clients/consumer.rs | 959 ++++-
core/sdk/src/clients/mod.rs | 48 +-
core/sdk/src/clients/producer.rs | 790 ++--
core/sdk/src/clients/producer_builder.rs | 22 +-
core/sdk/src/clients/producer_config.rs | 2 +-
core/sdk/src/clients/producer_error_callback.rs | 6 +
core/sdk/src/driver.rs | 1175 +++++-
core/sdk/src/driver/poll_router.rs | 1572 --------
core/sdk/src/driver/route_cache.rs | 50 +
core/sdk/src/leader_aware.rs | 518 ---
core/sdk/src/lib.rs | 1 -
core/sdk/src/links/connect.rs | 244 +-
core/sdk/src/links/dial.rs | 180 +-
core/sdk/src/links/fake_cluster.rs | 169 +-
core/sdk/src/links/mod.rs | 132 +-
core/sdk/src/links/quic.rs | 32 +-
core/sdk/src/links/replicas.rs | 640 ++-
core/sdk/src/prelude.rs | 18 +-
core/sdk/src/quic/quic_client.rs | 2094 +---------
core/sdk/src/session_owner.rs | 119 +-
core/sdk/src/session_owner/lanes.rs | 640 ++-
core/sdk/src/session_owner/pending.rs | 151 +
.../stream_builder/build/build_iggy_producer.rs | 3 -
.../stream_builder/config/config_iggy_producer.rs | 42 +-
core/sdk/src/tcp/tcp_client.rs | 4196 +++-----------------
core/sdk/src/vsr.rs | 519 +--
core/sdk/src/websocket/websocket_client.rs | 2436 +-----------
core/server/README.md | 15 +-
core/server/src/boot/listeners.rs | 1 -
core/server/src/boot/mod.rs | 4 +-
core/server/src/boot/recovery.rs | 1 -
core/server/src/dispatch/authz.rs | 16 +-
core/server/src/dispatch/failure.rs | 3 -
core/server/src/dispatch/host.rs | 4 -
core/server/src/dispatch/mod.rs | 311 +-
core/server/src/dispatch/partition.rs | 461 ++-
core/server/src/dispatch/reads.rs | 149 +-
core/server/src/dispatch/submit.rs | 2 +-
core/server/src/http.rs | 2 -
core/server/src/http/handlers.rs | 26 +-
core/server/src/http/reads.rs | 92 +-
core/server/src/http/state.rs | 4 -
core/server/src/http/submit.rs | 23 +-
core/server/src/partition_reconciler.rs | 11 +-
core/server/src/pat.rs | 137 +-
core/server/src/reply_frame.rs | 45 +-
core/server/src/rewrite.rs | 42 +-
core/shard/src/lib.rs | 5 +-
core/shard/src/poll.rs | 26 +-
core/shard/src/poll/completion_tests.rs | 110 +-
core/simulator/src/replica.rs | 6 +-
core/simulator/src/workload/mod.rs | 9 +
examples/go/go.mod | 1 -
examples/go/go.sum | 2 -
examples/python/high-level/background_producer.py | 2 -
examples/python/high-level/producer.py | 2 -
.../stream-builder/stream-producer-config/main.rs | 5 -
foreign/cpp/README.md | 74 +
foreign/cpp/include/iggy.hpp | 133 +-
foreign/cpp/src/client.cpp | 114 +-
foreign/cpp/src/client.rs | 235 +-
foreign/cpp/src/lib.rs | 82 +-
foreign/cpp/tests/e2e/client.cpp | 304 +-
foreign/cpp/tests/e2e/consumer_group.cpp | 100 +-
foreign/cpp/tests/e2e/message.cpp | 401 +-
foreign/cpp/tests/e2e/stream.cpp | 6 +-
foreign/cpp/tests/e2e/test_helpers.hpp | 37 +-
foreign/cpp/tests/e2e/topic.cpp | 10 +-
foreign/cpp/tests/unit/unit_tests.cpp | 63 +
.../StepDefinitions/LeaderRedirectionSteps.cs | 21 +-
.../Iggy_SDK.Tests.Integration/HeartbeatTests.cs | 34 +-
.../IggyTlsConnectionTests.cs | 9 +-
.../IggyTypedConsumerTests.cs | 20 +-
.../Iggy_SDK/Configuration/ConnectionString.cs | 26 +-
.../Configuration/IggyClientConfigurator.cs | 34 +-
.../Iggy_SDK/Configuration/ReconnectionSettings.cs | 4 +-
.../Iggy_SDK/Consumers/IggyConsumer.Rented.cs | 4 +-
foreign/csharp/Iggy_SDK/Consumers/IggyConsumer.cs | 79 +-
.../Exceptions/IggyInvalidStatusCodeException.cs | 3 +
.../Iggy_SDK/Exceptions/VsrLaneBlockedException.cs | 15 +-
.../Exceptions/VsrOperationNotRetainedException.cs | 24 +-
.../VsrRequestOutcomeUnknownException.cs | 8 +-
.../Exceptions/VsrSessionEvictedException.cs | 5 +-
foreign/csharp/Iggy_SDK/IggyClient/IIggyClient.cs | 26 +
.../TcpMessageStream.PollRouting.cs | 796 ++--
.../TcpMessageStream.ReplicaLinks.cs | 549 +++
.../Implementations/TcpMessageStream.Vsr.cs | 573 +--
.../IggyClient/Implementations/TcpMessageStream.cs | 587 +--
.../Publishers/BackgroundMessageProcessor.cs | 80 +-
foreign/csharp/Iggy_SDK/Utils/CommandCodes.cs | 5 +-
foreign/csharp/Iggy_SDK/Vsr/ConsensusSession.cs | 12 +-
.../Iggy_SDK/Vsr/ConsumerGroupClientState.cs | 3 +-
foreign/csharp/Iggy_SDK/Vsr/MutationLanes.cs | 466 +++
foreign/csharp/Iggy_SDK/Vsr/VsrConnection.cs | 630 +--
foreign/csharp/Iggy_SDK/Vsr/VsrError.cs | 5 +
foreign/csharp/Iggy_SDK/Vsr/VsrHeader.cs | 11 +
foreign/csharp/Iggy_SDK/Vsr/VsrOperation.cs | 4 +-
foreign/csharp/Iggy_SDK/Vsr/VsrReplyDecoder.cs | 15 +-
.../ClientTests/ConnectionStringTests.cs | 72 +
.../ConsumerTests/PartitionIncarnationTests.cs | 322 ++
.../ConsumerTests/RentedConsumerTests.cs | 83 +
.../Iggy_SDK_Tests/UtilityTests/SendUnitTests.cs | 175 +
.../VsrTests/ConsensusSessionTests.cs | 14 +-
.../VsrTests/EndpointFailoverTests.cs | 714 +++-
foreign/csharp/Iggy_SDK_Tests/VsrTests/MockNode.cs | 55 +-
.../Iggy_SDK_Tests/VsrTests/MutationLaneTests.cs | 407 ++
.../Iggy_SDK_Tests/VsrTests/NativeRecoveryTests.cs | 1166 ++++++
.../Iggy_SDK_Tests/VsrTests/PrimaryPollingTests.cs | 1212 +++++-
.../Iggy_SDK_Tests/VsrTests/ReplicaLinkTests.cs | 298 ++
.../Iggy_SDK_Tests/VsrTests/VsrHeaderTests.cs | 2 +-
.../VsrTests/VsrMultiplexingTests.cs | 324 ++
.../VsrTests/VsrReplyDecoderTests.cs | 58 +
foreign/csharp/README.md | 113 +-
foreign/go/README.md | 116 +-
foreign/go/client/iggy_client.go | 60 +-
foreign/go/client/iggy_client_test.go | 15 +-
foreign/go/client/tcp/cluster.go | 60 +-
foreign/go/client/tcp/tcp_connect_test.go | 311 +-
foreign/go/client/tcp/tcp_core.go | 1370 +------
foreign/go/client/tcp/tcp_core_review_test.go | 52 +-
foreign/go/client/tcp/tcp_core_test.go | 282 +-
foreign/go/client/tcp/tcp_driver.go | 577 +++
foreign/go/client/tcp/tcp_driver_test.go | 730 ++++
foreign/go/client/tcp/tcp_failover_test.go | 579 +--
foreign/go/client/tcp/tcp_group_polling.go | 15 +-
foreign/go/client/tcp/tcp_group_polling_test.go | 70 +
foreign/go/client/tcp/tcp_link.go | 232 ++
foreign/go/client/tcp/tcp_link_test.go | 237 ++
foreign/go/client/tcp/tcp_messaging.go | 59 +-
foreign/go/client/tcp/tcp_pending.go | 407 ++
foreign/go/client/tcp/tcp_poll_routing.go | 637 +--
foreign/go/client/tcp/tcp_poll_routing_test.go | 700 ++--
foreign/go/client/tcp/tcp_replicas.go | 581 +++
foreign/go/client/tcp/tcp_replicas_test.go | 606 +++
.../go/client/tcp/tcp_session_credentials_test.go | 201 +
foreign/go/client/tcp/tcp_session_management.go | 616 ++-
foreign/go/client/tcp/tcp_testing_test.go | 118 +-
foreign/go/client/tcp/tcp_topic_cache.go | 14 +
foreign/go/client/tcp/tcp_topic_cache_test.go | 88 +-
foreign/go/client/tcp/tcp_user_management.go | 73 +-
foreign/go/contracts/client.go | 20 +-
foreign/go/errors/errors.yaml | 18 +
foreign/go/errors/errors_gen.go | 57 +
foreign/go/go.mod | 1 -
foreign/go/go.sum | 2 -
foreign/go/internal/command/code.go | 104 +-
foreign/go/internal/vsr/envelope.go | 21 +-
foreign/go/internal/vsr/envelope_test.go | 8 +
foreign/go/internal/vsr/header.go | 29 +-
foreign/go/internal/vsr/reply.go | 56 +
foreign/go/internal/vsr/reply_test.go | 56 +
foreign/go/internal/vsr/session.go | 7 +-
foreign/go/internal/vsr/session_test.go | 8 +-
foreign/java/README.md | 89 +-
.../iggy/client/async/tcp/AsyncIggyTcpClient.java | 528 ++-
.../async/tcp/AsyncIggyTcpClientBuilder.java | 28 +-
.../iggy/client/async/tcp/AsyncTcpConnection.java | 786 +++-
.../client/async/tcp/ConsumerGroupsTcpClient.java | 53 +-
.../client/async/tcp/ConsumerOffsetsTcpClient.java | 11 +-
.../iggy/client/async/tcp/LeaderAwareness.java | 22 +-
.../iggy/client/async/tcp/LoginRoutingHook.java | 9 +-
.../iggy/client/async/tcp/MessagesTcpClient.java | 253 +-
.../iggy/client/async/tcp/PartitionsTcpClient.java | 22 +-
.../async/tcp/PersonalAccessTokensTcpClient.java | 25 +-
.../apache/iggy/client/async/tcp/PollRouter.java | 971 +++--
.../iggy/client/async/tcp/StreamsTcpClient.java | 43 +-
.../iggy/client/async/tcp/SystemTcpClient.java | 49 +-
.../iggy/client/async/tcp/TopicsTcpClient.java | 68 +-
.../iggy/client/async/tcp/UsersTcpClient.java | 39 +-
.../client/async/tcp/vsr/ConsensusSession.java | 541 ++-
.../iggy/client/async/tcp/vsr/VsrHeaders.java | 7 +
.../iggy/client/async/tcp/vsr/VsrOperation.java | 2 +-
.../client/async/tcp/vsr/VsrRequestEncoder.java | 6 +-
.../client/async/tcp/vsr/VsrResponseHandler.java | 196 +-
.../iggy/client/blocking/tcp/IggyTcpClient.java | 18 +
.../client/blocking/tcp/IggyTcpClientBuilder.java | 12 +-
.../java/org/apache/iggy/config/RetryPolicy.java | 10 +-
.../org/apache/iggy/exception/IggyErrorCode.java | 3 +
.../iggy/exception/IggyOperationException.java} | 30 +-
.../java/org/apache/iggy/serde/CommandCode.java | 7 +-
.../apache/iggy/client/BaseIntegrationTest.java | 6 +-
.../AsyncIggyTcpClientEndpointFailoverTest.java | 1079 ++++-
.../tcp/AsyncIggyTcpClientEventLoopGroupTest.java | 4 +-
.../tcp/AsyncIggyTcpClientLoginRoutingTest.java | 81 +-
.../AsyncIggyTcpClientPartitionContextTest.java | 56 +-
.../tcp/AsyncIggyTcpClientRawRequestTest.java | 238 +-
.../async/tcp/AsyncIggyTcpClientRecoveryTest.java | 1473 +++++++
.../AsyncIggyTcpClientSendContextCacheTest.java | 138 +-
.../AsyncIggyTcpClientTransientFailoverTest.java | 196 +-
.../tcp/AsyncTcpConnectionConcurrencyTest.java | 274 +-
.../tcp/AsyncTcpConnectionLifecycleBusyTest.java | 93 +-
.../tcp/AsyncTcpConnectionRequestTimeoutTest.java | 89 +-
.../client/async/tcp/LoginRoutingHookTest.java | 4 +-
.../iggy/client/async/tcp/PollRouterTest.java | 431 +-
.../client/async/tcp/vsr/ConsensusSessionTest.java | 401 ++
.../async/tcp/vsr/VsrRequestEncoderTest.java | 7 +-
.../async/tcp/vsr/VsrResponseHandlerTest.java | 163 +-
.../client/blocking/tcp/UsersTcpClientTest.java | 12 +
foreign/node/README.md | 154 +-
foreign/node/package-lock.json | 10 -
foreign/node/package.json | 1 -
foreign/node/src/client.e2e.ts | 8 +-
foreign/node/src/client/client.config.test.ts | 17 +-
foreign/node/src/client/client.config.ts | 16 +-
.../src/client/client.connection-string.test.ts | 50 +
.../node/src/client/client.connection-string.ts | 21 +-
foreign/node/src/client/client.connection.test.ts | 1145 ++----
foreign/node/src/client/client.connection.ts | 736 +---
foreign/node/src/client/client.operation.test.ts | 265 ++
foreign/node/src/client/client.operation.ts | 414 ++
foreign/node/src/client/client.socket.test.ts | 3065 +++++++++-----
foreign/node/src/client/client.socket.ts | 2050 ++++------
foreign/node/src/client/client.ts | 124 +-
foreign/node/src/client/client.type.ts | 63 +-
foreign/node/src/e2e/tcp.consumer-stream.e2e.ts | 4 +
foreign/node/src/e2e/tls.system.e2e.ts | 27 +-
foreign/node/src/stream/consumer-stream.ts | 85 +-
foreign/node/src/wire/command-set.ts | 21 +-
foreign/node/src/wire/command.code.ts | 5 +-
foreign/node/src/wire/error.utils.ts | 2 +
.../node/src/wire/message/poll-messages.command.ts | 3 +-
.../node/src/wire/message/send-messages.command.ts | 2 +-
foreign/node/src/wire/vsr/header.ts | 16 +-
foreign/node/src/wire/vsr/index.ts | 13 +-
foreign/node/src/wire/vsr/reply.ts | 46 +-
foreign/node/src/wire/vsr/session.test.ts | 12 +
foreign/node/src/wire/vsr/session.ts | 15 +-
foreign/node/src/wire/vsr/vsr.test.ts | 56 +-
foreign/node/tsconfig.json | 1 +
foreign/php/README.md | 24 +
foreign/php/iggy-php.stubs.php | 78 +-
foreign/php/src/client.rs | 193 +-
foreign/php/src/error.rs | 80 +-
foreign/php/src/lib.rs | 6 +-
foreign/php/tests/RawCommandTest.php | 141 +
foreign/php/tests/bootstrap.php | 4 +-
foreign/python/README.md | 67 +-
foreign/python/apache_iggy.pyi | 157 +-
foreign/python/src/client.rs | 173 +-
foreign/python/src/config.rs | 180 +-
foreign/python/src/consumer.rs | 15 +-
foreign/python/src/lib.rs | 8 +-
foreign/python/src/producer.rs | 219 +-
foreign/python/tests/test_client_config.py | 29 +
foreign/python/tests/test_producer.py | 89 +-
foreign/python/tests/test_quic_config.py | 30 +-
foreign/python/tests/test_raw_command.py | 50 +-
foreign/swift/Sources/Iggy/Client/ClientCore.swift | 18 +-
.../Sources/Iggy/Client/IggyClient+Messages.swift | 114 +-
foreign/swift/Sources/Iggy/Client/IggyClient.swift | 13 +-
foreign/swift/Sources/Iggy/Client/PollRouter.swift | 138 +-
.../swift/Sources/Iggy/Protocol/CommandCode.swift | 8 +-
.../Sources/Iggy/Protocol/ConsensusSession.swift | 14 +-
.../swift/Sources/Iggy/Protocol/Responses.swift | 43 +-
foreign/swift/Sources/Iggy/Protocol/VSRFrame.swift | 12 +-
.../Tests/IggyTests/ClientTransportTests.swift | 16 +-
foreign/swift/Tests/IggyTests/Fixtures/golden.json | 2 +-
foreign/swift/Tests/IggyTests/MessagingTests.swift | 220 +-
foreign/swift/Tests/IggyTests/ProtocolTests.swift | 25 +-
.../Tests/IggyTests/ResponseVectorTests.swift | 14 +-
.../Tests/IggyTests/Support/FakeVSRServer.swift | 45 +-
.../swift/Tests/IggyTests/WireVectorTests.swift | 3 +
foreign/swift/Tools/golden-vectors/src/main.rs | 37 +-
.../kafka/tests/bridge_iggy_integration_tests.rs | 34 +-
338 files changed, 36274 insertions(+), 24747 deletions(-)
diff --git a/.github/actions/cpp-bazel/pre-merge/action.yml b/.github/actions/cpp-bazel/pre-merge/action.yml
index 8b9ab0507..ebfc34830 100644
--- a/.github/actions/cpp-bazel/pre-merge/action.yml
+++ b/.github/actions/cpp-bazel/pre-merge/action.yml
@@ -89,11 +89,12 @@ runs:
with:
bin: target/debug/iggy-server
- - name: Test with coverage
+ - name: Test Rust bridge and C++ coverage
if: inputs.task == 'test'
shell: bash
run: |
cd foreign/cpp
+ cargo test
../../scripts/ci/cpp-coverage.sh
- name: Stop server after tests
diff --git a/bdd/cpp/features/step_definitions/background_steps.cpp b/bdd/cpp/features/step_definitions/background_steps.cpp
index 33fcb008e..55cfa0935 100644
--- a/bdd/cpp/features/step_definitions/background_steps.cpp
+++ b/bdd/cpp/features/step_definitions/background_steps.cpp
@@ -58,10 +58,11 @@ GIVEN("^I have a running Iggy server$") {
}
GIVEN("^I am authenticated as the root user$") {
+ iggy::ffi::ErrorInfo error_info{};
cucumber::ScenarioScope<bdd::GlobalContext> context;
ASSERT_NE(context->client, nullptr);
const std::string username = required_env("IGGY_ROOT_USERNAME");
const std::string password = required_env("IGGY_ROOT_PASSWORD");
- context->client->login_user(username, password);
+ context->client->login_user(username, password, error_info);
}
diff --git a/bdd/cpp/features/step_definitions/messaging_steps.cpp b/bdd/cpp/features/step_definitions/messaging_steps.cpp
index f29b74b9d..ed894441d 100644
--- a/bdd/cpp/features/step_definitions/messaging_steps.cpp
+++ b/bdd/cpp/features/step_definitions/messaging_steps.cpp
@@ -42,10 +42,11 @@ GIVEN("^I have no streams in the system$") {
}
WHEN("^I create a stream with name \"([^\"]{1,255})\"$") {
+ iggy::ffi::ErrorInfo error_info{};
REGEX_PARAM(std::string, name);
cucumber::ScenarioScope<bdd::GlobalContext> context;
- context->client->create_stream(name);
+ context->client->create_stream(name, error_info);
}
THEN("^the stream should be created successfully$") {
@@ -64,6 +65,7 @@ THEN("^the stream should have name \"([^\"]{1,255})\"$") {
}
WHEN("^I create a topic with name \"([^\"]{1,255})\" in stream ([0-9]+) with ([0-9]+) partitions$") {
+ iggy::ffi::ErrorInfo error_info{};
REGEX_PARAM(std::string, topic_name);
REGEX_PARAM(int, stream_id);
REGEX_PARAM(int, partitions_count);
@@ -81,7 +83,7 @@ WHEN("^I create a topic with name \"([^\"]{1,255})\" in stream ([0-9]+) with ([0
opts.max_topic_size = "server_default";
context->client->create_topic(bdd::make_numeric_identifier(static_cast<std::uint32_t>(stream_id)), topic_name,
- std::move(opts));
+ std::move(opts), error_info);
}
THEN("^the topic should be created successfully$") {
@@ -110,6 +112,7 @@ THEN("^the topic should have ([0-9]+) partitions$") {
}
WHEN("^I send ([0-9]+) messages to stream ([0-9]+), topic ([0-9]+), partition ([0-9]+)$") {
+ iggy::ffi::ErrorInfo error_info{};
REGEX_PARAM(int, message_count);
REGEX_PARAM(int, stream_id);
REGEX_PARAM(int, topic_id);
@@ -129,7 +132,7 @@ WHEN("^I send ([0-9]+) messages to stream ([0-9]+), topic ([0-9]+), partition ([
context->client->send_messages(bdd::make_numeric_identifier(static_cast<std::uint32_t>(stream_id)),
bdd::make_numeric_identifier(static_cast<std::uint32_t>(topic_id)), "partition_id",
bdd::partition_id_bytes(static_cast<std::uint32_t>(partition_id)),
- std::move(messages));
+ std::move(messages), error_info);
context->last_sent_payload = bdd::expected_payload(static_cast<std::uint32_t>(message_count - 1));
context->last_sent_id_lo = static_cast<std::uint64_t>(message_count);
@@ -141,6 +144,7 @@ THEN("^all messages should be sent successfully$") {
}
WHEN("^I poll messages from stream ([0-9]+), topic ([0-9]+), partition ([0-9]+) starting from offset ([0-9]+)$") {
+ iggy::ffi::ErrorInfo error_info{};
REGEX_PARAM(int, stream_id);
REGEX_PARAM(int, topic_id);
REGEX_PARAM(int, partition_id);
@@ -150,7 +154,8 @@ WHEN("^I poll messages from stream ([0-9]+), topic ([0-9]+), partition ([0-9]+)
const auto polled = context->client->poll_messages(
bdd::make_numeric_identifier(static_cast<std::uint32_t>(stream_id)),
bdd::make_numeric_identifier(static_cast<std::uint32_t>(topic_id)), static_cast<std::uint32_t>(partition_id),
- "consumer", bdd::make_numeric_identifier(1), "offset", static_cast<std::uint64_t>(offset), 100, false);
+ "consumer", bdd::make_numeric_identifier(1), "offset", static_cast<std::uint64_t>(offset), 100, false,
+ error_info);
context->polled.count = polled.count;
context->polled.offsets.clear();
diff --git a/bdd/cpp/features/step_definitions/raw_command_steps.cpp b/bdd/cpp/features/step_definitions/raw_command_steps.cpp
index f7693b083..395775456 100644
--- a/bdd/cpp/features/step_definitions/raw_command_steps.cpp
+++ b/bdd/cpp/features/step_definitions/raw_command_steps.cpp
@@ -36,7 +36,8 @@ WHEN("^I send a raw command with code ([0-9]+) and an empty payload$") {
context->raw_response.clear();
context->raw_error.clear();
try {
- const auto response = context->client->send_binary_request(code, rust::Vec<std::uint8_t>());
+ iggy::ffi::ErrorInfo error_info{};
+ const auto response = context->client->send_binary_request(code, rust::Vec<std::uint8_t>(), error_info);
context->raw_response.assign(response.begin(), response.end());
} catch (const std::exception &error) {
context->raw_error = error.what();
diff --git a/bdd/go/go.mod b/bdd/go/go.mod
index cd3f31a38..66edac7eb 100644
--- a/bdd/go/go.mod
+++ b/bdd/go/go.mod
@@ -14,7 +14,6 @@ require (
require (
github.com/Masterminds/semver/v3 v3.4.0 // indirect
- github.com/avast/retry-go/v5 v5.0.0 // indirect
github.com/cucumber/gherkin/go/v42 v42.0.0 // indirect
github.com/cucumber/messages/go/v34 v34.2.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
diff --git a/bdd/go/go.sum b/bdd/go/go.sum
index db64f6a15..213543b6a 100644
--- a/bdd/go/go.sum
+++ b/bdd/go/go.sum
@@ -1,7 +1,5 @@
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
-github.com/avast/retry-go/v5 v5.0.0 h1:kf1Qc2UsTZ4qq8elDymqfbISvkyMuhgRxuJqX2NHP7k=
-github.com/avast/retry-go/v5 v5.0.0/go.mod h1://d+usmKWio1agtZfS1H/ltTqwtIfBnRq9zEwjc3eH8=
github.com/cucumber/gherkin/go/v42 v42.0.0 h1:Ulh3E2awUUSSja+wonP/IOQ+ycmiZwZbgmzqk5H8JNI=
github.com/cucumber/gherkin/go/v42 v42.0.0/go.mod h1:CsaumaO2dR9XvBc6ZyiGLMhWCKtTRDxgoxqJigSjSSg=
github.com/cucumber/godog v0.16.0 h1:ezQbgItuWqZrjPUQwLJ3muwIlvzXBOfZso5QZfG7efE=
diff --git a/core/binary_protocol/src/codes.rs b/core/binary_protocol/src/codes.rs
index 1f136fb33..4c1626696 100644
--- a/core/binary_protocol/src/codes.rs
+++ b/core/binary_protocol/src/codes.rs
@@ -55,8 +55,8 @@ pub const LOGIN_WITH_PERSONAL_ACCESS_TOKEN_CODE: u32 = 44;
pub const POLL_MESSAGES_CODE: u32 = 100;
pub const SEND_MESSAGES_CODE: u32 = 101;
// 102 was FLUSH_UNSAVED_BUFFER. Never reuse it: older clients still send it.
-pub const GET_POLL_ROUTING_CODE: u32 = 103;
-pub const POLL_MESSAGES_ON_PRIMARY_CODE: u32 = 104;
+// 103 was GET_POLL_ROUTING. Never reuse it: released clients still send it.
+// 104 was POLL_MESSAGES_ON_PRIMARY. Never reuse it: released clients still send it.
/// The route of one partition: its incarnation, the group view and the primary
/// of that view. Sends, polls and consumer offsets all route with it.
pub const GET_PARTITION_ROUTE_CODE: u32 = 105;
@@ -65,9 +65,7 @@ pub const GET_PARTITION_ROUTE_CODE: u32 = 105;
pub const GET_CONSUMER_OFFSET_CODE: u32 = 120;
pub const STORE_CONSUMER_OFFSET_CODE: u32 = 121;
pub const DELETE_CONSUMER_OFFSET_CODE: u32 = 122;
-/// Primary and parent session for offset writes; uses `GetConsumerOffsetRequest`
-/// and `PollRoutingResponse`, with the offset ownership fence (revocations may drain).
-pub const GET_CONSUMER_OFFSET_ROUTING_CODE: u32 = 123;
+// 123 was GET_CONSUMER_OFFSET_ROUTING. Never reuse it: released clients still send it.
// -- Streams --
pub const GET_STREAM_CODE: u32 = 200;
@@ -116,7 +114,7 @@ pub const fn command_name(code: u32) -> Result<&'static str, WireError> {
mod tests {
use super::*;
- const RETIRED_CODES: &[u32] = &[14, 102, 205, 305];
+ const RETIRED_CODES: &[u32] = &[14, 102, 103, 104, 123, 205, 305];
const ALL_CODES: &[u32] = &[
PING_CODE,
@@ -144,14 +142,11 @@ mod tests {
DELETE_PERSONAL_ACCESS_TOKEN_CODE,
LOGIN_WITH_PERSONAL_ACCESS_TOKEN_CODE,
POLL_MESSAGES_CODE,
- GET_POLL_ROUTING_CODE,
- POLL_MESSAGES_ON_PRIMARY_CODE,
GET_PARTITION_ROUTE_CODE,
SEND_MESSAGES_CODE,
GET_CONSUMER_OFFSET_CODE,
STORE_CONSUMER_OFFSET_CODE,
DELETE_CONSUMER_OFFSET_CODE,
- GET_CONSUMER_OFFSET_ROUTING_CODE,
GET_STREAM_CODE,
GET_STREAMS_CODE,
CREATE_STREAM_CODE,
diff --git a/core/binary_protocol/src/consensus/header.rs b/core/binary_protocol/src/consensus/header.rs
index 8e583ab7c..cf7bebef3 100644
--- a/core/binary_protocol/src/consensus/header.rs
+++ b/core/binary_protocol/src/consensus/header.rs
@@ -659,6 +659,8 @@ pub struct ReplyHeader {
/// Carved from `reserved` like `user_id` in `RequestHeader` / `PrepareHeader`;
/// no existing field offset moves and `validate` does not inspect it.
pub status: u32,
+ /// Byte 220 is [`Self::COMMITTED_RESULT`] only for a final committed result.
+ /// Zero and unknown values carry no commitment proof.
pub reserved: [u8; 4],
/// Echoes the request, and the plain poll reply overwrites it with the
/// served incarnation. Clients read the served context from the poll
@@ -668,6 +670,7 @@ pub struct ReplyHeader {
}
const _: () = {
assert!(size_of::<ReplyHeader>() == HEADER_SIZE);
+ assert!(offset_of!(ReplyHeader, reserved) == 220);
assert!(
offset_of!(ReplyHeader, request_checksum)
== offset_of!(ReplyHeader, reserved_frame) + size_of::<[u8; 66]>()
@@ -711,10 +714,13 @@ impl Default for ReplyHeader {
}
impl ReplyHeader {
+ /// Wire marker for a final committed result, stored in `reserved[0]`.
+ pub const COMMITTED_RESULT: u8 = 1;
+
/// The reply to a committed prepare.
///
- /// Every field comes from the prepare or is zero, never from the primary's
- /// live state, so a cached reply replayed by any replica carries the same
+ /// Fields come from the prepare and fixed protocol values, never from the
+ /// primary's live state, so a cached reply replayed by any replica carries the same
/// bytes for `(client, request)`: `view` is the commit-time view and
/// `replica` the original primary's id. `commit` is the prepare's `op`, not
/// `commit_max`, because it drives the `ClientTable` eviction order and
@@ -735,6 +741,7 @@ impl ReplyHeader {
timestamp: prepare_header.timestamp,
request: prepare_header.request,
operation: prepare_header.operation,
+ reserved: [Self::COMMITTED_RESULT, 0, 0, 0],
partition_incarnation: prepare_header.partition_incarnation,
..Self::default()
}
@@ -769,6 +776,15 @@ impl ReplyHeader {
..Self::default()
}
}
+
+ /// Header evidence of a final committed result. The caller must also validate
+ /// the result body and its correlation with the original request.
+ #[must_use]
+ pub fn has_committed_result(&self) -> bool {
+ self.command == Command::Reply
+ && self.status == 0
+ && self.reserved[0] == Self::COMMITTED_RESULT
+ }
}
impl ConsensusHeader for ReplyHeader {
@@ -3407,6 +3423,7 @@ mod tests {
use std::mem::offset_of;
assert_eq!(size_of::<ReplyHeader>(), HEADER_SIZE);
assert_eq!(offset_of!(ReplyHeader, status), 216);
+ assert_eq!(offset_of!(ReplyHeader, reserved), 220);
assert_eq!(
offset_of!(ReplyHeader, reserved) + size_of::<[u8; 36]>(),
HEADER_SIZE
@@ -3540,11 +3557,30 @@ mod tests {
assert_eq!(reply.context, 0);
assert_eq!(reply.operation_padding, [0; 7]);
assert_eq!(reply.status, 0);
- assert_eq!(reply.reserved, [0; 4]);
+ assert_eq!(reply.reserved, [ReplyHeader::COMMITTED_RESULT, 0, 0, 0]);
+ assert!(reply.has_committed_result());
assert_eq!(reply.reserved_tail, [0; 24]);
assert_eq!(reply.partition_incarnation, 19);
}
+ #[test]
+ fn given_unknown_marker_or_denial_when_reading_reply_should_not_prove_commit() {
+ let mut reply = ReplyHeader::from_prepare(
+ &PrepareHeader::default(),
+ u32::try_from(HEADER_SIZE).unwrap(),
+ );
+ for marker in [0, 2, u8::MAX] {
+ reply.reserved[0] = marker;
+ assert!(!reply.has_committed_result());
+ }
+ reply.reserved[0] = ReplyHeader::COMMITTED_RESULT;
+ reply.status = 1;
+ assert!(!reply.has_committed_result());
+ reply.status = 0;
+ reply.command = Command::Eviction;
+ assert!(!reply.has_committed_result());
+ }
+
#[test]
fn reply_echoing_copies_the_frame_and_request_identity_only() {
let request = RoutedRequestHeader {
@@ -3595,6 +3631,7 @@ mod tests {
assert_eq!(reply.context, 0);
assert_eq!(reply.operation_padding, [0; 7]);
assert_eq!(reply.reserved, [0; 4]);
+ assert!(!reply.has_committed_result());
assert_eq!(reply.reserved_tail, [0; 24]);
assert_eq!(reply.partition_incarnation, 19);
}
diff --git a/core/binary_protocol/src/consensus/reply_result.rs b/core/binary_protocol/src/consensus/reply_result.rs
index c28cb532a..0135eca97 100644
--- a/core/binary_protocol/src/consensus/reply_result.rs
+++ b/core/binary_protocol/src/consensus/reply_result.rs
@@ -59,8 +59,8 @@ fn read_u32(reply_body: &[u8], offset: usize) -> Option<u32> {
/// caller treats `None` as malformed, never Ok ("classify never guesses").
#[must_use]
pub fn result_code(reply_body: &[u8]) -> Option<u32> {
- let count = read_u32(reply_body, 0)?;
- if count == 0 {
+ let section_len = result_section_len(reply_body)?;
+ if section_len == RESULT_COUNT_LEN {
Some(0)
} else {
// First entry's `result` sits past the count and its leading index; a
@@ -80,8 +80,10 @@ pub fn result_code(reply_body: &[u8]) -> Option<u32> {
/// guessed offset.
#[must_use]
pub fn result_section_len(reply_body: &[u8]) -> Option<usize> {
- let count = read_u32(reply_body, 0)? as usize;
- let len = RESULT_COUNT_LEN + count * RESULT_ENTRY_LEN;
+ let count = usize::try_from(read_u32(reply_body, 0)?).ok()?;
+ let len = count
+ .checked_mul(RESULT_ENTRY_LEN)?
+ .checked_add(RESULT_COUNT_LEN)?;
(reply_body.len() >= len).then_some(len)
}
@@ -158,4 +160,31 @@ mod tests {
assert_eq!(result_code(&[1, 0, 0, 0, 0, 0, 0, 0]), None); // result missing
assert_eq!(result_section_len(&[1, 0, 0, 0, 0, 0, 0, 0]), None);
}
+
+ #[test]
+ fn given_truncated_result_entries_when_decoding_should_not_return_the_first_error() {
+ let mut body = rejection_body(1009);
+ body[..RESULT_COUNT_LEN].copy_from_slice(&2u32.to_le_bytes());
+ for missing_tail in [0, RESULT_ENTRY_LEN - 1] {
+ let mut truncated = body.clone();
+ truncated.extend(std::iter::repeat_n(0, missing_tail));
+ assert_eq!(result_code(&truncated), None);
+ assert_eq!(result_section_len(&truncated), None);
+ }
+ body.extend_from_slice(&1u32.to_le_bytes());
+ body.extend_from_slice(&1010u32.to_le_bytes());
+ assert_eq!(result_code(&body), Some(1009));
+ assert_eq!(
+ result_section_len(&body),
+ Some(RESULT_COUNT_LEN + 2 * RESULT_ENTRY_LEN)
+ );
+ }
+
+ #[test]
+ fn given_maximum_result_count_when_body_is_short_should_reject_without_overflow() {
+ let mut body = rejection_body(1009);
+ body[..RESULT_COUNT_LEN].copy_from_slice(&u32::MAX.to_le_bytes());
+ assert_eq!(result_code(&body), None);
+ assert_eq!(result_section_len(&body), None);
+ }
}
diff --git a/core/binary_protocol/src/dispatch.rs b/core/binary_protocol/src/dispatch.rs
index d133dfec0..93be52300 100644
--- a/core/binary_protocol/src/dispatch.rs
+++ b/core/binary_protocol/src/dispatch.rs
@@ -183,9 +183,6 @@ pub const COMMAND_TABLE: &[CommandMeta] = &[
// Options catalog discovery
CommandMeta::non_replicated(DESCRIBE_OPTIONS_CODE, "options.describe"),
CommandMeta::non_replicated(BIND_SESSION_CODE, "session.bind"),
- CommandMeta::non_replicated(GET_POLL_ROUTING_CODE, "message.poll_routing"),
- CommandMeta::non_replicated(POLL_MESSAGES_ON_PRIMARY_CODE, "message.poll_primary"),
- CommandMeta::non_replicated(GET_CONSUMER_OFFSET_ROUTING_CODE, "consumer_offset.routing"),
CommandMeta::non_replicated(GET_PARTITION_ROUTE_CODE, "partition.route"),
];
@@ -247,10 +244,7 @@ pub const fn lookup_command(code: u32) -> Option<&'static CommandMeta> {
LOGIN_REGISTER_WITH_PAT_CODE => 46,
DESCRIBE_OPTIONS_CODE => 47,
BIND_SESSION_CODE => 48,
- GET_POLL_ROUTING_CODE => 49,
- POLL_MESSAGES_ON_PRIMARY_CODE => 50,
- GET_CONSUMER_OFFSET_ROUTING_CODE => 51,
- GET_PARTITION_ROUTE_CODE => 52,
+ GET_PARTITION_ROUTE_CODE => 49,
_ => return None,
};
Some(&COMMAND_TABLE[idx])
diff --git a/core/binary_protocol/src/responses/messages/mod.rs b/core/binary_protocol/src/responses/messages/mod.rs
index 24111cb44..325f878f7 100644
--- a/core/binary_protocol/src/responses/messages/mod.rs
+++ b/core/binary_protocol/src/responses/messages/mod.rs
@@ -17,10 +17,8 @@
pub mod partition_route;
pub mod poll_messages;
-pub mod poll_routing;
pub mod send_messages;
pub use partition_route::PartitionRouteResponse;
pub use poll_messages::{PollMessagesResponse, PollMessagesResponseHeader};
-pub use poll_routing::PollRoutingResponse;
pub use send_messages::{SendMessagesConfirmationResponse, SendMessagesResponse};
diff --git a/core/binary_protocol/src/responses/messages/poll_routing.rs b/core/binary_protocol/src/responses/messages/poll_routing.rs
deleted file mode 100644
index beb79565a..000000000
--- a/core/binary_protocol/src/responses/messages/poll_routing.rs
+++ /dev/null
@@ -1,104 +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::primitives::partition_history::PartitionContext;
-use crate::requests::system::SessionIdentity;
-use crate::responses::system::get_cluster_metadata::ClusterNodeResponse;
-use bytes::BytesMut;
-
-/// Primary and parent session for a poll or offset-write route query.
-///
-/// The primary is a hint: the receiving partition still checks its role before
-/// accepting consumer progress. The attachment carries the coordinator's authenticated
-/// identity and metadata floor, never credentials.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct PollRoutingResponse {
- pub consumer_session: SessionIdentity,
- pub context: PartitionContext,
- pub primary: ClusterNodeResponse,
-}
-
-impl WireEncode for PollRoutingResponse {
- fn encoded_size(&self) -> usize {
- self.consumer_session.encoded_size()
- + self.context.encoded_size()
- + self.primary.encoded_size()
- }
-
- fn encode(&self, buf: &mut BytesMut) {
- self.consumer_session.encode(buf);
- self.context.encode(buf);
- self.primary.encode(buf);
- }
-}
-
-impl WireDecode for PollRoutingResponse {
- fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> {
- let (consumer_session, consumed) = SessionIdentity::decode(buf)?;
- let (context, context_size) = PartitionContext::decode(&buf[consumed..])?;
- let (primary, node_size) = ClusterNodeResponse::decode(&buf[consumed + context_size..])?;
- Ok((
- Self {
- consumer_session,
- context,
- primary,
- },
- consumed + context_size + node_size,
- ))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn roundtrip_and_reject_truncation() {
- let response = PollRoutingResponse {
- consumer_session: SessionIdentity {
- client_id: u128::MAX,
- session: 7,
- metadata_watermark: 11,
- },
- context: PartitionContext::default(),
- primary: ClusterNodeResponse {
- replica_id: 2,
- name: "node-1".to_owned(),
- ip: "::1".to_owned(),
- tcp_port: 8090,
- quic_port: 8091,
- http_port: 0,
- websocket_port: 3000,
- role: 1,
- status: 1,
- },
- };
- let bytes = response.to_bytes();
- assert_eq!(
- PollRoutingResponse::decode(&bytes).unwrap(),
- (response, bytes.len())
- );
- for end in 0..bytes.len() {
- assert!(
- PollRoutingResponse::decode(&bytes[..end]).is_err(),
- "accepted truncation at {end}"
- );
- }
- }
-}
diff --git a/core/common/src/lib.rs b/core/common/src/lib.rs
index 71e11bf16..486a97abf 100644
--- a/core/common/src/lib.rs
+++ b/core/common/src/lib.rs
@@ -81,6 +81,10 @@ pub use iggy_binary_protocol::responses::messages::{
};
pub use traits::binary_client::BinaryClient;
pub use traits::binary_transport::BinaryTransport;
+#[doc(hidden)]
+pub use traits::binary_transport::{
+ BINARY_OPERATION_TIMEOUT, binary_operation_deadline, with_binary_deadline,
+};
pub use traits::binary_transport::{VsrSessionControl, VsrSessionSealed, decode_session_binding};
pub use traits::client::Client;
pub use traits::cluster_client::ClusterClient;
@@ -98,6 +102,8 @@ pub use traits::system_client::SystemClient;
pub use traits::topic_client::TopicClient;
pub use traits::user_client::UserClient;
pub use traits::validatable::Validatable;
+#[doc(hidden)]
+pub use traits::{BinarySendPartitioning, send_binary_messages};
pub use traits::{rust_sdk_version_info, sign_in_request};
pub use types::args::*;
pub use types::client::client_info::*;
@@ -111,6 +117,7 @@ pub use types::configuration::auth_config::credentials::*;
pub use types::configuration::http_config::http_client_config::*;
pub use types::configuration::http_config::http_client_config_builder::*;
pub use types::configuration::http_config::http_connection_string_options::*;
+pub use types::configuration::pending_operations_config::PendingOperationsConfig;
pub use types::configuration::quic_config::quic_client_config::*;
pub use types::configuration::quic_config::quic_client_config_builder::*;
pub use types::configuration::quic_config::quic_client_reconnection_config::*;
diff --git a/core/common/src/traits/binary_impls/messages.rs b/core/common/src/traits/binary_impls/messages.rs
index a91edd71c..7a7249ac7 100644
--- a/core/common/src/traits/binary_impls/messages.rs
+++ b/core/common/src/traits/binary_impls/messages.rs
@@ -16,7 +16,6 @@
// under the License.
use crate::BinaryClient;
-use crate::BinaryTransport;
use crate::traits::binary_auth::fail_if_not_authenticated;
use crate::wire_conversions::{
consumer_to_wire, identifier_to_wire, partitioning_to_wire, polling_strategy_to_wire,
@@ -25,20 +24,21 @@ use crate::{
Consumer, Identifier, IggyError, IggyMessage, MessageClient, Partitioning, PolledMessages,
PollingStrategy, SendMessagesResponse,
};
-use crate::{ConsumerKind, PartitioningKind, TopicClient, calculate_32};
+use crate::{
+ ConsumerKind, PartitioningKind, TopicClient, binary_operation_deadline, calculate_32,
+ with_binary_deadline,
+};
use bytes::{Bytes, BytesMut};
use iggy_binary_protocol::codec::WireDecode;
use iggy_binary_protocol::codec::WireEncode;
+use iggy_binary_protocol::codes::SEND_MESSAGES_CODE;
use iggy_binary_protocol::codes::SYNC_CONSUMER_GROUP_CODE;
-use iggy_binary_protocol::codes::{GET_PARTITION_ROUTE_CODE, SEND_MESSAGES_CODE};
use iggy_binary_protocol::requests::consumer_groups::SyncConsumerGroupRequest;
use iggy_binary_protocol::requests::messages::{
- GetPartitionRouteRequest, PollMessagesRequest, RawMessage, SendMessagesEncoder,
- SendMessagesHeader,
+ PollMessagesRequest, RawMessage, SendMessagesEncoder,
};
use iggy_binary_protocol::responses::consumer_groups::SyncConsumerGroupResponse;
-use iggy_binary_protocol::responses::messages::PartitionRouteResponse;
-use iggy_binary_protocol::{WireIdentifier, WirePartitioning};
+use std::borrow::Cow;
/// Max attempts to resolve a fenced consumer-group poll: one re-sync after the
/// coordinator rejects a stale assignment, then retry once.
@@ -112,10 +112,7 @@ async fn topic_partition_count<B: BinaryClient>(
stream_id: &Identifier,
topic_id: &Identifier,
) -> Result<u32, IggyError> {
- if let Some(count) = client
- .consumer_group_state()
- .partition_count(stream_id, topic_id)
- {
+ if let Some(count) = client.routed_partition_count(stream_id, topic_id) {
return Ok(count);
}
let details = TopicClient::get_topic(client, stream_id, topic_id)
@@ -124,40 +121,118 @@ async fn topic_partition_count<B: BinaryClient>(
Ok(details.partitions_count)
}
-/// Resolve `Balanced` / `MessagesKey` locally using the SDK's partition cache and cursor.
-async fn resolve_partitioning<B: BinaryClient>(
+/// A chunk keeps its selected partition while an earlier lane blocker resolves.
+/// Only a definitive missing-partition result permits one fresh selection.
+#[doc(hidden)]
+pub struct BinarySendPartitioning<'a> {
+ original: &'a Partitioning,
+ selected: Option<Cow<'a, Partitioning>>,
+ refreshed: bool,
+}
+
+impl<'a> BinarySendPartitioning<'a> {
+ pub fn new(original: &'a Partitioning) -> Self {
+ Self {
+ original,
+ selected: None,
+ refreshed: false,
+ }
+ }
+
+ pub fn original(&self) -> &Partitioning {
+ self.original
+ }
+
+ pub fn is_resolved(&self) -> bool {
+ self.selected.is_some()
+ }
+}
+
+#[doc(hidden)]
+pub async fn send_binary_messages<B: BinaryClient>(
client: &B,
stream_id: &Identifier,
topic_id: &Identifier,
- partitioning: &Partitioning,
-) -> Result<Partitioning, IggyError> {
- match partitioning.kind {
- PartitioningKind::PartitionId => Ok(partitioning.clone()),
- PartitioningKind::Balanced => {
- let count = topic_partition_count(client, stream_id, topic_id).await?;
- if count == 0 {
- return Err(IggyError::TopicIdNotFound(
- topic_id.clone(),
- stream_id.clone(),
- ));
- }
- let partition = client
- .consumer_group_state()
- .next_balanced_partition(stream_id, topic_id, count);
- Ok(Partitioning::partition_id(partition))
+ partitioning: &mut BinarySendPartitioning<'_>,
+ messages: &mut [IggyMessage],
+) -> Result<SendMessagesResponse, IggyError> {
+ with_binary_deadline(binary_operation_deadline(), async {
+ fail_if_not_authenticated(client).await?;
+ if partitioning.selected.is_none() {
+ partitioning.selected = Some(match partitioning.original.kind {
+ PartitioningKind::PartitionId => Cow::Borrowed(partitioning.original),
+ _ => {
+ let count = topic_partition_count(client, stream_id, topic_id).await?;
+ Cow::Owned(select_partition(
+ client,
+ stream_id,
+ topic_id,
+ partitioning.original,
+ count,
+ )?)
+ }
+ });
}
- PartitioningKind::MessagesKey => {
- let count = topic_partition_count(client, stream_id, topic_id).await?;
- if count == 0 {
- return Err(IggyError::TopicIdNotFound(
- topic_id.clone(),
- stream_id.clone(),
- ));
+ loop {
+ let selected = partitioning
+ .selected
+ .as_deref()
+ .ok_or(IggyError::InvalidCommand)?;
+ let payload = encode_messages(stream_id, topic_id, selected, messages)?;
+ match client
+ .send_raw_with_context(
+ SEND_MESSAGES_CODE,
+ payload,
+ crate::PartitionContext::default(),
+ )
+ .await
+ {
+ Err(IggyError::PartitionNotFound(..))
+ if !partitioning.refreshed
+ && partitioning.original.kind != PartitioningKind::PartitionId =>
+ {
+ partitioning.refreshed = true;
+ let details = TopicClient::get_topic(client, stream_id, topic_id)
+ .await?
+ .ok_or_else(|| {
+ IggyError::TopicIdNotFound(topic_id.clone(), stream_id.clone())
+ })?;
+ partitioning.selected = Some(Cow::Owned(select_partition(
+ client,
+ stream_id,
+ topic_id,
+ partitioning.original,
+ details.partitions_count,
+ )?));
+ }
+ result => return result.map(|response| committed_send_confirmations(&response)),
}
- let partition = calculate_32(&partitioning.value) % count;
- Ok(Partitioning::partition_id(partition))
}
+ })
+ .await
+}
+
+fn select_partition<B: BinaryClient>(
+ client: &B,
+ stream_id: &Identifier,
+ topic_id: &Identifier,
+ partitioning: &Partitioning,
+ count: u32,
+) -> Result<Partitioning, IggyError> {
+ if count == 0 {
+ return Err(IggyError::TopicIdNotFound(
+ topic_id.clone(),
+ stream_id.clone(),
+ ));
}
+ let partition = match partitioning.kind {
+ PartitioningKind::Balanced => client
+ .consumer_group_state()
+ .next_balanced_partition(stream_id, topic_id, count),
+ PartitioningKind::MessagesKey => calculate_32(&partitioning.value) % count,
+ PartitioningKind::PartitionId => return Err(IggyError::InvalidCommand),
+ };
+ Ok(Partitioning::partition_id(partition))
}
/// Poll a consumer group: select one of the member's assigned partitions
@@ -275,87 +350,6 @@ fn committed_send_confirmations(response: &[u8]) -> SendMessagesResponse {
})
}
-/// Raw `SendMessages` body, sent the way the typed send sends an explicit
-/// partition. `Balanced` and `MessagesKey` are resolved by the typed send from
-/// its partition cache and cursor, so a raw body with them names no partition
-/// to capture a context for.
-pub(crate) async fn send_raw_messages<B: BinaryTransport + Sync + ?Sized>(
- client: &B,
- payload: Bytes,
-) -> Result<Bytes, IggyError> {
- let (metadata_length, body) = payload
- .split_first_chunk()
- .ok_or(IggyError::InvalidCommand)?;
- let header = body
- .get(..u32::from_le_bytes(*metadata_length) as usize)
- .and_then(|metadata| SendMessagesHeader::decode_from(metadata).ok())
- .ok_or(IggyError::InvalidCommand)?;
- let WirePartitioning::PartitionId(partition_id) = header.partitioning else {
- tracing::error!(
- "Raw SendMessages needs an explicit partition id. Use MessageClient::send_messages for Balanced or MessagesKey partitioning."
- );
- return Err(IggyError::FeatureUnavailable);
- };
- let stream_id = identifier_from_wire(&header.stream_id)?;
- let topic_id = identifier_from_wire(&header.topic_id)?;
- let capture = GetPartitionRouteRequest {
- stream_id: header.stream_id,
- topic_id: header.topic_id,
- partition_id,
- };
- send_with_partition_context(client, &stream_id, &topic_id, &capture, payload).await
-}
-
-/// Send under the cached send context, or one captured from a `GetPartitionRoute` reply.
-/// A history refusal means the context is stale: the topic's contexts are
-/// dropped and one fresh capture is tried.
-async fn send_with_partition_context<B: BinaryTransport + Sync + ?Sized>(
- client: &B,
- stream_id: &Identifier,
- topic_id: &Identifier,
- capture: &GetPartitionRouteRequest,
- payload: Bytes,
-) -> Result<Bytes, IggyError> {
- let state = client.consumer_group_state();
- let mut context = state.partition_context(stream_id, topic_id, capture.partition_id);
- let mut refresh_available = true;
- loop {
- let captured = if let Some(context) = context {
- context
- } else {
- let response = client
- .send_raw_with_response(GET_PARTITION_ROUTE_CODE, capture.to_bytes())
- .await?;
- let context = super::decode_response::<PartitionRouteResponse>(&response)?.context();
- state.set_partition_context(stream_id, topic_id, capture.partition_id, context);
- context
- };
- match client
- .send_raw_with_context(SEND_MESSAGES_CODE, payload.clone(), captured)
- .await
- {
- Err(IggyError::HistoryUnavailable) => {
- state.invalidate_topic(stream_id, topic_id);
- if refresh_available {
- refresh_available = false;
- context = None;
- continue;
- }
- return Err(IggyError::HistoryUnavailable);
- }
- result => return result,
- }
- }
-}
-
-/// Inverse of `identifier_to_wire`, so raw and typed sends share cache keys.
-fn identifier_from_wire(id: &WireIdentifier) -> Result<Identifier, IggyError> {
- match id {
- WireIdentifier::Numeric(id) => Identifier::numeric(*id),
- WireIdentifier::String(name) => Identifier::named(name),
- }
-}
-
#[async_trait::async_trait]
impl<B: BinaryClient> MessageClient for B {
async fn poll_messages(
@@ -390,34 +384,37 @@ impl<B: BinaryClient> MessageClient for B {
count: u32,
auto_commit: bool,
) -> Result<PolledMessages, IggyError> {
- fail_if_not_authenticated(self).await?;
- // VSR: a consumer-group poll without an explicit partition is resolved
- // client-side from the member's cached assignment (the broker routes
- // explicit partitions only).
- if consumer.kind == ConsumerKind::ConsumerGroup && partition_id.is_none() {
- return poll_group_messages(
- self,
- stream_id,
- topic_id,
- consumer,
- strategy_for,
+ with_binary_deadline(binary_operation_deadline(), async {
+ fail_if_not_authenticated(self).await?;
+ // VSR: a consumer-group poll without an explicit partition is resolved
+ // client-side from the member's cached assignment (the broker routes
+ // explicit partitions only).
+ if consumer.kind == ConsumerKind::ConsumerGroup && partition_id.is_none() {
+ return poll_group_messages(
+ self,
+ stream_id,
+ topic_id,
+ consumer,
+ strategy_for,
+ count,
+ auto_commit,
+ )
+ .await;
+ }
+ let strategy = strategy_for(partition_id.unwrap_or(0));
+ let req = PollMessagesRequest {
+ consumer: consumer_to_wire(consumer)?,
+ stream_id: identifier_to_wire(stream_id)?,
+ topic_id: identifier_to_wire(topic_id)?,
+ partition_id,
+ strategy: polling_strategy_to_wire(&strategy),
count,
auto_commit,
- )
- .await;
- }
- let strategy = strategy_for(partition_id.unwrap_or(0));
- let req = PollMessagesRequest {
- consumer: consumer_to_wire(consumer)?,
- stream_id: identifier_to_wire(stream_id)?,
- topic_id: identifier_to_wire(topic_id)?,
- partition_id,
- strategy: polling_strategy_to_wire(&strategy),
- count,
- auto_commit,
- };
- let response = self.send_poll_with_response(&req, strategy.context).await?;
- PolledMessages::from_bytes(response)
+ };
+ let response = self.send_poll_with_response(&req, strategy.context).await?;
+ PolledMessages::from_bytes(response)
+ })
+ .await
}
async fn send_messages(
@@ -427,76 +424,66 @@ impl<B: BinaryClient> MessageClient for B {
partitioning: &Partitioning,
messages: &mut [IggyMessage],
) -> Result<SendMessagesResponse, IggyError> {
- fail_if_not_authenticated(self).await?;
- // VSR: resolve Balanced/MessagesKey to an explicit partition client-side.
- // An explicit `PartitionId` needs no resolution, so borrow the input
- // directly on that fast path instead of cloning its `value: Vec<u8>`.
- let resolved_partitioning;
- let partitioning = if partitioning.kind == PartitioningKind::PartitionId {
- partitioning
- } else {
- resolved_partitioning =
- resolve_partitioning(self, stream_id, topic_id, partitioning).await?;
- &resolved_partitioning
- };
- let wire_stream_id = identifier_to_wire(stream_id)?;
- let wire_topic_id = identifier_to_wire(topic_id)?;
- let wire_partitioning = partitioning_to_wire(partitioning)?;
- let partition_id = u32::from_le_bytes(
- partitioning
- .value
- .as_slice()
- .try_into()
- .map_err(|_| IggyError::InvalidCommand)?,
- );
- // The producer owns message ids now that batches ride the wire
- // verbatim: a zero id is minted here, before the frame checksum
- // covers it.
- for message in messages.iter_mut() {
- if message.header.id == 0 {
- message.header.id = crate::utils::random_id::get_uuid();
- }
- }
- let raw_messages: Vec<RawMessage<'_>> = messages
- .iter()
- .map(|m| RawMessage {
- id: m.header.id,
- origin_timestamp: m.header.origin_timestamp,
- headers: m.user_headers.as_deref(),
- payload: &m.payload,
- })
- .collect();
- let size = SendMessagesEncoder::encoded_size(
- &wire_stream_id,
- &wire_topic_id,
- &wire_partitioning,
- &raw_messages,
- );
- let mut buf = BytesMut::with_capacity(size);
- SendMessagesEncoder::encode(
- &mut buf,
- &wire_stream_id,
- &wire_topic_id,
- &wire_partitioning,
- &raw_messages,
+ send_binary_messages(
+ self,
+ stream_id,
+ topic_id,
+ &mut BinarySendPartitioning::new(partitioning),
+ messages,
)
- .map_err(|error| match error {
- iggy_binary_protocol::WireError::InvalidMessageTimestampDelta(delta) => {
- IggyError::InvalidMessageTimestampDelta(delta)
- }
- _ => IggyError::InvalidCommand,
- })?;
- let capture = GetPartitionRouteRequest {
- stream_id: wire_stream_id,
- topic_id: wire_topic_id,
- partition_id,
- };
- let response =
- send_with_partition_context(self, stream_id, topic_id, &capture, buf.freeze()).await?;
- Ok(committed_send_confirmations(&response))
+ .await
}
}
+fn encode_messages(
+ stream_id: &Identifier,
+ topic_id: &Identifier,
+ partitioning: &Partitioning,
+ messages: &mut [IggyMessage],
+) -> Result<Bytes, IggyError> {
+ let wire_stream_id = identifier_to_wire(stream_id)?;
+ let wire_topic_id = identifier_to_wire(topic_id)?;
+ let wire_partitioning = partitioning_to_wire(partitioning)?;
+ // The producer owns message ids now that batches ride the wire
+ // verbatim: a zero id is minted here, before the frame checksum
+ // covers it.
+ for message in messages.iter_mut() {
+ if message.header.id == 0 {
+ message.header.id = crate::utils::random_id::get_uuid();
+ }
+ }
+ let raw_messages: Vec<RawMessage<'_>> = messages
+ .iter()
+ .map(|m| RawMessage {
+ id: m.header.id,
+ origin_timestamp: m.header.origin_timestamp,
+ headers: m.user_headers.as_deref(),
+ payload: &m.payload,
+ })
+ .collect();
+ let size = SendMessagesEncoder::encoded_size(
+ &wire_stream_id,
+ &wire_topic_id,
+ &wire_partitioning,
+ &raw_messages,
+ );
+ let mut buf = BytesMut::with_capacity(size);
+ SendMessagesEncoder::encode(
+ &mut buf,
+ &wire_stream_id,
+ &wire_topic_id,
+ &wire_partitioning,
+ &raw_messages,
+ )
+ .map_err(|error| match error {
+ iggy_binary_protocol::WireError::InvalidMessageTimestampDelta(delta) => {
+ IggyError::InvalidMessageTimestampDelta(delta)
+ }
+ _ => IggyError::InvalidCommand,
+ })?;
+ Ok(buf.freeze())
+}
+
#[cfg(test)]
mod tests {
use super::{committed_send_confirmations, decode_send_confirmations};
diff --git a/core/common/src/traits/binary_impls/mod.rs b/core/common/src/traits/binary_impls/mod.rs
index dbad9bf87..26b21b8ca 100644
--- a/core/common/src/traits/binary_impls/mod.rs
+++ b/core/common/src/traits/binary_impls/mod.rs
@@ -27,8 +27,7 @@ mod system;
mod topics;
mod users;
-pub use messages::decode_send_confirmations;
-pub(crate) use messages::send_raw_messages;
+pub use messages::{BinarySendPartitioning, decode_send_confirmations, send_binary_messages};
use crate::IggyError;
use crate::http::users::defaults::{
@@ -44,6 +43,7 @@ use iggy_binary_protocol::{
ClientVersionInfo, IGGY_PROTOCOL_VERSION, MAX_WIRE_NAME_LENGTH, WireDecode, WireName,
};
use secrecy::ExposeSecret;
+use tokio::time::timeout_at;
/// SDK identifier sent in the login-register version prefix. Foreign SDKs
/// send their own (e.g. `go-sdk`) once they adopt VSR framing.
@@ -95,7 +95,7 @@ pub fn sign_in_request(
}
}
-/// Release a live session before a fresh login on the same connection.
+/// Prepare the connection before login, then release any existing session.
///
/// The server binds a connection to one `(client, session)` and resolves the
/// acting user from that binding, not the wire header. A re-login on a still-
@@ -103,8 +103,12 @@ pub fn sign_in_request(
/// identity, so switching users on a live connection requires logging out
/// first: the committed Logout unbinds the connection cluster-wide, so the
/// following Register takes the full register path and rebinds the newly
-/// authenticated user. No-op when the client is not authenticated.
+/// authenticated user. Connection establishment shares the login deadline and
+/// finishes before the caller captures the session fence.
pub(crate) async fn logout_before_relogin<B: BinaryClient>(client: &B) -> Result<(), IggyError> {
+ timeout_at(crate::binary_operation_deadline(), client.prepare_sign_in())
+ .await
+ .map_err(|_| IggyError::TransientNotAccepted)??;
if client.get_state().await == ClientState::Authenticated {
client.logout_user().await?;
}
diff --git a/core/common/src/traits/binary_impls/personal_access_tokens.rs b/core/common/src/traits/binary_impls/personal_access_tokens.rs
index 9dfc1e3ed..48ad1d157 100644
--- a/core/common/src/traits/binary_impls/personal_access_tokens.rs
+++ b/core/common/src/traits/binary_impls/personal_access_tokens.rs
@@ -90,30 +90,34 @@ impl<B: BinaryClient> PersonalAccessTokenClient for B {
&self,
token: &str,
) -> Result<IdentityInfo, IggyError> {
- super::logout_before_relogin(self).await?;
- super::validate_token(token)?;
- let credentials = Credentials::PersonalAccessToken(SecretString::from(token.to_string()));
- let fence = self.session_fence();
- let (code, payload) = super::sign_in_request(
- &credentials,
- super::rust_sdk_version_info(self.sdk_version())?,
- self.session_bind_secret().await?,
- )?;
- let response = self.send_raw_with_response(code, payload).await?;
- let wire_resp = super::decode_response::<LoginRegisterResponse>(&response)?;
- self.bind_vsr_session_at(fence, wire_resp.session).await?;
- tracing::debug!(
- server_version = %wire_resp.server_version,
- server_protocol_version = wire_resp.server_protocol_version,
- "authenticated against iggy server"
- );
- self.set_state(ClientState::Authenticated).await;
- self.remember_session_credentials(credentials, wire_resp.user_id)
- .await;
- self.publish_event(DiagnosticEvent::SignedIn).await;
- Ok(IdentityInfo {
- user_id: wire_resp.user_id,
- access_token: None,
+ crate::with_binary_deadline(crate::binary_operation_deadline(), async {
+ super::validate_token(token)?;
+ super::logout_before_relogin(self).await?;
+ let credentials =
+ Credentials::PersonalAccessToken(SecretString::from(token.to_string()));
+ let fence = self.session_fence();
+ let (code, payload) = super::sign_in_request(
+ &credentials,
+ super::rust_sdk_version_info(self.sdk_version())?,
+ self.session_bind_secret().await?,
+ )?;
+ let response = self.send_raw_with_response(code, payload).await?;
+ let wire_resp = super::decode_response::<LoginRegisterResponse>(&response)?;
+ self.bind_vsr_session_at(fence, wire_resp.session).await?;
+ tracing::debug!(
+ server_version = %wire_resp.server_version,
+ server_protocol_version = wire_resp.server_protocol_version,
+ "authenticated against iggy server"
+ );
+ self.set_state(ClientState::Authenticated).await;
+ self.remember_session_credentials(credentials, wire_resp.user_id)
+ .await;
+ self.publish_event(DiagnosticEvent::SignedIn).await;
+ Ok(IdentityInfo {
+ user_id: wire_resp.user_id,
+ access_token: None,
+ })
})
+ .await
}
}
diff --git a/core/common/src/traits/binary_impls/users.rs b/core/common/src/traits/binary_impls/users.rs
index 06e5c496b..b6533611e 100644
--- a/core/common/src/traits/binary_impls/users.rs
+++ b/core/common/src/traits/binary_impls/users.rs
@@ -129,9 +129,6 @@ impl<B: BinaryClient> UserClient for B {
.to_bytes(),
)
.await?;
- if let Some(username) = username {
- self.refresh_session_username(user_id, username).await;
- }
Ok(())
}
@@ -175,40 +172,42 @@ impl<B: BinaryClient> UserClient for B {
.to_bytes(),
)
.await?;
- self.refresh_session_password(user_id, new_password).await;
Ok(())
}
async fn login_user(&self, username: &str, password: &str) -> Result<IdentityInfo, IggyError> {
- super::validate_username(username)?;
- super::validate_password(password)?;
- super::logout_before_relogin(self).await?;
- let credentials = Credentials::UsernamePassword(
- username.to_owned(),
- SecretString::from(password.to_string()),
- );
- let fence = self.session_fence();
- let (code, payload) = super::sign_in_request(
- &credentials,
- super::rust_sdk_version_info(self.sdk_version())?,
- self.session_bind_secret().await?,
- )?;
- let response = self.send_raw_with_response(code, payload).await?;
- let wire_resp = super::decode_response::<LoginRegisterResponse>(&response)?;
- self.bind_vsr_session_at(fence, wire_resp.session).await?;
- tracing::debug!(
- server_version = %wire_resp.server_version,
- server_protocol_version = wire_resp.server_protocol_version,
- "authenticated against iggy server"
- );
- self.set_state(ClientState::Authenticated).await;
- self.remember_session_credentials(credentials, wire_resp.user_id)
- .await;
- self.publish_event(DiagnosticEvent::SignedIn).await;
- Ok(IdentityInfo {
- user_id: wire_resp.user_id,
- access_token: None,
+ crate::with_binary_deadline(crate::binary_operation_deadline(), async {
+ super::validate_username(username)?;
+ super::validate_password(password)?;
+ super::logout_before_relogin(self).await?;
+ let credentials = Credentials::UsernamePassword(
+ username.to_owned(),
+ SecretString::from(password.to_string()),
+ );
+ let fence = self.session_fence();
+ let (code, payload) = super::sign_in_request(
+ &credentials,
+ super::rust_sdk_version_info(self.sdk_version())?,
+ self.session_bind_secret().await?,
+ )?;
+ let response = self.send_raw_with_response(code, payload).await?;
+ let wire_resp = super::decode_response::<LoginRegisterResponse>(&response)?;
+ self.bind_vsr_session_at(fence, wire_resp.session).await?;
+ tracing::debug!(
+ server_version = %wire_resp.server_version,
+ server_protocol_version = wire_resp.server_protocol_version,
+ "authenticated against iggy server"
+ );
+ self.set_state(ClientState::Authenticated).await;
+ self.remember_session_credentials(credentials, wire_resp.user_id)
+ .await;
+ self.publish_event(DiagnosticEvent::SignedIn).await;
+ Ok(IdentityInfo {
+ user_id: wire_resp.user_id,
+ access_token: None,
+ })
})
+ .await
}
async fn logout_user(&self) -> Result<(), IggyError> {
diff --git a/core/common/src/traits/binary_transport.rs b/core/common/src/traits/binary_transport.rs
index 3ee42f044..42528b496 100644
--- a/core/common/src/traits/binary_transport.rs
+++ b/core/common/src/traits/binary_transport.rs
@@ -15,7 +15,6 @@
// specific language governing permissions and limitations
// under the License.
-use super::binary_impls::send_raw_messages;
use crate::{
ClientState, Credentials, DiagnosticEvent, Identifier, IggyError, NonZeroIggyDuration,
PartitionContext,
@@ -25,13 +24,38 @@ use bytes::Bytes;
use iggy_binary_protocol::WireDecode;
use iggy_binary_protocol::WireEncode;
use iggy_binary_protocol::codes::{
- DELETE_CONSUMER_OFFSET_CODE, POLL_MESSAGES_CODE, SEND_MESSAGES_CODE, STORE_CONSUMER_OFFSET_CODE,
+ DELETE_CONSUMER_OFFSET_CODE, POLL_MESSAGES_CODE, STORE_CONSUMER_OFFSET_CODE,
};
use iggy_binary_protocol::requests::messages::PollMessagesRequest;
use iggy_binary_protocol::requests::system::{BindSessionRequest, SessionIdentity};
use iggy_binary_protocol::requests::users::login_register::BindSecret;
use iggy_binary_protocol::responses::users::LoginRegisterResponse;
use std::sync::Arc;
+use std::time::Duration;
+use tokio::time::Instant;
+
+/// Default budget shared by a binary call's lookups, admission and retries.
+#[doc(hidden)]
+pub const BINARY_OPERATION_TIMEOUT: Duration = Duration::from_secs(30);
+
+tokio::task_local! {
+ static OPERATION_DEADLINE: Instant;
+}
+
+#[doc(hidden)]
+pub async fn with_binary_deadline<F: Future>(deadline: Instant, future: F) -> F::Output {
+ let deadline = OPERATION_DEADLINE
+ .try_with(|current| deadline.min(*current))
+ .unwrap_or(deadline);
+ OPERATION_DEADLINE.scope(deadline, future).await
+}
+
+#[doc(hidden)]
+pub fn binary_operation_deadline() -> Instant {
+ OPERATION_DEADLINE
+ .try_with(|deadline| *deadline)
+ .unwrap_or_else(|_| Instant::now() + BINARY_OPERATION_TIMEOUT)
+}
#[async_trait]
pub trait BinaryTransport {
@@ -43,31 +67,20 @@ pub trait BinaryTransport {
/// Low-level raw API: send `code` with an encoded `payload` and return the
/// raw reply body.
///
- /// Partition commands carry the partition context the typed API would send:
- /// - `SendMessages` with an explicit partition id uses the cached send
- /// context, or captures one from `GetPartitionRoute`. After a
- /// `HistoryUnavailable` refusal the topic's cached contexts are dropped and
- /// one fresh capture is tried. `Balanced` and `MessagesKey` partitioning
- /// fail with [`IggyError::FeatureUnavailable`] before anything is sent:
- /// use [`MessageClient::send_messages`](crate::MessageClient::send_messages)
- /// or an explicit partition id.
- /// - `PollMessages` takes the routed path of a typed poll (`GetPollRouting`),
- /// and `StoreConsumerOffset` and `DeleteConsumerOffset` that of a typed
- /// offset write (`GetConsumerOffsetRouting`). Each takes the context its
- /// route reports, so after another client deleted and recreated the
- /// partition, one call can fail with `HistoryUnavailable`
- /// (`ConsumerGroupPartitionNotOwned` for a consumer group). The failed
- /// route is dropped and the next call routes again.
+ /// The transport routes partition commands to their primary and captures
+ /// context when the caller supplies none. Raw `SendMessages` requires an
+ /// explicit partition id; raw `Balanced` and `MessagesKey` sends return
+ /// [`IggyError::FeatureUnavailable`]. Use [`MessageClient::send_messages`](crate::MessageClient::send_messages)
+ /// for balanced or keyed selection.
///
- /// A partition command payload that does not decode fails with
- /// [`IggyError::InvalidCommand`] before anything is sent. Every other code
- /// is sent unchanged, without a partition context.
+ /// Retries keep their request identity and first context. A definitive
+ /// history refusal lets a send capture once again; an uncertain operation
+ /// stays retained under its original context for explicit recovery.
async fn send_raw_with_response(&self, code: u32, payload: Bytes) -> Result<Bytes, IggyError>
where
Self: Sync,
{
match code {
- SEND_MESSAGES_CODE => send_raw_messages(self, payload).await,
POLL_MESSAGES_CODE => {
let request = PollMessagesRequest::decode_from(&payload)
.map_err(|_| IggyError::InvalidCommand)?;
@@ -84,8 +97,8 @@ pub trait BinaryTransport {
}
}
/// Send with a captured partition incarnation and owner. Every retry must retain it.
- /// A history refusal after an uncertain attempt must return
- /// `TransientNotCommitted`, so callers cannot refresh and repeat that write.
+ /// A history refusal after an uncertain attempt returns `OperationUncertain`,
+ /// so callers cannot refresh and repeat that write under a new identity.
async fn send_raw_with_context(
&self,
code: u32,
@@ -113,6 +126,16 @@ pub trait BinaryTransport {
) -> Result<Bytes, IggyError>
where
Self: Sync;
+ /// The partition count from the newest usable route for this topic.
+ #[doc(hidden)]
+ fn routed_partition_count(
+ &self,
+ _stream_id: &Identifier,
+ _topic_id: &Identifier,
+ ) -> Option<u32> {
+ None
+ }
+
fn get_heartbeat_interval(&self) -> NonZeroIggyDuration;
/// Per-transport consumer-group + partitioning cache used to resolve
@@ -132,6 +155,22 @@ mod vsr_session_sealed {
/// mutation corrupts the dedup counter or silently breaks at-most-once.
#[async_trait]
pub trait VsrSessionControl: vsr_session_sealed::Sealed + BinaryTransport {
+ /// Establish a connection for explicit credentials before capturing the
+ /// sign-in fence. Binary SDK transports suppress automatic sign-in here.
+ #[doc(hidden)]
+ async fn prepare_sign_in(&self) -> Result<(), IggyError>
+ where
+ Self: crate::Client,
+ {
+ if matches!(
+ self.get_state().await,
+ ClientState::Disconnected | ClientState::Connecting
+ ) {
+ self.connect().await?;
+ }
+ Ok(())
+ }
+
/// Internal bearer proof. Never log or expose this value to application users.
#[doc(hidden)]
async fn session_bind_secret(&self) -> Result<BindSecret, IggyError>;
@@ -193,18 +232,6 @@ pub trait VsrSessionControl: vsr_session_sealed::Sealed + BinaryTransport {
/// Drop them: after an explicit logout there is no session to restore,
/// and a reconnect must not resurrect one.
async fn forget_session_credentials(&self) {}
- /// A committed password change for `user`: when it is the signed-in user,
- /// the credentials the next reconnect signs in with switch to the new
- /// password, or that reconnect would replay the old one and fail an
- /// unrelated request with `InvalidCredentials`. Other users' changes are
- /// ignored.
- ///
- /// This covers a configured `AutoLogin` as well as a sign-in the caller
- /// ran: the configured credentials still decide *who* the client signs in
- /// as, and a committed change decides what that user's password is.
- async fn refresh_session_password(&self, _user: &Identifier, _new_password: &str) {}
- /// Keep auxiliary logins and reconnects working after the session user is renamed.
- async fn refresh_session_username(&self, _user: &Identifier, _new_username: &str) {}
/// SDK crate version sent in the login-register version prefix.
/// Implemented by the transports so the value is the SDK crate's own
/// `CARGO_PKG_VERSION` (`iggy` for Rust), not `iggy_common`'s.
@@ -236,17 +263,11 @@ mod tests {
use super::*;
use crate::ConsumerGroupClientState;
use bytes::BytesMut;
- use iggy_binary_protocol::codes::{
- GET_CONSUMER_OFFSET_ROUTING_CODE, GET_PARTITION_ROUTE_CODE, GET_POLL_ROUTING_CODE,
- PING_CODE, POLL_MESSAGES_ON_PRIMARY_CODE,
- };
+ use iggy_binary_protocol::codes::{GET_PARTITION_ROUTE_CODE, PING_CODE, SEND_MESSAGES_CODE};
use iggy_binary_protocol::requests::consumer_offsets::{
DeleteConsumerOffsetRequest, StoreConsumerOffsetRequest,
};
- use iggy_binary_protocol::requests::messages::{
- GetPartitionRouteRequest, RawMessage, SendMessagesEncoder,
- };
- use iggy_binary_protocol::responses::messages::PartitionRouteResponse;
+ use iggy_binary_protocol::requests::messages::{RawMessage, SendMessagesEncoder};
use iggy_binary_protocol::{
AckLevel, WireConsumer, WireIdentifier, WirePartitioning, WirePollingStrategy,
};
@@ -256,12 +277,6 @@ mod tests {
const TOPIC: &str = "orders";
const PARTITION: u32 = 3;
const RECEIPT: &[u8] = b"receipt";
- const CAPTURED: PartitionContext = PartitionContext {
- incarnation: 7,
- owner_generation: 0,
- metadata_op: 9,
- };
-
#[derive(Debug, PartialEq)]
enum Call {
Raw(u32, Bytes, PartitionContext),
@@ -303,16 +318,6 @@ mod tests {
context: PartitionContext,
) -> Result<Bytes, IggyError> {
self.record(Call::Raw(code, payload, context));
- if code == GET_PARTITION_ROUTE_CODE {
- return Ok(PartitionRouteResponse {
- incarnation: CAPTURED.incarnation,
- metadata_op: CAPTURED.metadata_op,
- view: 0,
- partitions_count: PARTITION + 1,
- primary_replica: 0,
- }
- .to_bytes());
- }
Ok(Bytes::from_static(RECEIPT))
}
@@ -372,63 +377,24 @@ mod tests {
}
#[tokio::test]
- async fn given_raw_send_to_partition_id_when_repeated_should_capture_context_once() {
+ async fn given_raw_send_to_partition_id_when_sent_should_leave_routing_to_transport() {
let transport = Recorder::default();
let payload = send_payload(&WirePartitioning::PartitionId(PARTITION));
- for _ in 0..2 {
- let response = transport
- .send_raw_with_response(SEND_MESSAGES_CODE, payload.clone())
- .await
- .unwrap();
- assert_eq!(response, Bytes::from_static(RECEIPT));
- }
- let capture = GetPartitionRouteRequest {
- stream_id: WireIdentifier::numeric(STREAM),
- topic_id: wire_topic(),
- partition_id: PARTITION,
- };
+ let response = transport
+ .send_raw_with_response(SEND_MESSAGES_CODE, payload.clone())
+ .await
+ .unwrap();
+ assert_eq!(response, Bytes::from_static(RECEIPT));
assert_eq!(
transport.take_calls(),
- vec![
- Call::Raw(
- GET_PARTITION_ROUTE_CODE,
- capture.to_bytes(),
- PartitionContext::default()
- ),
- Call::Raw(SEND_MESSAGES_CODE, payload.clone(), CAPTURED),
- Call::Raw(SEND_MESSAGES_CODE, payload, CAPTURED),
- ]
- );
- // Typed sends key the same cache by domain identifiers.
- assert_eq!(
- transport.state.partition_context(
- &Identifier::numeric(STREAM).unwrap(),
- &Identifier::named(TOPIC).unwrap(),
- PARTITION
- ),
- Some(CAPTURED)
+ vec![Call::Raw(
+ SEND_MESSAGES_CODE,
+ payload,
+ PartitionContext::default()
+ )]
);
}
- #[tokio::test]
- async fn given_raw_send_without_partition_id_when_sent_should_fail_before_sending() {
- let transport = Recorder::default();
- for partitioning in [
- WirePartitioning::Balanced,
- WirePartitioning::MessagesKey(b"key".to_vec()),
- ] {
- let result = transport
- .send_raw_with_response(SEND_MESSAGES_CODE, send_payload(&partitioning))
- .await;
- assert_eq!(
- result,
- Err(IggyError::FeatureUnavailable),
- "{partitioning:?}"
- );
- }
- assert!(transport.take_calls().is_empty());
- }
-
#[tokio::test]
async fn given_raw_poll_when_sent_should_route_like_a_typed_poll() {
let transport = Recorder::default();
@@ -485,13 +451,7 @@ mod tests {
async fn given_non_partition_code_when_sent_should_pass_through_with_default_context() {
let transport = Recorder::default();
let payload = Bytes::from_static(b"opaque");
- for code in [
- PING_CODE,
- GET_PARTITION_ROUTE_CODE,
- GET_POLL_ROUTING_CODE,
- POLL_MESSAGES_ON_PRIMARY_CODE,
- GET_CONSUMER_OFFSET_ROUTING_CODE,
- ] {
+ for code in [PING_CODE, GET_PARTITION_ROUTE_CODE] {
transport
.send_raw_with_response(code, payload.clone())
.await
@@ -510,14 +470,7 @@ mod tests {
#[tokio::test]
async fn given_undecodable_partition_payload_when_sent_should_fail_before_sending() {
let transport = Recorder::default();
- let mut metadata_past_end =
- send_payload(&WirePartitioning::PartitionId(PARTITION)).to_vec();
- metadata_past_end[..4].copy_from_slice(&u32::MAX.to_le_bytes());
- for (code, payload) in [
- (SEND_MESSAGES_CODE, Bytes::new()),
- (SEND_MESSAGES_CODE, Bytes::from(metadata_past_end)),
- (POLL_MESSAGES_CODE, Bytes::from_static(b"lost-poll")),
- ] {
+ for (code, payload) in [(POLL_MESSAGES_CODE, Bytes::from_static(b"lost-poll"))] {
let result = transport.send_raw_with_response(code, payload).await;
assert_eq!(result, Err(IggyError::InvalidCommand), "code {code}");
}
diff --git a/core/common/src/traits/client.rs b/core/common/src/traits/client.rs
index a93a8addd..1ef190225 100644
--- a/core/common/src/traits/client.rs
+++ b/core/common/src/traits/client.rs
@@ -51,12 +51,13 @@ pub trait Client:
/// Disconnect from the server. Repeated calls are safe.
///
- /// On TCP, QUIC and WebSocket, the disconnect holds until the next `connect()`,
- /// also on a client that was not connected: nothing reconnects the client on
- /// its own, even with auto-login credentials. Until then, a request that needs
- /// a session fails with `IggyError::Disconnected`, and any other request with
- /// `IggyError::NotConnected`. A connection that drops without this call can
- /// still reconnect on its own. Over HTTP this call does nothing.
+ /// On TCP, QUIC and WebSocket, the disconnect holds until the next `connect()`
+ /// or explicit username/PAT login, also on a client that was not connected.
+ /// Nothing reconnects the client on its own, even with auto-login credentials.
+ /// Requests requiring a session fail with `IggyError::Disconnected`; other
+ /// requests can return `IggyError::NotConnected`. A connection that drops
+ /// without this call can still reconnect on its own. Over HTTP this call does
+ /// nothing.
async fn disconnect(&self) -> Result<(), IggyError>;
/// Shut down the client and release all the resources. Repeated calls are safe.
@@ -81,29 +82,34 @@ pub trait Client:
/// HTTP keeps no connection, so it publishes no events.
async fn subscribe_events(&self) -> Receiver<DiagnosticEvent>;
- /// Replays the retained operation `op` until it commits or `deadline`
- /// passes. `op` is the request id that `OperationUncertain` or
+ /// Replays the retained operation `op` until its committed result is proved
+ /// or `deadline` passes. `op` is the request id that `OperationUncertain` or
/// `LaneBlocked` carries.
///
- /// `Ok(())` means that the operation committed exactly once. After
- /// `OperationUncertain(op)` the outcome is still unknown, and the
- /// operation stays retained. An operation that is not retained gives
- /// `OperationNotRetained(op)`. A client that retains no operations
- /// returns `FeatureUnavailable`.
+ /// `Ok(())` means a successful commit was proved. A proved committed business
+ /// rejection returns its original error. Both release the retained operation
+ /// and its lane. `OperationUncertain(op)` keeps the original frame and lane:
+ /// a later denial without committed-result proof cannot settle an earlier send.
+ /// TCP, QUIC and WebSocket support recovery; HTTP returns `FeatureUnavailable`.
///
- /// A session reset drops retained operations without settling them.
- /// `OperationNotRetained(op)` after a reset means the outcome is still
- /// unknown and can no longer be recovered through this client.
- #[doc(hidden)]
+ /// The client keeps the proved outcomes of its last
+ /// [`max_operations`](crate::PendingOperationsConfig::max_operations) replays,
+ /// also across a session reset. A later resolve of `op` returns the same
+ /// outcome without a request, also when a producer or a consumer of this
+ /// client replayed `op` first.
+ ///
+ /// `OperationNotRetained(op)` means the outcome is unknown and can no longer
+ /// be recovered through this client. Either a session reset or an abandon
+ /// dropped `op` before a replay proved its outcome, or that outcome aged out.
async fn resolve_operation(&self, _op: u64, _deadline: Instant) -> Result<(), IggyError> {
Err(IggyError::FeatureUnavailable)
}
/// Frees the lane that the retained operation `op` blocks, and the outcome
- /// of `op` stays unknown. An operation that is not retained gives
- /// `OperationNotRetained(op)`. A client that retains no operations
- /// returns `FeatureUnavailable`.
- #[doc(hidden)]
+ /// of `op` stays unknown. A replay of `op` that is already running still
+ /// keeps the outcome it proves for [`Self::resolve_operation`]. An operation
+ /// that is not retained gives `OperationNotRetained(op)`. A client that
+ /// retains no operations returns `FeatureUnavailable`.
async fn abandon_operation(&self, _op: u64) -> Result<(), IggyError> {
Err(IggyError::FeatureUnavailable)
}
diff --git a/core/common/src/traits/message_client.rs b/core/common/src/traits/message_client.rs
index bd13352be..f1d49b179 100644
--- a/core/common/src/traits/message_client.rs
+++ b/core/common/src/traits/message_client.rs
@@ -138,7 +138,9 @@ pub trait MessageClient {
///
/// Binary clients refresh the partition context once after a definitive
/// `HistoryUnavailable` (87) refusal. A refusal after an uncertain send
- /// keeps its original context and returns `TransientNotCommitted` (57).
+ /// keeps its original context and returns `OperationUncertain(op)`.
+ /// `Balanced` and `MessagesKey` sends select a new partition once after a
+ /// definitive `PartitionNotFound` refusal.
async fn send_messages(
&self,
stream_id: &Identifier,
diff --git a/core/common/src/traits/mod.rs b/core/common/src/traits/mod.rs
index 9c200766d..b18529ec5 100644
--- a/core/common/src/traits/mod.rs
+++ b/core/common/src/traits/mod.rs
@@ -35,5 +35,5 @@ pub(crate) mod topic_client;
pub(crate) mod user_client;
pub(crate) mod validatable;
-pub use binary_impls::decode_send_confirmations;
+pub use binary_impls::{BinarySendPartitioning, decode_send_confirmations, send_binary_messages};
pub use binary_impls::{rust_sdk_version_info, sign_in_request};
diff --git a/core/common/src/types/configuration/mod.rs b/core/common/src/types/configuration/mod.rs
index 667e58884..58abe7ac8 100644
--- a/core/common/src/types/configuration/mod.rs
+++ b/core/common/src/types/configuration/mod.rs
@@ -17,6 +17,7 @@
pub(crate) mod auth_config;
pub(crate) mod http_config;
+pub(crate) mod pending_operations_config;
pub(crate) mod quic_config;
pub(crate) mod tcp_config;
pub(crate) mod transport;
diff --git a/core/common/src/types/configuration/pending_operations_config.rs b/core/common/src/types/configuration/pending_operations_config.rs
new file mode 100644
index 000000000..fbe16aa08
--- /dev/null
+++ b/core/common/src/types/configuration/pending_operations_config.rs
@@ -0,0 +1,145 @@
+// 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::num::NonZeroUsize;
+
+/// Client-wide limits for active and retained replicated mutations.
+/// Queued writers keep their frame bytes charged after completion or abandonment.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PendingOperationsConfig {
+ /// Active or retained mutations sharing this client session.
+ pub max_operations: NonZeroUsize,
+ /// Frozen headers and bodies, including frames still held by a writer.
+ /// A useful limit must fit the 256-byte header plus the largest mutation body.
+ /// Smaller positive limits are valid but reject every mutation that cannot fit.
+ pub max_bytes: NonZeroUsize,
+}
+
+impl PendingOperationsConfig {
+ pub const DEFAULT_MAX_OPERATIONS: NonZeroUsize = NonZeroUsize::new(256).unwrap();
+ pub const DEFAULT_MAX_BYTES: NonZeroUsize = NonZeroUsize::new(64 * 1024 * 1024).unwrap();
+}
+
+impl Default for PendingOperationsConfig {
+ fn default() -> Self {
+ Self {
+ max_operations: Self::DEFAULT_MAX_OPERATIONS,
+ max_bytes: Self::DEFAULT_MAX_BYTES,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{
+ ConnectionString, IggyError, QuicClientConfig, QuicClientConfigBuilder,
+ QuicConnectionStringOptions, TcpClientConfig, TcpClientConfigBuilder,
+ TcpConnectionStringOptions, WebSocketClientConfig, WebSocketClientConfigBuilder,
+ WebSocketConnectionStringOptions,
+ };
+ use std::str::FromStr;
+
+ #[test]
+ fn given_custom_mutation_limits_when_building_transport_configs_should_preserve_them() {
+ let limits = PendingOperationsConfig {
+ max_operations: NonZeroUsize::new(3).unwrap(),
+ max_bytes: NonZeroUsize::new(4096).unwrap(),
+ };
+ assert_eq!(
+ TcpClientConfigBuilder::new()
+ .with_pending_operations(limits)
+ .build()
+ .unwrap()
+ .pending_operations,
+ limits
+ );
+ assert_eq!(
+ QuicClientConfigBuilder::new()
+ .with_pending_operations(limits)
+ .build()
+ .unwrap()
+ .pending_operations,
+ limits
+ );
+ assert_eq!(
+ WebSocketClientConfigBuilder::new()
+ .with_pending_operations(limits)
+ .build()
+ .unwrap()
+ .pending_operations,
+ limits
+ );
+ }
+
+ #[test]
+ fn given_connection_string_limits_when_building_all_binary_transports_should_preserve_them() {
+ let query = "max_pending_operations=3&max_pending_operation_bytes=4096";
+ let tcp = TcpClientConfig::from(
+ ConnectionString::<TcpConnectionStringOptions>::from_str(&format!(
+ "iggy+tcp://iggy:iggy@localhost:8090?{query}"
+ ))
+ .unwrap(),
+ );
+ let quic = QuicClientConfig::from(
+ ConnectionString::<QuicConnectionStringOptions>::from_str(&format!(
+ "iggy+quic://iggy:iggy@localhost:8080?{query}"
+ ))
+ .unwrap(),
+ );
+ let ws = WebSocketClientConfig::from(
+ ConnectionString::<WebSocketConnectionStringOptions>::from_str(&format!(
+ "iggy+ws://iggy:iggy@localhost:8092?{query}"
+ ))
+ .unwrap(),
+ );
+ let expected = PendingOperationsConfig {
+ max_operations: NonZeroUsize::new(3).unwrap(),
+ max_bytes: NonZeroUsize::new(4096).unwrap(),
+ };
+ for actual in [
+ tcp.pending_operations,
+ quic.pending_operations,
+ ws.pending_operations,
+ ] {
+ assert_eq!(actual, expected);
+ }
+ }
+
+ #[test]
+ fn given_invalid_connection_string_limits_when_parsing_should_fail_before_client_creation() {
+ for field in ["max_pending_operations", "max_pending_operation_bytes"] {
+ for value in ["0", "-1", "1.5", "18446744073709551616", ""] {
+ let address = format!("iggy+tcp://iggy:iggy@localhost:8090?{field}={value}");
+ assert!(matches!(
+ ConnectionString::<TcpConnectionStringOptions>::from_str(&address),
+ Err(IggyError::InvalidConnectionString)
+ ));
+ let address = address.replace("iggy+tcp:", "iggy+quic:");
+ assert!(matches!(
+ ConnectionString::<QuicConnectionStringOptions>::from_str(&address),
+ Err(IggyError::InvalidConnectionString)
+ ));
+ let address = address.replace("iggy+quic:", "iggy+ws:");
+ assert!(matches!(
+ ConnectionString::<WebSocketConnectionStringOptions>::from_str(&address),
+ Err(IggyError::InvalidConnectionString)
+ ));
+ }
+ }
+ }
+}
diff --git a/core/common/src/types/configuration/quic_config/quic_client_config.rs b/core/common/src/types/configuration/quic_config/quic_client_config.rs
index 774924bb3..4b57162fb 100644
--- a/core/common/src/types/configuration/quic_config/quic_client_config.rs
+++ b/core/common/src/types/configuration/quic_config/quic_client_config.rs
@@ -17,7 +17,7 @@
use crate::{
AutoLogin, ConnectionString, ConnectionStringOptions, NonZeroIggyDuration,
- QuicClientReconnectionConfig, QuicConnectionStringOptions,
+ PendingOperationsConfig, QuicClientReconnectionConfig, QuicConnectionStringOptions,
};
use std::str::FromStr;
@@ -32,6 +32,8 @@ pub struct QuicClientConfig {
pub server_name: String,
/// Whether to automatically login user after establishing connection.
pub auto_login: AutoLogin,
+ /// Shared limits across this client's mutation lanes.
+ pub pending_operations: PendingOperationsConfig,
// Whether to automatically reconnect when disconnected.
pub reconnection: QuicClientReconnectionConfig,
/// The size of the response buffer.
@@ -63,6 +65,7 @@ impl Default for QuicClientConfig {
server_address: "127.0.0.1:8080".to_string(),
server_name: "localhost".to_string(),
auto_login: AutoLogin::Disabled,
+ pending_operations: PendingOperationsConfig::default(),
heartbeat_interval: NonZeroIggyDuration::from_str("5s").unwrap(),
reconnection: QuicClientReconnectionConfig::default(),
response_buffer_size: 1000 * 1000 * 10,
@@ -85,6 +88,7 @@ impl From<ConnectionString<QuicConnectionStringOptions>> for QuicClientConfig {
server_address: connection_string.server_address().into(),
server_name: "localhost".to_string(),
auto_login: connection_string.auto_login().to_owned(),
+ pending_operations: connection_string.options().pending_operations(),
reconnection: connection_string.options().reconnection().to_owned(),
response_buffer_size: connection_string.options().response_buffer_size(),
max_concurrent_bidi_streams: connection_string.options().max_concurrent_bidi_streams(),
diff --git a/core/common/src/types/configuration/quic_config/quic_client_config_builder.rs b/core/common/src/types/configuration/quic_config/quic_client_config_builder.rs
index 0ade0cabb..8c8f6b641 100644
--- a/core/common/src/types/configuration/quic_config/quic_client_config_builder.rs
+++ b/core/common/src/types/configuration/quic_config/quic_client_config_builder.rs
@@ -16,8 +16,8 @@
// under the License.
use crate::{
- AutoLogin, IggyDuration, IggyError, NonZeroIggyDuration, QuicClientConfig,
- validate_server_address,
+ AutoLogin, IggyDuration, IggyError, NonZeroIggyDuration, PendingOperationsConfig,
+ QuicClientConfig, validate_server_address,
};
/// Builder for the QUIC client configuration.
@@ -60,6 +60,12 @@ impl QuicClientConfigBuilder {
self
}
+ /// Sets client-wide active and retained mutation limits.
+ pub fn with_pending_operations(mut self, pending_operations: PendingOperationsConfig) -> Self {
+ self.config.pending_operations = pending_operations;
+ self
+ }
+
/// Sets the auto sign in during connection.
pub fn with_auto_sign_in(mut self, auto_sign_in: AutoLogin) -> Self {
self.config.auto_login = auto_sign_in;
@@ -83,13 +89,13 @@ impl QuicClientConfigBuilder {
self
}
- /// Sets the interval between retries when connecting to the server.
+ /// Sets the full-jitter exponential backoff base, capped at 10 seconds.
pub fn with_reconnection_interval(mut self, interval: NonZeroIggyDuration) -> Self {
self.config.reconnection.interval = interval;
self
}
- /// Sets the cooldown before reconnecting after a previously successful connection.
+ /// Sets the stable connection duration that resets the retry count and backoff.
pub fn with_reestablish_after(mut self, reestablish_after: IggyDuration) -> Self {
self.config.reconnection.reestablish_after = reestablish_after;
self
diff --git a/core/common/src/types/configuration/quic_config/quic_client_reconnection_config.rs b/core/common/src/types/configuration/quic_config/quic_client_reconnection_config.rs
index e5e6d4825..d60e82a70 100644
--- a/core/common/src/types/configuration/quic_config/quic_client_reconnection_config.rs
+++ b/core/common/src/types/configuration/quic_config/quic_client_reconnection_config.rs
@@ -21,9 +21,17 @@ use std::str::FromStr;
#[derive(Debug, Clone)]
pub struct QuicClientReconnectionConfig {
pub enabled: bool,
+ /// Retry passes after the initial bootstrap pass, and consecutive background
+ /// dial attempts per replica. `None` permits unlimited retries; `Some(0)`
+ /// permits only the initial bootstrap pass. The limit covers one reconnect
+ /// burst: while the client is signed in, each `IggyClient` heartbeat
+ /// restarts the replica links that used it up, with a fresh budget. A
+ /// transport client without `IggyClient` has no heartbeat, so only
+ /// `connect()` restarts them.
pub max_retries: Option<u32>,
- /// Delay between connection attempts.
+ /// Full-jitter exponential backoff base, capped at 10 seconds.
pub interval: NonZeroIggyDuration,
+ /// Stable connection duration that resets the retry count and backoff.
pub reestablish_after: IggyDuration,
}
diff --git a/core/common/src/types/configuration/quic_config/quic_connection_string_options.rs b/core/common/src/types/configuration/quic_config/quic_connection_string_options.rs
index 43f401661..a17d2be1d 100644
--- a/core/common/src/types/configuration/quic_config/quic_connection_string_options.rs
+++ b/core/common/src/types/configuration/quic_config/quic_connection_string_options.rs
@@ -16,13 +16,14 @@
// under the License.
use crate::{
- ConnectionStringOptions, IggyDuration, IggyError, NonZeroIggyDuration,
+ ConnectionStringOptions, IggyDuration, IggyError, NonZeroIggyDuration, PendingOperationsConfig,
QuicClientReconnectionConfig,
};
use std::str::FromStr;
#[derive(Debug)]
pub struct QuicConnectionStringOptions {
+ pending_operations: PendingOperationsConfig,
reconnection: QuicClientReconnectionConfig,
response_buffer_size: u64,
max_concurrent_bidi_streams: u64,
@@ -37,6 +38,10 @@ pub struct QuicConnectionStringOptions {
}
impl QuicConnectionStringOptions {
+ pub fn pending_operations(&self) -> PendingOperationsConfig {
+ self.pending_operations
+ }
+
pub fn reconnection(&self) -> &QuicClientReconnectionConfig {
&self.reconnection
}
@@ -89,6 +94,7 @@ impl ConnectionStringOptions for QuicConnectionStringOptions {
fn parse_options(options: &str) -> Result<QuicConnectionStringOptions, IggyError> {
let options = options.split('&').collect::<Vec<&str>>();
+ let mut pending_operations = PendingOperationsConfig::default();
let mut response_buffer_size = 1000 * 1000 * 10;
let mut max_concurrent_bidi_streams = 10000;
let mut datagram_send_buffer_size = 100_000;
@@ -111,6 +117,16 @@ impl ConnectionStringOptions for QuicConnectionStringOptions {
return Err(IggyError::InvalidConnectionString);
}
match option_parts[0] {
+ "max_pending_operations" => {
+ pending_operations.max_operations = option_parts[1]
+ .parse()
+ .map_err(|_| IggyError::InvalidConnectionString)?;
+ }
+ "max_pending_operation_bytes" => {
+ pending_operations.max_bytes = option_parts[1]
+ .parse()
+ .map_err(|_| IggyError::InvalidConnectionString)?;
+ }
"response_buffer_size" => match option_parts[1].parse::<u64>() {
Ok(value) => {
response_buffer_size = value;
@@ -215,7 +231,7 @@ impl ConnectionStringOptions for QuicConnectionStringOptions {
let heartbeat_interval = NonZeroIggyDuration::from_str(heartbeat_interval.as_str())
.map_err(|_| IggyError::InvalidConnectionString)?;
- let connection_string_options = QuicConnectionStringOptions::new(
+ let mut connection_string_options = QuicConnectionStringOptions::new(
reconnection,
response_buffer_size,
max_concurrent_bidi_streams,
@@ -229,6 +245,7 @@ impl ConnectionStringOptions for QuicConnectionStringOptions {
heartbeat_interval,
);
+ connection_string_options.pending_operations = pending_operations;
Ok(connection_string_options)
}
}
@@ -249,6 +266,7 @@ impl QuicConnectionStringOptions {
heartbeat_interval: NonZeroIggyDuration,
) -> Self {
Self {
+ pending_operations: PendingOperationsConfig::default(),
reconnection,
response_buffer_size,
max_concurrent_bidi_streams,
@@ -267,6 +285,7 @@ impl QuicConnectionStringOptions {
impl Default for QuicConnectionStringOptions {
fn default() -> Self {
QuicConnectionStringOptions {
+ pending_operations: PendingOperationsConfig::default(),
reconnection: Default::default(),
response_buffer_size: 1000 * 1000 * 10,
max_concurrent_bidi_streams: 10000,
diff --git a/core/common/src/types/configuration/tcp_config/tcp_client_config.rs b/core/common/src/types/configuration/tcp_config/tcp_client_config.rs
index 9c3431ebd..f91f0eea1 100644
--- a/core/common/src/types/configuration/tcp_config/tcp_client_config.rs
+++ b/core/common/src/types/configuration/tcp_config/tcp_client_config.rs
@@ -18,7 +18,7 @@
use crate::types::configuration::auth_config::connection_string::ConnectionString;
use crate::types::configuration::auth_config::connection_string_options::ConnectionStringOptions;
use crate::types::configuration::tcp_config::tcp_connection_string_options::TcpConnectionStringOptions;
-use crate::{AutoLogin, NonZeroIggyDuration, TcpClientReconnectionConfig};
+use crate::{AutoLogin, NonZeroIggyDuration, PendingOperationsConfig, TcpClientReconnectionConfig};
use std::str::FromStr;
/// Configuration for the TCP client.
@@ -37,6 +37,8 @@ pub struct TcpClientConfig {
pub tls_validate_certificate: bool,
/// Whether to automatically login user after establishing connection.
pub auto_login: AutoLogin,
+ /// Shared limits across this client's mutation lanes.
+ pub pending_operations: PendingOperationsConfig,
/// Whether to automatically reconnect when disconnected.
pub reconnection: TcpClientReconnectionConfig,
/// Interval of heartbeats sent by the client
@@ -55,6 +57,7 @@ impl Default for TcpClientConfig {
tls_validate_certificate: true,
heartbeat_interval: NonZeroIggyDuration::from_str("5s").unwrap(),
auto_login: AutoLogin::Disabled,
+ pending_operations: PendingOperationsConfig::default(),
reconnection: TcpClientReconnectionConfig::default(),
nodelay: false,
}
@@ -66,6 +69,7 @@ impl From<ConnectionString<TcpConnectionStringOptions>> for TcpClientConfig {
TcpClientConfig {
server_address: connection_string.server_address().into(),
auto_login: connection_string.auto_login().to_owned(),
+ pending_operations: connection_string.options().pending_operations(),
tls_enabled: connection_string.options().tls_enabled(),
tls_domain: connection_string.options().tls_domain().into(),
tls_ca_file: connection_string.options().tls_ca_file().to_owned(),
diff --git a/core/common/src/types/configuration/tcp_config/tcp_client_config_builder.rs b/core/common/src/types/configuration/tcp_config/tcp_client_config_builder.rs
index 943b69f53..7b063bb85 100644
--- a/core/common/src/types/configuration/tcp_config/tcp_client_config_builder.rs
+++ b/core/common/src/types/configuration/tcp_config/tcp_client_config_builder.rs
@@ -16,8 +16,8 @@
// under the License.
use crate::{
- AutoLogin, IggyDuration, IggyError, NonZeroIggyDuration, TcpClientConfig,
- validate_server_address,
+ AutoLogin, IggyDuration, IggyError, NonZeroIggyDuration, PendingOperationsConfig,
+ TcpClientConfig, validate_server_address,
};
/// Builder for the TCP client configuration.
@@ -44,6 +44,12 @@ impl TcpClientConfigBuilder {
self
}
+ /// Sets client-wide active and retained mutation limits.
+ pub fn with_pending_operations(mut self, pending_operations: PendingOperationsConfig) -> Self {
+ self.config.pending_operations = pending_operations;
+ self
+ }
+
/// Sets the auto sign in during connection.
pub fn with_auto_sign_in(mut self, auto_sign_in: AutoLogin) -> Self {
self.config.auto_login = auto_sign_in;
@@ -61,13 +67,13 @@ impl TcpClientConfigBuilder {
self
}
- /// Sets the interval between retries when connecting to the server.
+ /// Sets the full-jitter exponential backoff base, capped at 10 seconds.
pub fn with_reconnection_interval(mut self, interval: NonZeroIggyDuration) -> Self {
self.config.reconnection.interval = interval;
self
}
- /// Sets the cooldown before reconnecting after a previously successful connection.
+ /// Sets the stable connection duration that resets the retry count and backoff.
pub fn with_reestablish_after(mut self, reestablish_after: IggyDuration) -> Self {
self.config.reconnection.reestablish_after = reestablish_after;
self
diff --git a/core/common/src/types/configuration/tcp_config/tcp_client_reconnection_config.rs b/core/common/src/types/configuration/tcp_config/tcp_client_reconnection_config.rs
index 497db1921..ea977f8e5 100644
--- a/core/common/src/types/configuration/tcp_config/tcp_client_reconnection_config.rs
+++ b/core/common/src/types/configuration/tcp_config/tcp_client_reconnection_config.rs
@@ -20,43 +20,21 @@ use std::str::FromStr;
#[derive(Debug, Clone)]
pub struct TcpClientReconnectionConfig {
- /// Whether a lost connection is redialed at all. With this off the
- /// endpoints the client knows still get one pass, since they were
- /// configured to be tried, but nothing is retried after it.
+ /// Whether to retry failed bootstrap passes and maintain replica links.
+ /// The first bootstrap pass still tries every known endpoint when disabled.
pub enabled: bool,
- /// How many passes over the known endpoints *after the first*, or `None`
- /// for unlimited. `Some(0)` still makes that one pass, since the endpoints
- /// were configured to be tried.
- ///
- /// Passes, not dials: one pass tries the endpoint the client is on, the
- /// addresses it was configured with, and every node the roster named, so a
- /// survivor is reached inside the first pass rather than one delay per
- /// endpoint.
- ///
- /// The number is not portable across SDKs. Each counts the same setting in
- /// its own terms, and `0` means something different in every one of them, so
- /// a deployment that runs several has to set this per SDK rather than copy
- /// one value across:
- ///
- /// | SDK | `N` | `0` | unlimited |
- /// | ---- | -------------------------------------- | ----------------------------------------- | ---------------- |
- /// | Rust | `N` passes after a first, unpaced one | that first pass alone | `None` |
- /// | C# | as Rust | unlimited | `0` |
- /// | Go | `N` passes, the first one of them | unlimited | `0` |
- /// | Java | `N` passes, the first one of them | one pass, and only with several endpoints | a large `N` |
- /// | Node | `N` passes, the first one of them | no pass at all | a large `N` |
+ /// Retry passes after the initial bootstrap pass, and consecutive background
+ /// dial attempts per replica. `None` permits unlimited retries; `Some(0)`
+ /// permits only the initial bootstrap pass. The limit covers one reconnect
+ /// burst: while the client is signed in, each `IggyClient` heartbeat
+ /// restarts the replica links that used it up, with a fresh budget. A
+ /// transport client without `IggyClient` has no heartbeat, so only
+ /// `connect()` restarts them.
pub max_retries: Option<u32>,
- /// Delay between passes. The first pass runs at once when the client knows
- /// more than one endpoint.
+ /// Full-jitter exponential backoff base, capped at 10 seconds. The initial
+ /// bootstrap pass is immediate; every background dial waits its jitter.
pub interval: NonZeroIggyDuration,
- /// Cooldown before redialing the endpoint of the last successful
- /// connection, measured from when that connection was established rather
- /// than from when it was lost: a session that outlived this interval is
- /// redialed with no wait at all, which is the point -- the pace limit is
- /// there for connections that keep dropping straight away.
- ///
- /// Owed to that endpoint alone: the others are dialed without waiting, and
- /// the paced one goes last in the pass.
+ /// Stable connection duration that resets the retry count and backoff.
pub reestablish_after: IggyDuration,
}
diff --git a/core/common/src/types/configuration/tcp_config/tcp_connection_string_options.rs b/core/common/src/types/configuration/tcp_config/tcp_connection_string_options.rs
index 1c957f1c3..f6e19b866 100644
--- a/core/common/src/types/configuration/tcp_config/tcp_connection_string_options.rs
+++ b/core/common/src/types/configuration/tcp_config/tcp_connection_string_options.rs
@@ -16,13 +16,14 @@
// under the License.
use crate::{
- ConnectionStringOptions, IggyDuration, IggyError, NonZeroIggyDuration,
+ ConnectionStringOptions, IggyDuration, IggyError, NonZeroIggyDuration, PendingOperationsConfig,
TcpClientReconnectionConfig,
};
use std::str::FromStr;
#[derive(Debug)]
pub struct TcpConnectionStringOptions {
+ pending_operations: PendingOperationsConfig,
tls_enabled: bool,
tls_domain: String,
tls_ca_file: Option<String>,
@@ -32,6 +33,10 @@ pub struct TcpConnectionStringOptions {
}
impl TcpConnectionStringOptions {
+ pub fn pending_operations(&self) -> PendingOperationsConfig {
+ self.pending_operations
+ }
+
pub fn tls_enabled(&self) -> bool {
self.tls_enabled
}
@@ -64,6 +69,7 @@ impl ConnectionStringOptions for TcpConnectionStringOptions {
fn parse_options(options: &str) -> Result<TcpConnectionStringOptions, IggyError> {
let options = options.split('&').collect::<Vec<&str>>();
+ let mut pending_operations = PendingOperationsConfig::default();
let mut tls_enabled = false;
let mut tls_domain = "".to_string();
let mut tls_ca_file = None;
@@ -79,6 +85,16 @@ impl ConnectionStringOptions for TcpConnectionStringOptions {
return Err(IggyError::InvalidConnectionString);
}
match option_parts[0] {
+ "max_pending_operations" => {
+ pending_operations.max_operations = option_parts[1]
+ .parse()
+ .map_err(|_| IggyError::InvalidConnectionString)?;
+ }
+ "max_pending_operation_bytes" => {
+ pending_operations.max_bytes = option_parts[1]
+ .parse()
+ .map_err(|_| IggyError::InvalidConnectionString)?;
+ }
"tls" => {
tls_enabled = option_parts[1] == "true";
}
@@ -128,7 +144,7 @@ impl ConnectionStringOptions for TcpConnectionStringOptions {
let heartbeat_interval = NonZeroIggyDuration::from_str(heartbeat_interval.as_str())
.map_err(|_| IggyError::InvalidConnectionString)?;
- let connection_string_options = TcpConnectionStringOptions::new(
+ let mut connection_string_options = TcpConnectionStringOptions::new(
tls_enabled,
tls_domain,
tls_ca_file,
@@ -137,6 +153,7 @@ impl ConnectionStringOptions for TcpConnectionStringOptions {
nodelay,
);
+ connection_string_options.pending_operations = pending_operations;
Ok(connection_string_options)
}
}
@@ -151,6 +168,7 @@ impl TcpConnectionStringOptions {
nodelay: bool,
) -> Self {
Self {
+ pending_operations: PendingOperationsConfig::default(),
tls_enabled,
tls_domain,
tls_ca_file,
@@ -164,6 +182,7 @@ impl TcpConnectionStringOptions {
impl Default for TcpConnectionStringOptions {
fn default() -> Self {
TcpConnectionStringOptions {
+ pending_operations: PendingOperationsConfig::default(),
tls_enabled: false,
tls_domain: "".to_string(),
tls_ca_file: None,
diff --git a/core/common/src/types/configuration/websocket_config/websocket_client_config.rs b/core/common/src/types/configuration/websocket_config/websocket_client_config.rs
index 6fdd79179..5c806194a 100644
--- a/core/common/src/types/configuration/websocket_config/websocket_client_config.rs
+++ b/core/common/src/types/configuration/websocket_config/websocket_client_config.rs
@@ -17,7 +17,9 @@
use crate::types::configuration::auth_config::connection_string::ConnectionString;
use crate::types::configuration::websocket_config::websocket_connection_string_options::WebSocketConnectionStringOptions;
-use crate::{AutoLogin, NonZeroIggyDuration, WebSocketClientReconnectionConfig};
+use crate::{
+ AutoLogin, NonZeroIggyDuration, PendingOperationsConfig, WebSocketClientReconnectionConfig,
+};
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use tungstenite::protocol::WebSocketConfig as TungsteniteConfig;
@@ -29,6 +31,8 @@ pub struct WebSocketClientConfig {
pub server_address: String,
/// Whether to automatically login user after establishing connection.
pub auto_login: AutoLogin,
+ /// Shared limits across this client's mutation lanes.
+ pub pending_operations: PendingOperationsConfig,
/// Whether to automatically reconnect when disconnected.
pub reconnection: WebSocketClientReconnectionConfig,
/// Interval of heartbeats sent by the client
@@ -72,6 +76,7 @@ impl Default for WebSocketClientConfig {
WebSocketClientConfig {
server_address: "127.0.0.1:8092".to_string(),
auto_login: AutoLogin::Disabled,
+ pending_operations: PendingOperationsConfig::default(),
reconnection: WebSocketClientReconnectionConfig::default(),
heartbeat_interval: NonZeroIggyDuration::from_str("5s").unwrap(),
ws_config: WebSocketConfig::default(),
@@ -158,6 +163,7 @@ impl From<ConnectionString<WebSocketConnectionStringOptions>> for WebSocketClien
WebSocketClientConfig {
server_address: connection_string.server_address().into(),
auto_login: connection_string.auto_login().to_owned(),
+ pending_operations: connection_string.options().pending_operations(),
reconnection: connection_string.options().reconnection().to_owned(),
heartbeat_interval: connection_string.options().heartbeat_interval(),
ws_config,
diff --git a/core/common/src/types/configuration/websocket_config/websocket_client_config_builder.rs b/core/common/src/types/configuration/websocket_config/websocket_client_config_builder.rs
index 89df1ba92..33bb25f08 100644
--- a/core/common/src/types/configuration/websocket_config/websocket_client_config_builder.rs
+++ b/core/common/src/types/configuration/websocket_config/websocket_client_config_builder.rs
@@ -16,8 +16,8 @@
// under the License.
use crate::{
- AutoLogin, IggyDuration, IggyError, NonZeroIggyDuration, WebSocketClientConfig,
- validate_server_address,
+ AutoLogin, IggyDuration, IggyError, NonZeroIggyDuration, PendingOperationsConfig,
+ WebSocketClientConfig, validate_server_address,
};
/// Builder for the WebSocket client configuration.
@@ -43,6 +43,12 @@ impl WebSocketClientConfigBuilder {
self
}
+ /// Sets client-wide active and retained mutation limits.
+ pub fn with_pending_operations(mut self, pending_operations: PendingOperationsConfig) -> Self {
+ self.config.pending_operations = pending_operations;
+ self
+ }
+
/// Sets the auto sign in during connection.
pub fn with_auto_sign_in(mut self, auto_sign_in: AutoLogin) -> Self {
self.config.auto_login = auto_sign_in;
@@ -60,13 +66,13 @@ impl WebSocketClientConfigBuilder {
self
}
- /// Sets the interval between retries when connecting to the server.
+ /// Sets the full-jitter exponential backoff base, capped at 10 seconds.
pub fn with_reconnection_interval(mut self, interval: NonZeroIggyDuration) -> Self {
self.config.reconnection.interval = interval;
self
}
- /// Sets the time to wait before attempting to reestablish connection.
+ /// Sets the stable connection duration that resets the retry count and backoff.
pub fn with_reestablish_after(mut self, reestablish_after: IggyDuration) -> Self {
self.config.reconnection.reestablish_after = reestablish_after;
self
diff --git a/core/common/src/types/configuration/websocket_config/websocket_client_reconnection_config.rs b/core/common/src/types/configuration/websocket_config/websocket_client_reconnection_config.rs
index c1fed5e8e..6867db305 100644
--- a/core/common/src/types/configuration/websocket_config/websocket_client_reconnection_config.rs
+++ b/core/common/src/types/configuration/websocket_config/websocket_client_reconnection_config.rs
@@ -23,18 +23,24 @@ use std::str::FromStr;
/// WebSocket client reconnection configuration.
/// It consists of the following fields:
/// - `enabled`: whether to enable reconnection.
-/// - `max_retries`: the maximum number of retries. If None, will retry infinitely.
-/// - `interval`: the interval between retries.
-/// - `reestablish_after`: the time to wait before attempting to reestablish connection.
+/// - `max_retries`: the retries of one reconnect burst. If None, will retry infinitely.
+/// - `interval`: the full-jitter exponential backoff base, capped at 10 seconds.
+/// - `reestablish_after`: the stable connection duration that resets the retry count and backoff.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WebSocketClientReconnectionConfig {
/// Whether to enable reconnection.
pub enabled: bool,
- /// The maximum number of retries. If None, will retry infinitely.
+ /// Retry passes after the initial bootstrap pass, and consecutive background
+ /// dial attempts per replica. `None` permits unlimited retries; `Some(0)`
+ /// permits only the initial bootstrap pass. The limit covers one reconnect
+ /// burst: while the client is signed in, each `IggyClient` heartbeat
+ /// restarts the replica links that used it up, with a fresh budget. A
+ /// transport client without `IggyClient` has no heartbeat, so only
+ /// `connect()` restarts them.
pub max_retries: Option<u32>,
- /// The interval between retries.
+ /// Full-jitter exponential backoff base, capped at 10 seconds.
pub interval: NonZeroIggyDuration,
- /// The time to wait before attempting to reestablish connection.
+ /// Stable connection duration that resets the retry count and backoff.
pub reestablish_after: IggyDuration,
}
diff --git a/core/common/src/types/configuration/websocket_config/websocket_connection_string_options.rs b/core/common/src/types/configuration/websocket_config/websocket_connection_string_options.rs
index 6bd0a4a33..f90f50df2 100644
--- a/core/common/src/types/configuration/websocket_config/websocket_connection_string_options.rs
+++ b/core/common/src/types/configuration/websocket_config/websocket_connection_string_options.rs
@@ -16,13 +16,14 @@
// under the License.
use crate::{
- ConnectionStringOptions, IggyDuration, IggyError, NonZeroIggyDuration,
+ ConnectionStringOptions, IggyDuration, IggyError, NonZeroIggyDuration, PendingOperationsConfig,
WebSocketClientReconnectionConfig,
};
use std::str::FromStr;
#[derive(Debug, Clone)]
pub struct WebSocketConnectionStringOptions {
+ pending_operations: PendingOperationsConfig,
heartbeat_interval: NonZeroIggyDuration,
reconnection: WebSocketClientReconnectionConfig,
@@ -41,6 +42,10 @@ pub struct WebSocketConnectionStringOptions {
}
impl WebSocketConnectionStringOptions {
+ pub fn pending_operations(&self) -> PendingOperationsConfig {
+ self.pending_operations
+ }
+
pub fn heartbeat_interval(&self) -> NonZeroIggyDuration {
self.heartbeat_interval
}
@@ -113,6 +118,16 @@ impl ConnectionStringOptions for WebSocketConnectionStringOptions {
}
match parts[0] {
+ "max_pending_operations" => {
+ parsed_options.pending_operations.max_operations = parts[1]
+ .parse()
+ .map_err(|_| IggyError::InvalidConnectionString)?;
+ }
+ "max_pending_operation_bytes" => {
+ parsed_options.pending_operations.max_bytes = parts[1]
+ .parse()
+ .map_err(|_| IggyError::InvalidConnectionString)?;
+ }
"heartbeat_interval" => {
parsed_options.heartbeat_interval = NonZeroIggyDuration::from_str(parts[1])
.map_err(|_| IggyError::InvalidConnectionString)?;
@@ -195,6 +210,7 @@ impl ConnectionStringOptions for WebSocketConnectionStringOptions {
impl Default for WebSocketConnectionStringOptions {
fn default() -> Self {
WebSocketConnectionStringOptions {
+ pending_operations: PendingOperationsConfig::default(),
heartbeat_interval: NonZeroIggyDuration::from_str("5s").unwrap(),
reconnection: WebSocketClientReconnectionConfig::default(),
read_buffer_size: None,
diff --git a/core/common/src/types/identifier/mod.rs b/core/common/src/types/identifier/mod.rs
index 28439a779..8cf8e33a5 100644
--- a/core/common/src/types/identifier/mod.rs
+++ b/core/common/src/types/identifier/mod.rs
@@ -19,6 +19,7 @@ use crate::Sizeable;
use crate::Validatable;
use crate::error::IggyError;
use crate::utils::byte_size::IggyByteSize;
+use iggy_binary_protocol::WireIdentifier;
use serde::{Deserialize, Serialize};
use serde_with::base64::Base64;
use serde_with::serde_as;
@@ -259,6 +260,17 @@ impl TryFrom<u32> for Identifier {
}
}
+impl TryFrom<&WireIdentifier> for Identifier {
+ type Error = IggyError;
+
+ fn try_from(value: &WireIdentifier) -> Result<Self, Self::Error> {
+ match value {
+ WireIdentifier::Numeric(id) => Self::numeric(*id),
+ WireIdentifier::String(name) => Self::named(name),
+ }
+ }
+}
+
impl TryFrom<String> for Identifier {
type Error = IggyError;
fn try_from(value: String) -> Result<Self, Self::Error> {
diff --git a/core/connectors/runtime/src/main.rs b/core/connectors/runtime/src/main.rs
index c53e28f20..87245472c 100644
--- a/core/connectors/runtime/src/main.rs
+++ b/core/connectors/runtime/src/main.rs
@@ -46,6 +46,7 @@ use state::StateStorage;
use std::{
collections::HashMap,
env,
+ num::NonZeroU32,
sync::{Arc, atomic::AtomicU32},
};
use system_stats::capture_allowed_cpus;
@@ -584,6 +585,7 @@ struct SourceConnectorPlugin {
struct SourceConnectorProducer {
encoder: Arc<dyn StreamEncoder>,
producer: IggyProducer,
+ batch_length: NonZeroU32,
}
struct SourceConnectorWrapper {
diff --git a/core/connectors/runtime/src/manager/source.rs b/core/connectors/runtime/src/manager/source.rs
index 44e0cf667..eb8e8d07e 100644
--- a/core/connectors/runtime/src/manager/source.rs
+++ b/core/connectors/runtime/src/manager/source.rs
@@ -266,7 +266,7 @@ impl SourceManager {
let instance_guard =
source::SourceInstanceGuard::for_container(container.clone(), plugin_id, key);
- let (producer, encoder, transforms) =
+ let (producer, batch_length, encoder, transforms) =
match source::setup_source_producer(key, config, iggy_client).await {
Ok(parts) => parts,
Err(error) => {
@@ -304,6 +304,7 @@ impl SourceManager {
config.verbose,
config.benchmark,
producer,
+ batch_length,
encoder,
transforms,
state_storage,
diff --git a/core/connectors/runtime/src/source.rs b/core/connectors/runtime/src/source.rs
index 36f4eb239..3a9191efe 100644
--- a/core/connectors/runtime/src/source.rs
+++ b/core/connectors/runtime/src/source.rs
@@ -18,11 +18,12 @@
use dashmap::DashMap;
use dlopen2::wrapper::Container;
use flume::{Receiver, Sender};
+use iggy::clients::MAX_BATCH_LENGTH;
use iggy::prelude::{
- DirectConfig, HeaderKey, HeaderValue, Identifier, IggyClient, IggyDuration, IggyError,
+ Client, DirectConfig, HeaderKey, HeaderValue, Identifier, IggyClient, IggyDuration, IggyError,
IggyMessage, IggyProducer, StreamClient, TopicClient, TopicCreateOptions,
};
-use iggy_common::{Durability, TopicRuntimeOptions};
+use iggy_common::{BINARY_OPERATION_TIMEOUT, Durability, TopicRuntimeOptions};
use iggy_connector_sdk::encoders::avro::{AvroEncoderConfig, AvroStreamEncoder};
use iggy_connector_sdk::{
ConnectorState, DecodedMessage, Error as SdkError, ProducedMessages, Schema, StreamEncoder,
@@ -36,6 +37,7 @@ use iggy_connector_sdk::{
use std::{
collections::{BTreeMap, HashMap},
future::Future,
+ num::NonZeroU32,
str::FromStr,
sync::{Arc, LazyLock, atomic::Ordering},
time::Instant,
@@ -60,6 +62,7 @@ use prometheus_client::metrics::counter::Counter;
use tokio::runtime::Handle;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
+use tokio::time::timeout;
const MAX_FAILED_TAIL_RETRIES: u32 = 3;
const SOURCE_TOPIC_MESSAGES_REQUIRED_TO_SAVE: u32 = 1;
@@ -254,7 +257,7 @@ pub async fn init(
};
match setup_source_producer(&key, &config, iggy_client).await {
- Ok((producer, encoder, transforms)) => {
+ Ok((producer, batch_length, encoder, transforms)) => {
let connector = source_connectors
.get_mut(&path)
.expect("source connector was inserted above");
@@ -263,7 +266,11 @@ pub async fn init(
.iter_mut()
.find(|plugin| plugin.id == plugin_id)
.expect("source plugin was pushed above");
- plugin.producer = Some(SourceConnectorProducer { producer, encoder });
+ plugin.producer = Some(SourceConnectorProducer {
+ encoder,
+ producer,
+ batch_length,
+ });
plugin.transforms = transforms;
instance_guard.disarm();
info!(
@@ -437,6 +444,8 @@ impl Drop for SourceInstanceGuard {
}
}
+/// Returns the last stream's producer, the batch length that splits its
+/// sends into requests, its encoder and the transforms.
pub(crate) async fn setup_source_producer(
key: &str,
config: &SourceConfig,
@@ -444,6 +453,7 @@ pub(crate) async fn setup_source_producer(
) -> Result<
(
IggyProducer,
+ NonZeroU32,
Arc<dyn StreamEncoder>,
Vec<Arc<dyn Transform>>,
),
@@ -469,7 +479,10 @@ pub(crate) async fn setup_source_producer(
RuntimeError::InvalidConfiguration(format!("Invalid linger time: {error}"))
})?;
ensure_durable_source_topic(iggy_client, &stream.stream, &stream.topic).await?;
- let batch_length = stream.batch_length.unwrap_or(1000);
+ // Passed explicitly for 0 as well, so the producer splits a send
+ // exactly where `send_with_failed_tail_retries` expects.
+ let batch_length =
+ NonZeroU32::new(stream.batch_length.unwrap_or(1000)).unwrap_or(MAX_BATCH_LENGTH);
let producer = iggy_client
.producer(&stream.stream, &stream.topic)?
// The topic was validated above. If it disappears before init,
@@ -478,7 +491,7 @@ pub(crate) async fn setup_source_producer(
.do_not_create_topic_if_not_exists()
.direct(
DirectConfig::builder()
- .batch_length(batch_length)
+ .batch_length(batch_length.get())
.linger_time(linger_time)
.build(),
)
@@ -501,17 +514,17 @@ pub(crate) async fn setup_source_producer(
other => other.encoder(),
};
last_encoder = Some(encoder);
- last_producer = Some(producer);
+ last_producer = Some((producer, batch_length));
}
- let producer = last_producer.ok_or_else(|| {
+ let (producer, batch_length) = last_producer.ok_or_else(|| {
RuntimeError::InvalidConfiguration("No streams configured for source".to_string())
})?;
let encoder = last_encoder.ok_or_else(|| {
RuntimeError::InvalidConfiguration("No encoder configured for source".to_string())
})?;
- Ok((producer, encoder, transforms))
+ Ok((producer, batch_length, encoder, transforms))
}
async fn ensure_durable_source_topic(
@@ -572,6 +585,7 @@ pub(crate) async fn source_forwarding_loop(
verbose: bool,
benchmark: bool,
producer: IggyProducer,
+ batch_length: NonZeroU32,
encoder: Arc<dyn StreamEncoder>,
transforms: Vec<Arc<dyn Transform>>,
state_storage: StateStorage,
@@ -692,9 +706,19 @@ pub(crate) async fn source_forwarding_loop(
let send_result = if state_unavailable {
Err(IggyError::Error)
} else if processing_errors == 0 {
- send_with_failed_tail_retries(processed.messages, plugin_id, |messages| {
- producer.send(messages)
- })
+ send_with_failed_tail_retries(
+ processed.messages,
+ batch_length,
+ plugin_id,
+ &context.iggy_clients.producer,
+ |messages| producer.send(messages),
+ |op| {
+ context
+ .iggy_clients
+ .producer
+ .resolve_operation(op, Instant::now() + BINARY_OPERATION_TIMEOUT)
+ },
+ )
.await
} else {
Err(IggyError::Error)
@@ -889,6 +913,7 @@ pub(crate) fn spawn_source_handler(
verbose: bool,
benchmark: bool,
producer: IggyProducer,
+ batch_length: NonZeroU32,
encoder: Arc<dyn StreamEncoder>,
transforms: Vec<Arc<dyn Transform>>,
state_storage: StateStorage,
@@ -920,6 +945,7 @@ pub(crate) fn spawn_source_handler(
verbose,
benchmark,
producer,
+ batch_length,
encoder,
transforms,
state_storage,
@@ -990,6 +1016,7 @@ pub fn handle(
plugin.verbose,
plugin.benchmark,
producer_wrapper.producer,
+ producer_wrapper.batch_length,
producer_wrapper.encoder,
plugin.transforms,
plugin.state_storage,
@@ -1087,14 +1114,19 @@ fn process_messages(
}
}
-async fn send_with_failed_tail_retries<F, Fut, T>(
+async fn send_with_failed_tail_retries<S, SendFut, T, R, ResolveFut>(
mut messages: Vec<IggyMessage>,
+ batch_length: NonZeroU32,
plugin_id: u32,
- mut send: F,
+ client: &IggyClient,
+ mut send: S,
+ mut resolve: R,
) -> Result<(), IggyError>
where
- F: FnMut(Vec<IggyMessage>) -> Fut,
- Fut: Future<Output = Result<T, IggyError>>,
+ S: FnMut(Vec<IggyMessage>) -> SendFut,
+ SendFut: Future<Output = Result<T, IggyError>>,
+ R: FnMut(u64) -> ResolveFut,
+ ResolveFut: Future<Output = Result<(), IggyError>>,
{
let mut retry = 0;
loop {
@@ -1108,11 +1140,21 @@ where
topic_name,
}) => {
warn!(
+ cause_code = cause.as_code(),
"Source connector with ID: {plugin_id} send failed after {} chunks committed; {} messages remain",
committed.len(),
failed.len()
);
- if retry >= MAX_FAILED_TAIL_RETRIES || failed.is_empty() {
+ // Exhausted SDK reconnect tasks need an explicit connect. A possibly
+ // submitted binary chunk returns OperationUncertain instead.
+ if retry >= MAX_FAILED_TAIL_RETRIES
+ || failed.is_empty()
+ || (matches!(*cause, IggyError::NotConnected | IggyError::Disconnected)
+ && !matches!(
+ timeout(BINARY_OPERATION_TIMEOUT, client.connect()).await,
+ Ok(Ok(()))
+ ))
+ {
return Err(IggyError::ProducerSendFailed {
cause,
failed,
@@ -1134,6 +1176,16 @@ where
});
}
};
+ // The tail starts with the chunk that `op` sent. A resend under
+ // a new request id would append it twice if it committed, so
+ // only a proved commit lets the rest go out.
+ if let IggyError::OperationUncertain(op) = *cause {
+ resolve(op).await?;
+ messages.drain(..messages.len().min(batch_length.get() as usize));
+ if messages.is_empty() {
+ return Ok(());
+ }
+ }
retry += 1;
}
Err(error) => return Err(error),
@@ -1220,7 +1272,7 @@ mod tests {
use iggy_connector_sdk::source::SendCallback;
use secrecy::SecretString;
use std::collections::VecDeque;
- use std::future::ready;
+ use std::future::{Ready, ready};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::time::Duration;
@@ -1327,6 +1379,7 @@ mod tests {
false,
false,
producer,
+ NonZeroU32::MIN,
Schema::Raw.encoder(),
vec![],
state_storage,
@@ -1387,6 +1440,24 @@ mod tests {
}
}
+ /// A send whose first chunk of `messages` was operation `op` and may
+ /// have committed.
+ fn uncertain_send(op: u64, messages: Vec<IggyMessage>) -> IggyError {
+ let mut failure = failed_send(messages);
+ if let IggyError::ProducerSendFailed { cause, .. } = &mut failure {
+ **cause = IggyError::OperationUncertain(op);
+ }
+ failure
+ }
+
+ fn no_resolve(op: u64) -> Ready<Result<(), IggyError>> {
+ panic!("operation {op} must not be resolved");
+ }
+
+ fn markers(messages: &[IggyMessage]) -> Vec<u8> {
+ messages.iter().map(|message| message.payload[0]).collect()
+ }
+
/// A close that records the ids it was handed and answers `result`.
///
/// The guard takes its close as a closure, so each test owns its recorder
@@ -1726,6 +1797,7 @@ mod tests {
false,
false,
producer,
+ NonZeroU32::MIN,
Schema::Raw.encoder(),
vec![],
state_storage,
@@ -1819,6 +1891,7 @@ mod tests {
false,
false,
producer,
+ NonZeroU32::MIN,
Schema::Raw.encoder(),
vec![],
state_storage,
@@ -1954,7 +2027,9 @@ mod tests {
let result = send_with_failed_tail_retries(
vec![test_message(1), test_message(2), test_message(3)],
+ NonZeroU32::MIN,
31,
+ &IggyClient::default(),
|messages| {
attempts.push(
messages
@@ -1964,6 +2039,7 @@ mod tests {
);
ready(responses.pop_front().expect("send response should exist"))
},
+ no_resolve,
)
.await;
@@ -1983,10 +2059,17 @@ mod tests {
.collect::<Vec<_>>(),
);
- let result = send_with_failed_tail_retries(vec![test_message(1)], 37, |_| {
- attempts += 1;
- ready(responses.pop_front().expect("send response should exist"))
- })
+ let result = send_with_failed_tail_retries(
+ vec![test_message(1)],
+ NonZeroU32::MIN,
+ 37,
+ &IggyClient::default(),
+ |_| {
+ attempts += 1;
+ ready(responses.pop_front().expect("send response should exist"))
+ },
+ no_resolve,
+ )
.await;
assert!(matches!(result, Err(IggyError::ProducerSendFailed { .. })));
@@ -2009,16 +2092,159 @@ mod tests {
}));
let mut attempts = 0;
- let result =
- send_with_failed_tail_retries(vec![test_message(1), test_message(2)], 41, |_| {
+ let result = send_with_failed_tail_retries(
+ vec![test_message(1), test_message(2)],
+ NonZeroU32::MIN,
+ 41,
+ &IggyClient::default(),
+ |_| {
attempts += 1;
ready(response.take().expect("send response should exist"))
- })
- .await;
+ },
+ no_resolve,
+ )
+ .await;
assert!(matches!(result, Err(IggyError::ProducerSendFailed { .. })));
assert_eq!(attempts, 1);
assert_eq!(retained.len(), 1);
});
}
+
+ #[test]
+ fn given_unsent_tail_when_reconnect_fails_should_preserve_the_original_failure() {
+ let runtime = tokio::runtime::Runtime::new().expect("failed to create test runtime");
+ runtime.block_on(async {
+ for failure_cause in [IggyError::NotConnected, IggyError::Disconnected] {
+ let client = IggyClient::default();
+ client.shutdown().await.expect("client should shut down");
+ let mut failure = failed_send(vec![test_message(2), test_message(3)]);
+ let IggyError::ProducerSendFailed { cause, .. } = &mut failure else {
+ panic!("expected producer failure");
+ };
+ **cause = failure_cause.clone();
+ let mut responses = VecDeque::from([Err(failure), Ok(())]);
+ let mut attempts = 0;
+
+ let result = send_with_failed_tail_retries(
+ vec![test_message(1), test_message(2), test_message(3)],
+ NonZeroU32::MIN,
+ 43,
+ &client,
+ |_| {
+ attempts += 1;
+ ready(responses.pop_front().expect("send response should exist"))
+ },
+ no_resolve,
+ )
+ .await;
+
+ let Err(IggyError::ProducerSendFailed {
+ cause,
+ failed,
+ committed,
+ stream_name,
+ topic_name,
+ }) = result
+ else {
+ panic!("reconnect failure must preserve the producer failure");
+ };
+ assert_eq!(*cause, failure_cause);
+ assert_eq!(
+ failed
+ .iter()
+ .map(|message| message.payload[0])
+ .collect::<Vec<_>>(),
+ [2, 3]
+ );
+ assert!(committed.is_empty());
+ assert_eq!(stream_name, "test-stream");
+ assert_eq!(topic_name, "test-topic");
+ assert_eq!(attempts, 1, "reconnect failure must not resubmit the tail");
+ }
+ });
+ }
+
+ #[test]
+ fn given_uncertain_chunk_when_resolve_proves_it_should_resend_only_the_rest() {
+ let runtime = tokio::runtime::Runtime::new().expect("failed to create test runtime");
+ runtime.block_on(async {
+ let failed = vec![test_message(1), test_message(2), test_message(3)];
+ let mut responses = VecDeque::from([Err(uncertain_send(7, failed)), Ok(())]);
+ let mut attempts = Vec::new();
+ let mut resolved = Vec::new();
+
+ let result = send_with_failed_tail_retries(
+ vec![test_message(1), test_message(2), test_message(3)],
+ NonZeroU32::MIN,
+ 47,
+ &IggyClient::default(),
+ |messages| {
+ attempts.push(markers(&messages));
+ ready(responses.pop_front().expect("send response should exist"))
+ },
+ |op| {
+ resolved.push(op);
+ ready(Ok(()))
+ },
+ )
+ .await;
+
+ assert_eq!(result, Ok(()));
+ assert_eq!(attempts, [vec![1, 2, 3], vec![2, 3]]);
+ assert_eq!(resolved, [7]);
+ });
+ }
+
+ #[test]
+ fn given_uncertain_chunk_when_resolve_fails_should_return_that_error_without_a_resend() {
+ let runtime = tokio::runtime::Runtime::new().expect("failed to create test runtime");
+ runtime.block_on(async {
+ let failed = vec![test_message(1), test_message(2), test_message(3)];
+ let mut responses = VecDeque::from([Err(uncertain_send(7, failed)), Ok(())]);
+ let mut attempts = Vec::new();
+
+ let result = send_with_failed_tail_retries(
+ vec![test_message(1), test_message(2), test_message(3)],
+ NonZeroU32::MIN,
+ 53,
+ &IggyClient::default(),
+ |messages| {
+ attempts.push(markers(&messages));
+ ready(responses.pop_front().expect("send response should exist"))
+ },
+ |op| ready(Err(IggyError::OperationNotRetained(op))),
+ )
+ .await;
+
+ assert_eq!(result, Err(IggyError::OperationNotRetained(7)));
+ assert_eq!(attempts, [vec![1, 2, 3]]);
+ });
+ }
+
+ #[test]
+ fn given_uncertain_last_chunk_when_resolve_proves_it_should_not_send_again() {
+ let runtime = tokio::runtime::Runtime::new().expect("failed to create test runtime");
+ runtime.block_on(async {
+ let failed = vec![test_message(1), test_message(2), test_message(3)];
+ let mut responses = VecDeque::from([Err(uncertain_send(7, failed)), Ok(())]);
+ let mut attempts = Vec::new();
+
+ let result = send_with_failed_tail_retries(
+ vec![test_message(1), test_message(2), test_message(3)],
+ NonZeroU32::new(1000).expect("batch length is not zero"),
+ 59,
+ &IggyClient::default(),
+ |messages| {
+ attempts.push(markers(&messages));
+ ready(responses.pop_front().expect("send response should exist"))
+ },
+ |_| ready(Ok(())),
+ )
+ .await;
+
+ assert_eq!(result, Ok(()));
+ assert_eq!(attempts, [vec![1, 2, 3]]);
+ });
+ }
}
diff --git a/core/connectors/sdk/README.md b/core/connectors/sdk/README.md
index a0e053ec5..a7060515f 100644
--- a/core/connectors/sdk/README.md
+++ b/core/connectors/sdk/README.md
@@ -16,6 +16,8 @@ Source connectors use a one-in-flight-batch contract between the plugin and the
An empty batch follows the same handshake. A source should return `state: None` when an empty poll made no progress; this avoids an unnecessary state write and cannot persist state left over from a failed batch. Producer errors, including request timeouts, report a NACK. A successful send from the legacy Iggy server is still an ACK even though that server returns an empty confirmation list.
+The runtime resolves a send request with an unknown outcome before it sends anything again. When the resolve proves that the request committed, the runtime resends only the messages after that request. Otherwise it reports a NACK, so a replay of the batch can deliver the messages of that request again.
+
The crash behavior is intentionally at-least-once:
| Crash point | Recovery behavior |
diff --git a/core/consensus/src/client_table.rs b/core/consensus/src/client_table.rs
index b5c3ef6f6..8d249f59e 100644
--- a/core/consensus/src/client_table.rs
+++ b/core/consensus/src/client_table.rs
@@ -1936,7 +1936,10 @@ impl ClientEntry {
#[allow(clippy::cast_possible_truncation)]
mod tests {
use super::*;
- use iggy_binary_protocol::{Command, Operation};
+ use iggy_binary_protocol::{
+ Command, Operation, PrepareHeader, REJECTION_SECTION_LEN, RoutedRequestHeader, result_code,
+ write_rejection_section,
+ };
/// Arbitrary non-zero user id for register fixtures; most tests don't
/// assert on it (see `register_stores_user_id` for the accessor check).
@@ -2293,6 +2296,57 @@ mod tests {
(table, epoch)
}
+ #[test]
+ fn given_committed_rejection_when_receipt_is_restored_should_preserve_final_result_proof() {
+ const CLIENT: u128 = 1;
+ const REQUEST: u64 = 1;
+ const COMMIT: u64 = 11;
+ let (mut table, epoch) = table_with_client();
+ let request = RoutedRequestHeader {
+ client: CLIENT,
+ session: epoch,
+ request: REQUEST,
+ operation: Operation::CreateUser,
+ ..Default::default()
+ };
+ let code = IggyError::UserAlreadyExists.as_code();
+ let uncommitted = crate::build_result_rejection_reply(&request, COMMIT, code);
+ assert!(!uncommitted.header().has_committed_result());
+ let prepare = PrepareHeader {
+ client: CLIENT,
+ request: REQUEST,
+ op: COMMIT,
+ operation: request.operation,
+ ..Default::default()
+ };
+ let committed = crate::build_reply_message_with(&prepare, REJECTION_SECTION_LEN, |body| {
+ write_rejection_section(body, code);
+ });
+ assert_eq!(uncommitted.header().op, committed.header().op);
+ assert_eq!(uncommitted.header().commit, committed.header().commit);
+ assert_eq!(uncommitted.body(), committed.body());
+ assert!(committed.header().has_committed_result());
+ assert_eq!(
+ table.commit_reply(CLIENT, TEST_USER_ID, committed.clone()),
+ CommitReply::Cached
+ );
+
+ for restored in [
+ ClientTable::from_snapshot(table.to_snapshot()).unwrap(),
+ ClientTable::decode(&table.encode()).unwrap(),
+ ] {
+ let RequestStatus::Duplicate(reply) =
+ restored.check_request(CLIENT, epoch, REQUEST, request.operation)
+ else {
+ panic!("restored committed rejection must remain available to a retry");
+ };
+ assert_eq!(reply.as_bytes(), committed.as_slice());
+ let reply = reply.into_message();
+ assert!(reply.header().has_committed_result());
+ assert_eq!(result_code(reply.body()), Some(code));
+ }
+ }
+
// Registration tests
#[test]
diff --git a/core/consensus/src/plane_helpers.rs b/core/consensus/src/plane_helpers.rs
index 006da97a6..78e54da70 100644
--- a/core/consensus/src/plane_helpers.rs
+++ b/core/consensus/src/plane_helpers.rs
@@ -629,13 +629,13 @@ where
/// Builds a `Reply` carrying only a single-entry result section, no payload:
/// the generic `[count=1][index=0][result=code]` rejection frame.
///
-/// Two families of `code` ride this frame. `TransientNotCommitted` marks a
-/// request that could not be committed *right now* (not-caught-up / in-flight
-/// / pipeline-full / view-change cancel); the SDK decodes it and replays the
-/// same `request_id` immediately instead of waiting out its response
-/// read-timeout. Any other code is a TERMINAL rejection (e.g. a committed
-/// metadata rejection like `UserAlreadyExists`) that the SDK surfaces as the
-/// typed error.
+/// `TransientNotCommitted` marks a request that could not be committed right
+/// now (not-caught-up / in-flight / pipeline-full / view-change cancel).
+/// Other codes describe pre-consensus rejections. Neither proves the final
+/// result of an earlier uncertain attempt with the same request identity, so
+/// the header carries no commit marker. A caller that refuses a replay of a
+/// request that committed swaps in the committed reply's header instead, as
+/// the metadata plane does for a replayed `CreatePersonalAccessToken`.
///
/// Stamped from the request header (no prepare exists for a rejected op).
/// `commit` is the primary's current commit position and is informational
diff --git a/core/integration/tests/cluster/client_table_restart.rs b/core/integration/tests/cluster/client_table_restart.rs
index 96537fc3a..ec263f477 100644
--- a/core/integration/tests/cluster/client_table_restart.rs
+++ b/core/integration/tests/cluster/client_table_restart.rs
@@ -53,7 +53,9 @@ use crate::server::raw_tcp::TEST_BIND_SECRET;
use bytes::Bytes;
use iggy::prelude::*;
use iggy_binary_protocol::codec::{WireDecode, WireEncode};
-use iggy_binary_protocol::codes::{GET_POLL_ROUTING_CODE, PING_CODE, POLL_MESSAGES_CODE};
+use iggy_binary_protocol::codes::{
+ CREATE_STREAM_CODE, GET_PARTITION_ROUTE_CODE, PING_CODE, POLL_MESSAGES_CODE,
+};
use iggy_binary_protocol::consensus::{
Command, Operation, ReplyHeader, RequestHeader, read_size_field, result_code,
result_section_len,
@@ -61,12 +63,12 @@ use iggy_binary_protocol::consensus::{
use iggy_binary_protocol::primitives::consumer::WireConsumer;
use iggy_binary_protocol::primitives::polling_strategy::WirePollingStrategy;
use iggy_binary_protocol::requests::consumer_groups::JoinConsumerGroupRequest;
-use iggy_binary_protocol::requests::messages::PollMessagesRequest;
+use iggy_binary_protocol::requests::messages::{GetPartitionRouteRequest, PollMessagesRequest};
use iggy_binary_protocol::requests::streams::CreateStreamRequest;
use iggy_binary_protocol::requests::system::{BindSessionRequest, SessionIdentity};
use iggy_binary_protocol::requests::users::LoginRegisterRequest;
use iggy_binary_protocol::requests::users::login_register::BindSecret;
-use iggy_binary_protocol::responses::messages::{PollMessagesResponse, PollRoutingResponse};
+use iggy_binary_protocol::responses::messages::{PartitionRouteResponse, PollMessagesResponse};
use iggy_binary_protocol::responses::users::LoginRegisterResponse;
use iggy_binary_protocol::{
ClientVersionInfo, HEADER_SIZE, IGGY_PROTOCOL_VERSION, WireIdentifier, WireName, WireOptions,
@@ -412,7 +414,9 @@ pub(super) async fn commit_request(
request: u64,
body: &Bytes,
) -> CommittedReply {
- let header = request_header(Operation::CreateStream, session, request, body.len());
+ let header =
+ RequestHeader::for_request(CREATE_STREAM_CODE, CLIENT_ID, request, session, body).unwrap();
+ assert_ne!(header.request_checksum, header.checksum);
commit_request_header(stream, &header, body).await
}
@@ -424,7 +428,20 @@ async fn commit_request_header(
let deadline = Instant::now() + COMMIT_BUDGET;
loop {
match exchange(stream, header, body).await.verdict() {
- Verdict::Success(reply) => return reply,
+ Verdict::Success(reply) => {
+ let receipt =
+ bytemuck::checked::try_pod_read_unaligned::<ReplyHeader>(reply.header.as_ref())
+ .unwrap();
+ assert!(receipt.has_committed_result());
+ assert_eq!(receipt.client, header.client);
+ assert_eq!(receipt.request, header.request);
+ assert_eq!(receipt.request_checksum, header.request_checksum);
+ assert_eq!(receipt.operation, header.operation);
+ assert_eq!(receipt.partition_incarnation, header.partition_incarnation);
+ assert_ne!(receipt.op, 0);
+ assert_eq!(receipt.op, receipt.commit);
+ return reply;
+ }
Verdict::Rejected(code) if is_transient(code) && Instant::now() < deadline => {
sleep(RETRY_PAUSE).await;
}
@@ -481,7 +498,9 @@ pub(super) async fn resume_request(
continue;
}
};
- let header = request_header(Operation::CreateStream, resumed, request, body.len());
+ let header =
+ RequestHeader::for_request(CREATE_STREAM_CODE, CLIENT_ID, request, resumed, body)
+ .unwrap();
match exchange(&mut stream, &header, body).await.verdict() {
Verdict::Success(reply) => {
if let Some(original) = expect_replay_of {
@@ -753,16 +772,25 @@ async fn given_full_registry_when_new_clients_arrive_should_preserve_live_member
auto_commit: true,
};
let first_poll = poll_request.to_bytes();
- let mut routing_header = request_header(Operation::NonReplicated, session, 0, first_poll.len());
+ let route_request = GetPartitionRouteRequest {
+ stream_id: poll_request.stream_id.clone(),
+ topic_id: poll_request.topic_id.clone(),
+ partition_id: 0,
+ }
+ .to_bytes();
+ let mut routing_header =
+ request_header(Operation::NonReplicated, session, 0, route_request.len());
routing_header.reserved[..size_of::<u32>()]
- .copy_from_slice(&GET_POLL_ROUTING_CODE.to_le_bytes());
+ .copy_from_slice(&GET_PARTITION_ROUTE_CODE.to_le_bytes());
let Exchange::Reply {
status: 0, body, ..
- } = exchange(&mut member, &routing_header, &first_poll).await
+ } = exchange(&mut member, &routing_header, &route_request).await
else {
panic!("the installed owner must discover its poll context");
};
- let context = PollRoutingResponse::decode_from(&body).unwrap().context;
+ let context = PartitionRouteResponse::decode_from(&body)
+ .unwrap()
+ .context();
let mut first_header = request_header(Operation::NonReplicated, session, 0, first_poll.len());
first_header.reserved[..size_of::<u32>()].copy_from_slice(&POLL_MESSAGES_CODE.to_le_bytes());
context.stamp(&mut first_header);
diff --git a/core/integration/tests/cluster/failover_client_continuity.rs b/core/integration/tests/cluster/failover_client_continuity.rs
index a52c01123..1e0f3ace7 100644
--- a/core/integration/tests/cluster/failover_client_continuity.rs
+++ b/core/integration/tests/cluster/failover_client_continuity.rs
@@ -17,17 +17,9 @@
//! Client continuity across a primary SIGKILL.
//!
-//! A producing SDK client pinned to the primary must, after the primary dies,
-//! complete its next operation against the surviving quorum within a small
-//! budget and without an authentication error. Three separate pieces of
-//! client state make that possible, and the test fails if any one of them is
-//! lost: the endpoints the cluster roster named while the connection was
-//! healthy (the roster is unreachable exactly when it is needed), the
-//! credentials the sign-in succeeded with (this harness client signs in by
-//! hand rather than configuring `AutoLogin`, and a reconnect has to
-//! re-establish the session on whichever node answers), and a reconnect that
-//! dials those endpoints in turn instead of redialing the address the client
-//! was configured with.
+//! A producing SDK client must reach the surviving partition primary after
+//! SIGKILL without replacing its session. Partition and metadata primaries
+//! move independently, so verify each route through an operation on its plane.
use std::time::Duration;
@@ -38,6 +30,7 @@ use tokio::time::sleep;
const STREAM_NAME: &str = "failover-stream";
const TOPIC_NAME: &str = "failover-topic";
+const GROUP_NAME: &str = "failover-session";
const PARTITION_ID: u32 = 0;
/// Acks the pinned producer must capture before the kill, so the session is
@@ -118,6 +111,24 @@ async fn given_a_client_producing_when_its_primary_is_killed_should_resume_witho
let stream = Identifier::named(STREAM_NAME).unwrap();
let topic = Identifier::named(TOPIC_NAME).unwrap();
let partitioning = Partitioning::partition_id(PARTITION_ID);
+ let group = producer
+ .create_consumer_group(&stream, &topic, GROUP_NAME)
+ .await
+ .expect("create the session continuity group");
+ producer
+ .join_consumer_group(&stream, &topic, &Identifier::numeric(group.id).unwrap())
+ .await
+ .expect("join the session continuity group");
+ let memberships_before = producer
+ .get_me()
+ .await
+ .expect("read the producer's pre-kill session membership")
+ .consumer_groups;
+ assert_eq!(
+ memberships_before.len(),
+ 1,
+ "the producer must have a membership identifying its VSR session"
+ );
let warmup_deadline = tokio::time::Instant::now() + WARMUP_TIMEOUT;
let mut acked = 0usize;
@@ -170,14 +181,35 @@ async fn given_a_client_producing_when_its_primary_is_killed_should_resume_witho
resumed,
"a client pinned to a killed primary must complete its next operation against \
the surviving quorum within {RESUME_BUDGET:?}: the roster learned while the \
- connection was healthy names the survivors, and the credentials the sign-in \
- succeeded with re-establish the session on whichever one answers \
+ connection was healthy names the survivors, and the same session remains bound \
+ on the surviving links \
({attempt} attempts, last error: {last_error:?})"
);
+ tokio::time::timeout_at(resume_deadline, producer.get_stream(&stream))
+ .await
+ .expect("metadata recovery must share the continuity budget")
+ .expect("the same session must reach the surviving metadata primary")
+ .expect("the stream must survive primary loss");
+ let memberships_after = tokio::time::timeout_at(resume_deadline, producer.get_me())
+ .await
+ .expect("session verification must share the continuity budget")
+ .expect("read the producer's recovered session membership")
+ .consumer_groups;
+ assert_eq!(
+ memberships_after.len(),
+ memberships_before.len(),
+ "the recovered session must retain its pre-kill group membership"
+ );
+ let before = &memberships_before[0];
+ let after = &memberships_after[0];
+ assert_eq!(
+ (after.stream_id, after.topic_id, after.group_id),
+ (before.stream_id, before.topic_id, before.group_id),
+ "recovery must preserve the same VSR session's group membership"
+ );
assert_ne!(
producer.get_connection_info().await.server_address,
primary_endpoint,
- "the send that resumed must have landed on a survivor, so the client has to \
- have moved off the killed primary's endpoint"
+ "connection info must name the recovered metadata primary"
);
}
diff --git a/core/integration/tests/cluster/fast_primary_rejoin.rs b/core/integration/tests/cluster/fast_primary_rejoin.rs
index 76be7396f..3074444c2 100644
--- a/core/integration/tests/cluster/fast_primary_rejoin.rs
+++ b/core/integration/tests/cluster/fast_primary_rejoin.rs
@@ -29,7 +29,12 @@
//! failure, not a durability failure.
use iggy::prelude::*;
+use iggy_binary_protocol::codes::GET_PARTITION_ROUTE_CODE;
+use iggy_binary_protocol::requests::messages::GetPartitionRouteRequest;
+use iggy_binary_protocol::responses::messages::PartitionRouteResponse;
+use iggy_binary_protocol::{WireDecode, WireEncode};
use iggy_common::store_consumer_offset::StoreConsumerOffset;
+use iggy_common::wire_conversions::identifier_to_wire;
use iggy_common::{IggyMessagesBatch, SendMessagesConfirmations};
use integration::harness::{TestHarness, disk};
use integration::iggy_harness;
@@ -272,10 +277,15 @@ async fn require_resume_after_primary_stop(
harness.stop_node(leader).expect("stop the primary");
acked.extend(require_acked_sends(&producer, "post-primary-stop", 1, RESUME_BUDGET).await);
+ producer
+ .get_stream(&Identifier::named(STREAM_NAME).unwrap())
+ .await
+ .expect("the same session must reach the surviving metadata primary")
+ .expect("the stream must survive primary loss");
assert_ne!(
producer.get_connection_info().await.server_address,
primary_endpoint,
- "the send that resumed must have landed on a survivor"
+ "connection info must name the recovered metadata primary"
);
require_readback(&producer, &acked).await;
}
@@ -398,16 +408,26 @@ async fn given_a_websocket_producer_when_its_first_roster_hop_is_down_should_rea
async fn given_http_writes_on_a_rejoined_backup_when_the_primary_moved_should_forward_once(
harness: &mut TestHarness,
) {
- let (producer, leader, primary_endpoint, mut acked) =
+ let (producer, leader, _, mut acked) =
warmed_producer_past_follower_restart(harness, TransportProtocol::Tcp, None).await;
harness
.restart_node(leader)
.expect("restart the primary with its data intact");
acked.extend(require_acked_sends(&producer, "settled-primary", 1, RESUME_BUDGET).await);
+ let route_request = GetPartitionRouteRequest {
+ stream_id: identifier_to_wire(&Identifier::named(STREAM_NAME).unwrap()).unwrap(),
+ topic_id: identifier_to_wire(&Identifier::named(TOPIC_NAME).unwrap()).unwrap(),
+ partition_id: PARTITION_ID,
+ };
+ let route = producer
+ .send_binary_request(GET_PARTITION_ROUTE_CODE, route_request.to_bytes())
+ .await
+ .expect("discover the partition primary after rejoin");
+ let route = PartitionRouteResponse::decode_from(&route).unwrap();
assert_ne!(
- producer.get_connection_info().await.server_address,
- primary_endpoint,
+ usize::from(route.primary_replica),
+ leader,
"the HTTP target must be a partition backup for this test"
);
diff --git a/core/integration/tests/cluster/partition_primary_routing.rs b/core/integration/tests/cluster/partition_primary_routing.rs
index a9f27da0d..5bdb574b0 100644
--- a/core/integration/tests/cluster/partition_primary_routing.rs
+++ b/core/integration/tests/cluster/partition_primary_routing.rs
@@ -25,19 +25,21 @@ use std::str::FromStr;
use std::time::Duration;
use super::register_forwarding::connect_without_login;
+use bytes::Bytes;
use futures::StreamExt;
use iggy::prelude::*;
use iggy_binary_protocol::codes::{
- BIND_SESSION_CODE, GET_CONSUMER_GROUP_CODE, GET_PARTITION_ROUTE_CODE, GET_POLL_ROUTING_CODE,
- POLL_MESSAGES_ON_PRIMARY_CODE, STORE_CONSUMER_OFFSET_CODE,
+ BIND_SESSION_CODE, GET_CONSUMER_GROUP_CODE, GET_PARTITION_ROUTE_CODE, POLL_MESSAGES_CODE,
+ STORE_CONSUMER_OFFSET_CODE,
};
+use iggy_binary_protocol::consensus::{RequestHeader, result_code, result_section_len};
use iggy_binary_protocol::requests::consumer_groups::GetConsumerGroupRequest;
use iggy_binary_protocol::requests::consumer_offsets::StoreConsumerOffsetRequest;
use iggy_binary_protocol::requests::messages::{GetPartitionRouteRequest, PollMessagesRequest};
use iggy_binary_protocol::requests::system::BindSessionRequest;
use iggy_binary_protocol::requests::users::login_register::BindSecret;
use iggy_binary_protocol::responses::consumer_groups::ConsumerGroupDetailsResponse;
-use iggy_binary_protocol::responses::messages::{PartitionRouteResponse, PollRoutingResponse};
+use iggy_binary_protocol::responses::messages::PartitionRouteResponse;
use iggy_binary_protocol::{
ClientVersionInfo, IGGY_PROTOCOL_VERSION, WireDecode, WireEncode, WireName,
};
@@ -58,9 +60,11 @@ use integration::iggy_harness;
use journal::superblock::{PingPongSuperblock, SuperblockStore};
use reqwest::StatusCode;
use reqwest::header::RETRY_AFTER;
+use tokio::net::TcpStream;
use tokio::time::{Instant, sleep, timeout};
use crate::server::http_client::{HttpClient, applied_op, node_url, until_primary_resolved};
+use crate::server::raw_tcp;
const STREAM_NAME: &str = "partition-routing-stream";
const TOPIC_NAME: &str = "partition-routing-topic";
@@ -82,6 +86,8 @@ const GROUP_POLL_BUDGET: Duration = Duration::from_secs(20);
const DATA_FAILOVER_BUDGET: Duration = Duration::from_secs(60);
const INITIAL_VIEW: u32 = 0;
const METADATA_CHECKPOINT_REQUESTS: usize = 256;
+// Keep handcrafted requests distinct from the parent SDK session's low IDs.
+const RAW_REQUEST_START: u64 = 1 << 63;
/// Long enough for the backups to miss `cluster.heartbeat_timeout` (5s by
/// default) and conclude an election.
@@ -308,21 +314,35 @@ async fn given_any_node_when_routing_a_partition_should_name_the_same_primary(
identity: member.session_identity().await.unwrap(),
bind_secret: member.session_bind_secret().await.unwrap(),
};
+ let mut request = RequestHeader {
+ client: binding.identity.client_id,
+ session: binding.identity.session,
+ request: RAW_REQUEST_START,
+ ..Default::default()
+ };
for node in 0..harness.cluster_size() {
- let data = connect_without_login(harness.node(node).tcp_addr().unwrap()).await;
- data.send_raw_with_response(BIND_SESSION_CODE, binding.to_bytes())
- .await
- .unwrap();
- data.bind_vsr_session(binding.identity.session)
- .await
- .unwrap();
+ let mut data = raw_tcp::connect_to(harness.node(node).tcp_addr().unwrap()).await;
+ data_request(
+ &mut data,
+ &mut request,
+ BIND_SESSION_CODE,
+ &binding.to_bytes(),
+ None,
+ )
+ .await
+ .unwrap();
// A node creates its replica of a new partition after it applies
// the topic, and answers transient until then.
let route = timeout(PRECONDITION_BUDGET, async {
loop {
- match data
- .send_raw_with_response(GET_PARTITION_ROUTE_CODE, route_request.clone())
- .await
+ match data_request(
+ &mut data,
+ &mut request,
+ GET_PARTITION_ROUTE_CODE,
+ &route_request,
+ None,
+ )
+ .await
{
Ok(reply) => break PartitionRouteResponse::decode_from(&reply).unwrap(),
Err(IggyError::TransientNotAccepted) => sleep(PRECONDITION_POLL).await,
@@ -436,7 +456,12 @@ async fn given_split_primaries_when_http_auto_commits_on_a_backup_should_replica
for (message, expected) in response.messages.iter().zip(GROUP_PAYLOADS) {
assert_eq!(message.payload.as_ref(), expected.as_bytes());
}
- assert_replicated_offset(harness, &consumer, Some((GROUP_PAYLOADS.len() - 1) as u64)).await;
+ assert_routed_offset_from_each_node(
+ harness,
+ &consumer,
+ Some((GROUP_PAYLOADS.len() - 1) as u64),
+ )
+ .await;
}
/// Every partition request an HTTP caller sends to a backup runs on the
@@ -898,7 +923,7 @@ async fn assert_group_offset_routing(
assert_eq!(member.get_me().await.unwrap().client_id, before.client_id);
}
let expected_offset = (GROUP_PAYLOADS.len() - 1) as u64;
- assert_replicated_offset(harness, &consumer, Some(expected_offset)).await;
+ assert_routed_offset_from_each_node(harness, &consumer, Some(expected_offset)).await;
member
.delete_consumer_offset(&consumer, &stream, &topic, Some(PARTITION_ID))
.await
@@ -918,7 +943,7 @@ async fn assert_group_offset_routing(
.leave_consumer_group(&stream, &topic, &group)
.await
.unwrap();
- assert_replicated_offset(harness, &consumer, None).await;
+ assert_routed_offset_from_each_node(harness, &consumer, None).await;
for (group_name, policy) in [
(
"interval-offset-group",
@@ -947,7 +972,7 @@ async fn assert_group_offset_routing(
.unwrap();
}
let consumer = Consumer::group(Identifier::named(group_name).unwrap());
- assert_replicated_offset(harness, &consumer, Some(expected_offset)).await;
+ assert_routed_offset_from_each_node(harness, &consumer, Some(expected_offset)).await;
assert_eq!(
member.get_connection_info().await.server_address,
metadata_address
@@ -957,7 +982,7 @@ async fn assert_group_offset_routing(
}
}
-async fn assert_replicated_offset(
+async fn assert_routed_offset_from_each_node(
harness: &TestHarness,
consumer: &Consumer,
expected: Option<u64>,
@@ -984,14 +1009,11 @@ async fn assert_replicated_offset(
}
})
.await
- .unwrap_or_else(|_| panic!("node {node} must observe replicated offset {expected:?}"));
- assert_eq!(
- ClientWrapper::Tcp(replica)
- .get_connection_info()
- .await
- .server_address,
- address.to_string()
- );
+ .unwrap_or_else(|_| {
+ panic!(
+ "a client starting on node {node} must read offset {expected:?} from the primary"
+ )
+ });
}
}
@@ -1194,7 +1216,7 @@ async fn assert_group_auto_commit_routing(harness: &mut TestHarness, transport:
}
let expected_offset = u64::try_from(GROUP_PAYLOADS.len() - 1).unwrap();
- assert_replicated_offset(harness, &consumer, Some(expected_offset)).await;
+ assert_routed_offset_from_each_node(harness, &consumer, Some(expected_offset)).await;
let partition_primary = assert_cached_route_after_primary_loss(
harness,
&member,
@@ -1254,29 +1276,22 @@ async fn assert_cached_route_after_primary_loss(
.unwrap();
let coordinator = member.get_connection_info().await.server_address;
harness.kill_node(previous_primary).unwrap();
- let poll = PollMessagesRequest {
- consumer: consumer_to_wire(consumer).unwrap(),
+ let route_request = GetPartitionRouteRequest {
stream_id: identifier_to_wire(stream).unwrap(),
topic_id: identifier_to_wire(topic).unwrap(),
- partition_id: Some(PARTITION_ID),
- strategy: polling_strategy_to_wire(&PollingStrategy::next()),
- count: 1,
- auto_commit: true,
+ partition_id: PARTITION_ID,
}
.to_bytes();
let primary = timeout(PRECONDITION_BUDGET, async {
loop {
match member
- .send_binary_request(GET_POLL_ROUTING_CODE, poll.clone())
+ .send_binary_request(GET_PARTITION_ROUTE_CODE, route_request.clone())
.await
{
Ok(response) => {
- let route = PollRoutingResponse::decode_from(&response).unwrap();
- let node = (0..harness.cluster_size())
- .find(|&node| {
- harness.node(node).tcp_addr().unwrap().port() == route.primary.tcp_port
- })
- .unwrap();
+ let route = PartitionRouteResponse::decode_from(&response).unwrap();
+ let node = usize::from(route.primary_replica);
+ assert!(node < harness.cluster_size());
if node != previous_primary {
break node;
}
@@ -1351,20 +1366,35 @@ async fn assert_data_session_fences(
auto_commit: true,
}
.to_bytes();
+ let route_request = GetPartitionRouteRequest {
+ stream_id: identifier_to_wire(stream).unwrap(),
+ topic_id: identifier_to_wire(topic).unwrap(),
+ partition_id: PARTITION_ID,
+ }
+ .to_bytes();
let response = member
- .send_binary_request(GET_POLL_ROUTING_CODE, poll.clone())
+ .send_binary_request(GET_PARTITION_ROUTE_CODE, route_request)
.await
.unwrap();
- let route = PollRoutingResponse::decode_from(&response).unwrap();
+ let route = PartitionRouteResponse::decode_from(&response).unwrap();
let address = harness.node(partition_primary).tcp_addr().unwrap();
- let data = connect_without_login(address).await;
+ let mut data = raw_tcp::connect_to(address).await;
let mut binding = {
let client = member.client();
let client = client.read().await;
- let bind_secret = match &*client {
- ClientWrapper::Tcp(client) => client.session_bind_secret().await,
- ClientWrapper::Quic(client) => client.session_bind_secret().await,
- ClientWrapper::WebSocket(client) => client.session_bind_secret().await,
+ let (identity, bind_secret) = match &*client {
+ ClientWrapper::Tcp(client) => (
+ client.session_identity().await.unwrap(),
+ client.session_bind_secret().await,
+ ),
+ ClientWrapper::Quic(client) => (
+ client.session_identity().await.unwrap(),
+ client.session_bind_secret().await,
+ ),
+ ClientWrapper::WebSocket(client) => (
+ client.session_identity().await.unwrap(),
+ client.session_bind_secret().await,
+ ),
ClientWrapper::Http(_) | ClientWrapper::Iggy(_) => {
panic!("fixture requires a binary transport");
}
@@ -1375,10 +1405,16 @@ async fn assert_data_session_fences(
sdk_name: WireName::new("routing-test").unwrap(),
sdk_version: WireName::new("1.0.0").unwrap(),
},
- identity: route.consumer_session,
+ identity,
bind_secret: bind_secret.unwrap(),
}
};
+ let mut request = RequestHeader {
+ client: binding.identity.client_id,
+ session: binding.identity.session,
+ request: RAW_REQUEST_START,
+ ..Default::default()
+ };
member
.create_user(OTHER_USER, OTHER_PASSWORD, UserStatus::Active, None)
.await
@@ -1420,31 +1456,51 @@ async fn assert_data_session_fences(
wrong_epoch.identity.session += 1;
assert!(
matches!(
- data.send_raw_with_response(BIND_SESSION_CODE, wrong_epoch.to_bytes())
- .await,
+ data_request(
+ &mut data,
+ &mut request,
+ BIND_SESSION_CODE,
+ &wrong_epoch.to_bytes(),
+ None
+ )
+ .await,
Err(IggyError::InvalidSession(_))
),
"attachment must require the exact parent epoch"
);
- data.send_raw_with_response(BIND_SESSION_CODE, binding.to_bytes())
- .await
- .unwrap();
- // Raw Bind authenticates the server connection, but the SDK encoder still
- // needs its epoch before it can issue the explicit offset request below.
- data.bind_vsr_session(binding.identity.session)
- .await
- .unwrap();
- data.send_raw_with_context(POLL_MESSAGES_ON_PRIMARY_CODE, poll.clone(), route.context)
- .await
- .unwrap();
+ data_request(
+ &mut data,
+ &mut request,
+ BIND_SESSION_CODE,
+ &binding.to_bytes(),
+ None,
+ )
+ .await
+ .unwrap();
+ let first_poll = data_request(
+ &mut data,
+ &mut request,
+ POLL_MESSAGES_CODE,
+ &poll,
+ Some(route.context()),
+ )
+ .await
+ .unwrap();
+ let context = PolledMessages::from_bytes(first_poll).unwrap().context;
+ assert_ne!(context.owner_generation, 0);
// A caller without the owner generation sends 0, and the primary binds it
// to the owner it installed for this session.
- let mut unbound = route.context;
+ let mut unbound = context;
unbound.owner_generation = 0;
- let response = data
- .send_raw_with_context(POLL_MESSAGES_ON_PRIMARY_CODE, poll.clone(), unbound)
- .await
- .expect("owner 0 must bind to the owner installed for this session");
+ let response = data_request(
+ &mut data,
+ &mut request,
+ POLL_MESSAGES_CODE,
+ &poll,
+ Some(unbound),
+ )
+ .await
+ .expect("owner 0 must bind to the owner installed for this session");
assert_eq!(
PolledMessages::from_bytes(response).unwrap().partition_id,
PARTITION_ID
@@ -1462,10 +1518,15 @@ async fn assert_data_session_fences(
.to_bytes();
timeout(PRECONDITION_BUDGET, async {
loop {
- let response = data
- .send_raw_with_response(GET_CONSUMER_GROUP_CODE, membership_query.clone())
- .await
- .unwrap();
+ let response = data_request(
+ &mut data,
+ &mut request,
+ GET_CONSUMER_GROUP_CODE,
+ &membership_query,
+ None,
+ )
+ .await
+ .unwrap();
let membership = ConsumerGroupDetailsResponse::decode_from(&response).unwrap();
if membership.group.members_count == 0 {
break;
@@ -1475,20 +1536,30 @@ async fn assert_data_session_fences(
})
.await
.expect("the data node must observe the member leaving");
- let response = data
- .send_raw_with_context(POLL_MESSAGES_ON_PRIMARY_CODE, poll.clone(), route.context)
- .await
- .unwrap();
+ let response = data_request(
+ &mut data,
+ &mut request,
+ POLL_MESSAGES_CODE,
+ &poll,
+ Some(context),
+ )
+ .await
+ .unwrap();
let polled = PolledMessages::from_bytes(response).unwrap();
assert_eq!(
polled.partition_id, RESYNC_REQUIRED_PARTITION_SENTINEL,
"the attached session must respect the member leaving"
);
assert!(polled.messages.is_empty());
- let response = data
- .send_raw_with_context(POLL_MESSAGES_ON_PRIMARY_CODE, poll.clone(), unbound)
- .await
- .unwrap();
+ let response = data_request(
+ &mut data,
+ &mut request,
+ POLL_MESSAGES_CODE,
+ &poll,
+ Some(unbound),
+ )
+ .await
+ .unwrap();
assert_eq!(
PolledMessages::from_bytes(response).unwrap().partition_id,
RESYNC_REQUIRED_PARTITION_SENTINEL,
@@ -1505,10 +1576,12 @@ async fn assert_data_session_fences(
.to_bytes();
assert!(
matches!(
- data.send_raw_with_context(
+ data_request(
+ &mut data,
+ &mut request,
STORE_CONSUMER_OFFSET_CODE,
- offset_write.clone(),
- route.context
+ &offset_write,
+ Some(context)
)
.await,
Err(IggyError::ConsumerGroupPartitionNotOwned(..))
@@ -1529,36 +1602,57 @@ async fn assert_data_session_fences(
PRECONDITION_BUDGET,
)
.await;
- // The rejoining session can still appear as the draining old owner.
- let replacement_route = timeout(PRECONDITION_BUDGET, async {
+ let replacement_context = timeout(PRECONDITION_BUDGET, async {
loop {
match member
- .send_binary_request(GET_POLL_ROUTING_CODE, poll.clone())
+ .poll_messages(
+ stream,
+ topic,
+ Some(PARTITION_ID),
+ consumer,
+ &PollingStrategy::first(),
+ 1,
+ false,
+ )
.await
{
- Ok(response) => break PollRoutingResponse::decode_from(&response).unwrap(),
- Err(
+ Ok(polled) if polled.context.owner_generation > context.owner_generation => {
+ break polled.context;
+ }
+ Ok(_)
+ | Err(
IggyError::ConsumerGroupPartitionNotOwned(..) | IggyError::TransientNotAccepted,
) => {}
- Err(error) => panic!("route discovery failed after rejoining: {error:?}"),
+ Err(error) => panic!("poll failed after rejoining: {error:?}"),
}
sleep(PRECONDITION_POLL).await;
}
})
.await
.expect("rejoining must install a pollable owner within the routing budget");
- assert!(replacement_route.context.owner_generation > route.context.owner_generation);
- let route = replacement_route;
- binding.identity = route.consumer_session;
- data.send_raw_with_response(BIND_SESSION_CODE, binding.to_bytes())
- .await
- .unwrap();
+ let context = replacement_context;
+ binding.identity.metadata_watermark =
+ binding.identity.metadata_watermark.max(context.metadata_op);
+ data_request(
+ &mut data,
+ &mut request,
+ BIND_SESSION_CODE,
+ &binding.to_bytes(),
+ None,
+ )
+ .await
+ .unwrap();
member.logout_user().await.unwrap();
timeout(PRECONDITION_BUDGET, async {
loop {
- let result = data
- .send_raw_with_context(POLL_MESSAGES_ON_PRIMARY_CODE, poll.clone(), route.context)
- .await;
+ let result = data_request(
+ &mut data,
+ &mut request,
+ POLL_MESSAGES_CODE,
+ &poll,
+ Some(context),
+ )
+ .await;
if matches!(result, Err(IggyError::Unauthenticated)) {
break;
}
@@ -1571,13 +1665,7 @@ async fn assert_data_session_fences(
})
.await
.expect("parent logout must fence the independent data session");
- assert_eq!(
- ClientWrapper::Tcp(data)
- .get_connection_info()
- .await
- .server_address,
- address.to_string()
- );
+ assert_eq!(data.peer_addr().unwrap(), address);
}
fn advance_backup_metadata_view(harness: &mut TestHarness, backup: usize) {
@@ -1628,3 +1716,38 @@ async fn send_once(
)),
}
}
+
+// Session-fence probes must reach the selected socket without client routing or retries.
+async fn data_request(
+ data: &mut TcpStream,
+ request: &mut RequestHeader,
+ code: u32,
+ body: &[u8],
+ context: Option<PartitionContext>,
+) -> Result<Bytes, IggyError> {
+ *request = RequestHeader::for_request(
+ code,
+ request.client,
+ request.request.checked_add(1).unwrap(),
+ request.session,
+ body,
+ )
+ .unwrap();
+ if let Some(context) = context {
+ context.stamp(request);
+ }
+ let (reply, body) = raw_tcp::exchange(data, request, body).await;
+ let status = raw_tcp::reply_status(&reply);
+ if status != 0 {
+ return Err(IggyError::from_code(status));
+ }
+ let body = Bytes::from(body);
+ if request.operation.is_result_framed() {
+ match result_code(&body).expect("complete result section") {
+ 0 => Ok(body.slice(result_section_len(&body).unwrap()..)),
+ code => Err(IggyError::from_code(code)),
+ }
+ } else {
+ Ok(body)
+ }
+}
diff --git a/core/integration/tests/data_integrity/verify_after_server_restart.rs b/core/integration/tests/data_integrity/verify_after_server_restart.rs
index a9dece200..9ed57b6b6 100644
--- a/core/integration/tests/data_integrity/verify_after_server_restart.rs
+++ b/core/integration/tests/data_integrity/verify_after_server_restart.rs
@@ -91,6 +91,9 @@ async fn should_fill_data_and_verify_after_restart() {
let expected_clients_count = stats.clients_count;
let expected_consumer_groups_count = stats.consumer_groups_count;
+ // Keep this handle from reconnecting alongside the replacement after restart.
+ client.disconnect().await.unwrap();
+
// Restart server
harness.restart_server().await.unwrap();
let server_addr = harness.server().raw_tcp_addr().unwrap();
@@ -170,10 +173,7 @@ async fn should_fill_data_and_verify_after_restart() {
"pinned-consumer",
IggyByteSize::from(amount_of_data_to_process.as_bytes_u64() * 2),
);
- drop(client_after_restart);
-
- // Connect and login to server
- let client = harness.tcp_root_client().await.unwrap();
+ let client = client_after_restart;
// Save stats from the second server (should have double the data)
let stats = client.get_stats().await.unwrap();
diff --git a/core/integration/tests/data_integrity/verify_consumer_group_partition_assignment.rs b/core/integration/tests/data_integrity/verify_consumer_group_partition_assignment.rs
index cb660f026..fd42ee27b 100644
--- a/core/integration/tests/data_integrity/verify_consumer_group_partition_assignment.rs
+++ b/core/integration/tests/data_integrity/verify_consumer_group_partition_assignment.rs
@@ -71,6 +71,10 @@ async fn create_stale_tcp_client(server_addr: &str) -> IggyClient {
let config = TcpClientConfig {
server_address: server_addr.to_string(),
heartbeat_interval: NonZeroIggyDuration::from_str("1h").unwrap(),
+ reconnection: TcpClientReconnectionConfig {
+ enabled: false,
+ ..TcpClientReconnectionConfig::default()
+ },
nodelay: true,
..TcpClientConfig::default()
};
diff --git a/core/integration/tests/server/scenarios/authentication_scenario.rs b/core/integration/tests/server/scenarios/authentication_scenario.rs
index 78ad83895..609a6cc7d 100644
--- a/core/integration/tests/server/scenarios/authentication_scenario.rs
+++ b/core/integration/tests/server/scenarios/authentication_scenario.rs
@@ -32,15 +32,12 @@ use iggy::prelude::*;
use iggy_binary_protocol::WireEncode;
use iggy_binary_protocol::codes::*;
use iggy_binary_protocol::dispatch::COMMAND_TABLE;
-use iggy_binary_protocol::requests::consumer_offsets::GetConsumerOffsetRequest;
-use iggy_binary_protocol::requests::messages::{GetPartitionRouteRequest, PollMessagesRequest};
+use iggy_binary_protocol::requests::messages::GetPartitionRouteRequest;
use iggy_binary_protocol::requests::system::{BindSessionRequest, SessionIdentity};
use iggy_binary_protocol::requests::users::login_register::BindSecret;
use iggy_binary_protocol::{ClientVersionInfo, IGGY_PROTOCOL_VERSION, WireName};
use iggy_common::VsrSessionControl;
-use iggy_common::wire_conversions::{
- consumer_to_wire, identifier_to_wire, polling_strategy_to_wire,
-};
+use iggy_common::wire_conversions::identifier_to_wire;
use integration::harness::{TestHarness, login_root};
const STREAM_NAME: &str = "auth-test-stream";
@@ -318,37 +315,7 @@ async fn test_all_commands_require_auth(client: &IggyClient, binding_identity: S
)
.await
.map(|_| ()),
- GET_POLL_ROUTING_CODE | POLL_MESSAGES_ON_PRIMARY_CODE => client
- .send_binary_request(
- code,
- PollMessagesRequest {
- consumer: consumer_to_wire(&ctx.consumer).unwrap(),
- stream_id: identifier_to_wire(&ctx.stream_id).unwrap(),
- topic_id: identifier_to_wire(&ctx.topic_id).unwrap(),
- partition_id: Some(0),
- strategy: polling_strategy_to_wire(&PollingStrategy::offset(0)),
- count: 1,
- auto_commit: true,
- }
- .to_bytes(),
- )
- .await
- .map(|_| ()),
-
// Consumer Offsets
- GET_CONSUMER_OFFSET_ROUTING_CODE => client
- .send_binary_request(
- code,
- GetConsumerOffsetRequest {
- consumer: consumer_to_wire(&ctx.consumer).unwrap(),
- stream_id: identifier_to_wire(&ctx.stream_id).unwrap(),
- topic_id: identifier_to_wire(&ctx.topic_id).unwrap(),
- partition_id: Some(0),
- }
- .to_bytes(),
- )
- .await
- .map(|_| ()),
GET_CONSUMER_OFFSET_CODE => client
.get_consumer_offset(&ctx.consumer, &ctx.stream_id, &ctx.topic_id, Some(0))
.await
diff --git a/core/integration/tests/server/scenarios/reconnect_after_restart_scenario.rs b/core/integration/tests/server/scenarios/reconnect_after_restart_scenario.rs
index cab5aed34..32033f9e6 100644
--- a/core/integration/tests/server/scenarios/reconnect_after_restart_scenario.rs
+++ b/core/integration/tests/server/scenarios/reconnect_after_restart_scenario.rs
@@ -56,7 +56,6 @@ pub async fn run_producer(harness: &mut TestHarness) {
.expect("Failed to create producer builder")
.create_stream_if_not_exists()
.create_topic_if_not_exists(1, IggyExpiry::NeverExpire, MaxTopicSize::ServerDefault)
- .send_retries(Some(10), Some(NonZeroIggyDuration::from_str("2s").unwrap()))
.build();
producer
diff --git a/core/integration/tests/server/scenarios/stale_client_consumer_group_scenario.rs b/core/integration/tests/server/scenarios/stale_client_consumer_group_scenario.rs
index e649ed757..6787665c5 100644
--- a/core/integration/tests/server/scenarios/stale_client_consumer_group_scenario.rs
+++ b/core/integration/tests/server/scenarios/stale_client_consumer_group_scenario.rs
@@ -125,7 +125,8 @@ async fn given_cluster_restart_when_member_is_replaced_should_resume_consumption
async fn given_live_member_when_backup_restarts_should_preserve_membership(
harness: &mut integration::harness::TestHarness,
) {
- let consumer_client = create_client(&harness.server().raw_tcp_addr().unwrap(), "1h").await;
+ let consumer_client =
+ create_client(&harness.server().raw_tcp_addr().unwrap(), "1h", true).await;
setup_resources(&consumer_client, Durability::Persisted).await;
let stream = Identifier::named(STREAM_NAME).unwrap();
let topic = Identifier::named(TOPIC_NAME).unwrap();
@@ -169,7 +170,7 @@ async fn verify_replacement_after_restart(
restart: Restart,
) {
let server_addr = harness.server().raw_tcp_addr().unwrap();
- let original = create_client(&server_addr, "500ms").await;
+ let original = create_client(&server_addr, "500ms", true).await;
setup_resources(&original, Durability::Persisted).await;
let stream = Identifier::named(STREAM_NAME).unwrap();
let topic = Identifier::named(TOPIC_NAME).unwrap();
@@ -232,7 +233,7 @@ async fn verify_replacement_after_restart(
harness.restart_node(0).unwrap();
}
- let replacement = create_client(&server_addr, "500ms").await;
+ let replacement = create_client(&server_addr, "500ms", true).await;
replacement
.login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
.await
@@ -313,10 +314,14 @@ async fn verify_replacement_after_restart(
}
}
-async fn create_client(server_addr: &str, heartbeat_interval: &str) -> IggyClient {
+async fn create_client(server_addr: &str, heartbeat_interval: &str, reconnect: bool) -> IggyClient {
let config = TcpClientConfig {
server_address: server_addr.to_string(),
heartbeat_interval: NonZeroIggyDuration::from_str(heartbeat_interval).unwrap(),
+ reconnection: TcpClientReconnectionConfig {
+ enabled: reconnect,
+ ..TcpClientReconnectionConfig::default()
+ },
nodelay: true,
..TcpClientConfig::default()
};
@@ -405,11 +410,11 @@ async fn should_handle_stale_client_with_manual_reconnection(
) {
let server_addr = harness.server().raw_tcp_addr().unwrap();
- let setup_client = create_client(&server_addr, "500ms").await;
+ let setup_client = create_client(&server_addr, "500ms", true).await;
setup_resources(&setup_client, Durability::Persisted).await;
- // Client with 1h heartbeat will become stale
- let stale_client = create_client(&server_addr, "1h").await;
+ // Rebinding after eviction would renew the logical session instead of letting it expire.
+ let stale_client = create_client(&server_addr, "1h", false).await;
stale_client
.login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
.await
@@ -485,7 +490,7 @@ async fn should_handle_stale_client_with_manual_reconnection(
// Reconnect with new client
drop(stale_client);
- let new_client = create_client(&server_addr, "500ms").await;
+ let new_client = create_client(&server_addr, "500ms", true).await;
new_client
.login_user(DEFAULT_ROOT_USERNAME, DEFAULT_ROOT_PASSWORD)
.await
@@ -526,8 +531,9 @@ async fn should_handle_stale_client_with_manual_reconnection(
.await;
}
-/// Tests that IggyConsumer automatically recovers after stale disconnect.
-#[iggy_harness(server(
+/// Tests that IggyConsumer automatically recovers after stale disconnect. On one
+/// node every eviction takes the client's only link down.
+#[iggy_harness(cluster_nodes = [1, 3], server(
heartbeat.enabled = true,
heartbeat.interval = "7s",
consumer_group.heartbeat_interval = "500ms",
@@ -537,7 +543,7 @@ async fn should_handle_stale_client_with_auto_reconnection(
) {
let server_addr = harness.server().raw_tcp_addr().unwrap();
- let setup_client = create_client(&server_addr, "500ms").await;
+ let setup_client = create_client(&server_addr, "500ms", true).await;
setup_resources(&setup_client, Durability::Persisted).await;
let consumer_client = create_reconnecting_client(&server_addr).await;
@@ -571,18 +577,29 @@ async fn should_handle_stale_client_with_auto_reconnection(
if let Some(Ok(_)) = poll_result {
messages_consumed += 1;
if messages_consumed == 5 {
- // Stay silent until the verifier evicts the connection and
- // the server ends the session, so the consumer must
- // reconnect, log in again and rejoin its group.
- integration::harness::wait_for_consumer_group_assignment(
- &setup_client,
- &Identifier::named(STREAM_NAME).unwrap(),
- &Identifier::named(TOPIC_NAME).unwrap(),
- &Identifier::named(CONSUMER_GROUP_NAME).unwrap(),
- 0,
- STALE_EVICTION_TIMEOUT,
- )
- .await;
+ // Stay silent past the bound in which a silent client loses
+ // its membership. The heartbeat verifier evicts the
+ // consumer's links, but each link reconnects and binds the
+ // same session again, which renews its lease. The setup
+ // client runs no heartbeat, so these reads also keep its own
+ // session alive.
+ let deadline = tokio::time::Instant::now() + STALE_EVICTION_TIMEOUT;
+ while tokio::time::Instant::now() < deadline {
+ let group = setup_client
+ .get_consumer_group(
+ &Identifier::named(STREAM_NAME).unwrap(),
+ &Identifier::named(TOPIC_NAME).unwrap(),
+ &Identifier::named(CONSUMER_GROUP_NAME).unwrap(),
+ )
+ .await
+ .unwrap()
+ .expect("consumer group exists");
+ assert_eq!(
+ group.members_count, 1,
+ "the rebound session must keep its membership: {group:?}"
+ );
+ sleep(STALE_EVICTION_RETRY_INTERVAL).await;
+ }
}
}
}
diff --git a/core/integration/tests/server/unknown_code_vsr.rs b/core/integration/tests/server/unknown_code_vsr.rs
index 993f298f3..e0b405199 100644
--- a/core/integration/tests/server/unknown_code_vsr.rs
+++ b/core/integration/tests/server/unknown_code_vsr.rs
@@ -56,6 +56,7 @@ use crate::server::raw_tcp::{
/// A code no `COMMAND_TABLE` entry claims.
const UNKNOWN_CODE: u32 = 9999;
+const RETIRED_ROUTING_CODES: [u32; 3] = [103, 104, 123];
/// An operation byte `Operation` does not declare.
/// `reserved_codes_remain_unknown` pins 131 as never reused, so a new
@@ -78,14 +79,16 @@ const NEXT_REQUEST: u64 = 2;
const CLIENT_ID: u128 = 0xBAD_C0DE;
#[iggy_harness]
-async fn given_bound_session_when_unknown_non_replicated_code_sent_should_deny_invalid_command(
+async fn given_bound_session_when_unknown_or_retired_code_sent_should_deny_invalid_command(
harness: &TestHarness,
) {
- assert!(
- lookup_command(UNKNOWN_CODE).is_none(),
- "test needs a code absent from COMMAND_TABLE"
- );
- assert_non_replicated_code_denied_invalid_command(harness, UNKNOWN_CODE).await;
+ for code in [UNKNOWN_CODE].into_iter().chain(RETIRED_ROUTING_CODES) {
+ assert!(
+ lookup_command(code).is_none(),
+ "code {code} must stay retired"
+ );
+ assert_non_replicated_code_denied_invalid_command(harness, code).await;
+ }
}
#[iggy_harness]
@@ -191,4 +194,11 @@ async fn assert_non_replicated_code_denied_invalid_command(harness: &TestHarness
"a deny Reply carries an empty body, got {} bytes",
reply_body.len()
);
+ let next = non_replicated_header(CLIENT_ID, session, NEXT_REQUEST, GET_ME_CODE);
+ let (next_reply, _) = exchange(&mut stream, &next, &[]).await;
+ assert_eq!(
+ reply_status(&next_reply),
+ 0,
+ "code {code} must not close the session"
+ );
}
diff --git a/core/metadata/src/impls/metadata.rs b/core/metadata/src/impls/metadata.rs
index fb6f1b037..fec554a77 100644
--- a/core/metadata/src/impls/metadata.rs
+++ b/core/metadata/src/impls/metadata.rs
@@ -25,7 +25,7 @@ use crate::stm::snapshot::{
FillSnapshot, MetadataSnapshot, PersistStage, RestoreSnapshotInPlace, Snapshot, SnapshotError,
};
use crate::stm::stream::{Streams, TruncatePartitionRequest};
-use crate::stm::user::{DeletePersonalAccessTokenRequest, Users};
+use crate::stm::user::{CreatePersonalAccessTokenRequest, DeletePersonalAccessTokenRequest, Users};
use crate::stm::{ConsensusGroupAllocator, StateMachine};
use compio::io::AsyncWriteAtExt;
use consensus::{
@@ -1063,6 +1063,9 @@ pub struct IggyMetadata<C, J, S, M, SB = PingPongSuperblock> {
/// `[metadata] partitions_max`, zero for no cap. See
/// [`Self::admit_partitions`].
partitions_max: Cell<u32>,
+ /// `[personal_access_token] max_tokens_per_user`, zero for no cap. See
+ /// [`Self::admit_personal_access_token`].
+ max_tokens_per_user: Cell<u32>,
/// Highest metadata op whose apply has been PUBLISHED on this node, plus
/// the reads parked on it. Shared by every shard; see
/// [`AppliedFrontier`] for the ordering and the wake contract.
@@ -1131,6 +1134,7 @@ where
transfer_offer_cache: RefCell::new(None),
prepare_gap_drops: Cell::new(0),
partitions_max: Cell::new(0),
+ max_tokens_per_user: Cell::new(0),
applied_frontier: Arc::default(),
}
}
@@ -1322,6 +1326,22 @@ impl<C, J, S, M, SB> IggyMetadata<C, J, S, M, SB> {
self.partitions_max.set(partitions_max);
}
+ /// Cap the personal access tokens of each user at `[personal_access_token]
+ /// max_tokens_per_user`, zero for no cap. Only the primary checks it, with
+ /// the value of its own node, when it admits a `CreatePersonalAccessToken`,
+ /// so every node needs the same value.
+ pub fn set_max_tokens_per_user(&self, max_tokens_per_user: u32) {
+ self.max_tokens_per_user.set(max_tokens_per_user);
+ }
+
+ /// The cap that [`Self::set_max_tokens_per_user`] set. Its rejection
+ /// carries only the error code, so an edge that names the cap reads it
+ /// here.
+ #[must_use]
+ pub const fn max_tokens_per_user(&self) -> u32 {
+ self.max_tokens_per_user.get()
+ }
+
/// Fire post-commit notifier. Clones the `Rc` out under a short
/// borrow so a re-entrant `set_commit_notifier` from inside the
/// closure cannot panic on `borrow_mut`.
@@ -2533,12 +2553,9 @@ where
match outcome {
PreflightOutcome::Dispatch => None,
PreflightOutcome::Replay(reply) => {
- if let Some(refusal) = unreplayable_secret_refusal(
- request_header,
- &reply,
- consensus.commit_max(),
- client_id,
- ) {
+ if let Some(refusal) =
+ unreplayable_secret_refusal(request_header, &reply, client_id)
+ {
return Some(Ok(refusal));
}
let owned =
@@ -2643,6 +2660,43 @@ where
admitted
}
+ /// `[personal_access_token] max_tokens_per_user` admission for a
+ /// `CreatePersonalAccessToken`. Other operations pass, so a user at the
+ /// cap can still delete a token to free a slot.
+ ///
+ /// A soft cap for the same reason as [`Self::admit_partitions`]: it counts
+ /// the tokens this primary has committed, so creates in flight can
+ /// overshoot it. It runs before the apply, so a create at the cap reports
+ /// the cap even when its name is taken, as the legacy server did.
+ ///
+ /// The PAT rewrite of every transport encodes the body, so the decode
+ /// cannot fail for a client request.
+ fn admit_personal_access_token(
+ &self,
+ message: &Message<RoutedRequestHeader>,
+ ) -> Result<(), IggyError> {
+ let max_tokens_per_user = self.max_tokens_per_user.get();
+ if max_tokens_per_user == 0
+ || message.header().operation != Operation::CreatePersonalAccessToken
+ {
+ return Ok(());
+ }
+ let Ok(request) = CreatePersonalAccessTokenRequest::decode_from(message.body()) else {
+ return Ok(());
+ };
+ let committed = self
+ .mux_stm
+ .users()
+ .read(|users| users.pat_count_of(request.user_id));
+ if committed >= max_tokens_per_user as usize {
+ return Err(IggyError::PersonalAccessTokensLimitReached(
+ request.user_id,
+ max_tokens_per_user,
+ ));
+ }
+ Ok(())
+ }
+
/// Submit `Logout` from in-process, await commit.
///
/// # Returns
@@ -3187,9 +3241,12 @@ where
}
// After the dedup above: a same-id replay of a create that already
- // committed got its cached reply there, so its partitions are never
- // counted twice.
- if let Err(error) = self.admit_partitions(&message) {
+ // committed got its cached reply there, so its partitions or its token
+ // are never counted twice.
+ if let Err(error) = self
+ .admit_partitions(&message)
+ .and_then(|()| self.admit_personal_access_token(&message))
+ {
return Ok(build_result_rejection_reply(
&request_header,
consensus.commit_max(),
@@ -3513,6 +3570,10 @@ where
build_reply_message_with(&prepare_header, pending.reply_body_len(), |dst| {
pending.write_reply_body(dst);
})
+ .transmute_header::<ReplyHeader>(|old, header| {
+ *header = old;
+ header.reserved[0] = 0;
+ })
} else {
reply
};
@@ -4547,6 +4608,7 @@ pub fn build_truncate_partition_client_message(
client: client_id,
session,
request: template.request,
+ request_checksum: template.request_checksum,
group: server_common::sharding::METADATA_GROUP,
..RoutedRequestHeader::default()
};
@@ -4727,26 +4789,28 @@ fn log_commit_reply_outcome(outcome: CommitReply, client_id: u128, op: u64) {
///
/// `PersonalAccessTokenAlreadyExists` is the honest code: the original create
/// committed, so the name IS taken, and the remedy it implies (delete by name,
-/// then recreate) is exactly right.
+/// then recreate) is exactly right. The refusal is the cached reply with only
+/// its result section replaced. It keeps the commit marker, the original op
+/// and the request identity, so a client that holds the create as uncertain
+/// gets a committed outcome for it.
///
/// A cached REJECTION replays untouched: it carries no secret, so serving it
/// is both safe and useful.
fn unreplayable_secret_refusal(
request_header: &RoutedRequestHeader,
cached: &Frozen<{ server_common::MESSAGE_ALIGN }>,
- commit: u64,
client_id: u128,
) -> Option<Message<GenericHeader>> {
if request_header.operation != Operation::CreatePersonalAccessToken {
return None;
}
- let cached_body = cached
+ let (cached_header, cached_body) = cached
.as_slice()
- .get(size_of::<ReplyHeader>()..)
- .unwrap_or_default();
+ .split_at_checked(size_of::<ReplyHeader>())?;
if iggy_binary_protocol::result_code(cached_body) != Some(0) {
return None;
}
+ let committed = bytemuck::checked::try_from_bytes::<ReplyHeader>(cached_header).ok()?;
warn!(
target: "iggy.metadata.diag",
client_id,
@@ -4754,14 +4818,19 @@ fn unreplayable_secret_refusal(
"refusing replayed CreatePersonalAccessToken: the committed secret is \
unrecoverable and a re-minted one would not match the stored hash"
);
- Some(
- build_result_rejection_reply(
- request_header,
- commit,
- IggyError::PersonalAccessTokenAlreadyExists(String::new(), 0).as_code(),
- )
- .into_generic(),
- )
+ let mut refusal = build_result_rejection_reply(
+ request_header,
+ committed.commit,
+ IggyError::PersonalAccessTokenAlreadyExists(String::new(), 0).as_code(),
+ );
+ let header = ReplyHeader {
+ size: refusal.header().size,
+ checksum: 0,
+ checksum_body: 0,
+ ..*committed
+ };
+ refusal.as_mut_slice()[..size_of::<ReplyHeader>()].copy_from_slice(bytemuck::bytes_of(&header));
+ Some(refusal.into_generic())
}
/// `requested` more partitions on top of the `committed` count against a
@@ -4793,7 +4862,7 @@ mod tests {
use crate::stm::consumer_group::JoinConsumerGroupRequest;
use crate::stm::lifecycle::{CompleteLifecycleRequest, LifecycleCompletion};
use crate::stm::stream::{Streams, StreamsInner};
- use crate::stm::user::{Users, UsersInner};
+ use crate::stm::user::{PAT_TOKEN_HASH_BYTES, Users, UsersInner};
use consensus::LocalPipeline;
use iggy_binary_protocol::WireOptions;
use iggy_binary_protocol::primitives::permissions::{
@@ -4801,7 +4870,7 @@ mod tests {
};
use iggy_binary_protocol::requests::consumer_groups::CreateConsumerGroupRequest;
use iggy_binary_protocol::requests::streams::CreateStreamRequest;
- use iggy_binary_protocol::requests::topics::CreateTopicRequest;
+ use iggy_binary_protocol::requests::topics::{CreateTopicRequest, DeleteTopicRequest};
use iggy_binary_protocol::requests::users::{CreateUserRequest, DeleteUserRequest};
use iggy_common::{IggyTimestamp, UserStatus, variadic};
use journal::prepare_journal::PrepareJournal;
@@ -5419,6 +5488,97 @@ mod tests {
IggyMetadata::new(Some(consensus), None, None, None, TestMux::default(), None)
}
+ #[compio::test]
+ async fn given_committed_lifecycle_intent_when_waiting_for_completion_should_not_prove_final_result()
+ {
+ const CLIENT: u128 = 1;
+ const SESSION: u64 = 1;
+ const ROOT_USER: u32 = 0;
+ let directory = tempfile::tempdir().unwrap();
+ let mut metadata = metadata_plane();
+ metadata.journal = Some(
+ PrepareJournal::open(&directory.path().join("journal.wal"), 0)
+ .await
+ .unwrap(),
+ );
+ metadata.mux_stm = Rc::new(TestMux::new((
+ users_with_topic_manager(),
+ (stream_with_one_partition().into(), ()),
+ )));
+ metadata
+ .client_table
+ .borrow_mut()
+ .commit_register(
+ CLIENT,
+ ROOT_USER,
+ [0x5a; 32],
+ register_reply(CLIENT, SESSION),
+ )
+ .unwrap();
+ let consensus = metadata.consensus.as_ref().unwrap();
+ let request_header = RoutedRequestHeader {
+ client: CLIENT,
+ session: SESSION,
+ request: 1,
+ user_id: ROOT_USER,
+ group: server_common::sharding::METADATA_GROUP,
+ ..Default::default()
+ };
+ let body = DeleteTopicRequest {
+ stream_id: WireIdentifier::numeric(0),
+ topic_id: WireIdentifier::numeric(0),
+ }
+ .to_bytes();
+ let prepare = consensus::seal_prepare_capacity(
+ build_prepare_message(consensus, &request_header, Operation::DeleteTopic, &body),
+ consensus.retry_capacity(&metadata.client_table.borrow()),
+ );
+ let intent_op = prepare.header().op;
+ let pending = metadata
+ .dispatch_prepare_and_await(consensus, prepare)
+ .await
+ .unwrap();
+ assert!(metadata.mux_stm.streams().lifecycle_pending(intent_op));
+ assert_eq!(
+ iggy_binary_protocol::result_code(pending.body()),
+ Some(IggyError::TransientNotCommitted.as_code())
+ );
+ assert!(
+ !pending.header().has_committed_result(),
+ "a committed intent cannot prove its final outcome before every partition finishes"
+ );
+
+ metadata
+ .submit_complete_lifecycle_in_process(
+ CompleteLifecycleRequest::new(
+ intent_op,
+ 0,
+ vec![LifecycleCompletion {
+ topic_id: 0,
+ partition_id: 0,
+ partition_op: 1,
+ }],
+ )
+ .unwrap(),
+ 0,
+ )
+ .await
+ .unwrap();
+ assert!(!metadata.mux_stm.streams().lifecycle_pending(intent_op));
+ let final_reply = metadata
+ .client_table
+ .borrow()
+ .get_reply(CLIENT)
+ .unwrap()
+ .clone()
+ .into_message();
+ assert!(final_reply.header().has_committed_result());
+ assert_eq!(
+ iggy_binary_protocol::result_code(final_reply.body()),
+ Some(0)
+ );
+ }
+
fn create_topic_request(client: u128, wire_user_id: u32) -> Message<RoutedRequestHeader> {
create_named_topic_request(client, wire_user_id, WireIdentifier::numeric(0), "t")
}
@@ -5718,12 +5878,15 @@ mod tests {
/// the dedup cache: the committed secret is unrecoverable (never
/// replicated) and the rewrite has already minted a fresh one whose hash
/// never reached consensus, so replaying would hand back a credential that
- /// authenticates against nothing. A cached REJECTION still replays -- it
- /// carries no secret.
+ /// authenticates against nothing. The refusal keeps the committed header,
+ /// so the client can still prove that the original create committed. A
+ /// cached REJECTION still replays -- it carries no secret.
#[compio::test]
async fn replayed_pat_create_is_refused_but_other_replays_pass_through() {
const CLIENT: u128 = 1;
const USER: u32 = 7;
+ const PAT_OP: u64 = 2;
+ const PAT_REQUEST_CHECKSUM: u128 = 0x2a;
let dir = tempfile::tempdir().unwrap();
let journal =
@@ -5755,23 +5918,56 @@ mod tests {
// Cache a committed SUCCESS for request 1 under the PAT operation,
// exactly as the commit path would (empty apply body + result section).
- let pat_success = committed_reply(CLIENT, 1, Operation::CreatePersonalAccessToken, 0);
+ let pat_success = build_reply_message(
+ &PrepareHeader {
+ client: CLIENT,
+ request: 1,
+ request_checksum: PAT_REQUEST_CHECKSUM,
+ operation: Operation::CreatePersonalAccessToken,
+ op: PAT_OP,
+ user_id: USER,
+ ..PrepareHeader::default()
+ },
+ &bytes::Bytes::copy_from_slice(&0u32.to_le_bytes()),
+ );
+ let committed = *pat_success.header();
md.client_table
.borrow_mut()
.commit_reply(CLIENT, USER, pat_success);
// Replaying request 1 as a PAT create must NOT return the cached
// success; it must refuse with the name-taken code.
- let reply = md
- .submit_request_in_process(pat_create_request(CLIENT, 1))
+ let refusal = md
+ .submit_request_in_process(pat_request(
+ CLIENT,
+ 1,
+ Operation::CreatePersonalAccessToken,
+ &[],
+ ))
.await
- .expect("refusal is a reply, not a submit error");
- let body = &reply.as_slice()[size_of::<ReplyHeader>()..];
+ .expect("refusal is a reply, not a submit error")
+ .try_into_typed::<ReplyHeader>()
+ .unwrap();
assert_eq!(
- iggy_binary_protocol::result_code(body),
+ iggy_binary_protocol::result_code(refusal.body()),
Some(IggyError::PersonalAccessTokenAlreadyExists(String::new(), 0).as_code()),
"a replayed PAT create must be refused, never answered from cache"
);
+ let header = refusal.header();
+ assert!(
+ header.has_committed_result(),
+ "the refusal must prove that the original create committed"
+ );
+ assert_eq!((header.op, header.commit), (PAT_OP, PAT_OP));
+ let expected = ReplyHeader {
+ size: header.size,
+ ..committed
+ };
+ assert_eq!(
+ bytemuck::bytes_of(header),
+ bytemuck::bytes_of(&expected),
+ "the refusal must keep the committed client, request, request checksum and operation"
+ );
// A cached REJECTION for the same operation carries no secret, so it
// replays untouched.
@@ -5786,7 +5982,12 @@ mod tests {
.borrow_mut()
.commit_reply(CLIENT, USER, pat_rejection);
let reply = md
- .submit_request_in_process(pat_create_request(CLIENT, 2))
+ .submit_request_in_process(pat_request(
+ CLIENT,
+ 2,
+ Operation::CreatePersonalAccessToken,
+ &[],
+ ))
.await
.expect("cached rejection replays");
let body = &reply.as_slice()[size_of::<ReplyHeader>()..];
@@ -5998,6 +6199,112 @@ mod tests {
);
}
+ /// The cap is graded before the apply grades the name, so a create at the
+ /// cap reports the cap even when its name is taken, as the legacy server
+ /// did.
+ #[test]
+ fn given_at_limit_duplicate_name_when_admitting_should_report_limit_not_duplicate() {
+ let metadata = metadata_capped_over(users_holding_token());
+
+ let error = metadata
+ .admit_personal_access_token(&pat_request(
+ 1,
+ 1,
+ Operation::CreatePersonalAccessToken,
+ &token_create(TOKEN_NAME).to_bytes(),
+ ))
+ .expect_err("a create at the cap must be denied even for a taken name");
+
+ assert!(
+ matches!(
+ error,
+ IggyError::PersonalAccessTokensLimitReached(TOKEN_OWNER, TOKEN_CAP)
+ ),
+ "expected the cap error before the name grading, got {error:?}"
+ );
+ }
+
+ /// A delete is how a user at the cap frees a slot, so capping it too
+ /// would lock the account at the cap.
+ #[test]
+ fn given_user_at_token_cap_when_deleting_should_admit() {
+ let metadata = metadata_capped_over(users_holding_token());
+
+ assert!(
+ metadata
+ .admit_personal_access_token(&pat_request(
+ 1,
+ 1,
+ Operation::DeletePersonalAccessToken,
+ &token_delete().to_bytes(),
+ ))
+ .is_ok()
+ );
+ }
+
+ #[test]
+ fn given_deletion_freed_a_slot_when_admitting_should_admit_the_next_create() {
+ let mut users = users_holding_token();
+ let deleted = StateHandler::apply(&token_delete(), &mut users, IggyTimestamp::now());
+ assert_eq!(deleted.code, 0, "the fixture token must be deleted");
+ let metadata = metadata_capped_over(users);
+
+ let admitted = metadata.admit_personal_access_token(&pat_request(
+ 1,
+ 1,
+ Operation::CreatePersonalAccessToken,
+ &token_create("replacement").to_bytes(),
+ ));
+
+ assert!(
+ admitted.is_ok(),
+ "a freed slot must admit the next create, got {admitted:?}"
+ );
+ }
+
+ const TOKEN_OWNER: u32 = 7;
+ const TOKEN_NAME: &str = "token";
+ const TOKEN_CAP: u32 = 1;
+
+ fn token_create(name: &str) -> CreatePersonalAccessTokenRequest {
+ CreatePersonalAccessTokenRequest {
+ user_id: TOKEN_OWNER,
+ name: WireName::new(name).unwrap(),
+ expiry: 0,
+ token_hash: [b'a'; PAT_TOKEN_HASH_BYTES],
+ }
+ }
+
+ fn token_delete() -> DeletePersonalAccessTokenRequest {
+ DeletePersonalAccessTokenRequest {
+ user_id: TOKEN_OWNER,
+ name: WireName::new(TOKEN_NAME).unwrap(),
+ only_if_expired: false,
+ }
+ }
+
+ /// `TOKEN_OWNER` holding `TOKEN_NAME`, which fills `TOKEN_CAP`.
+ fn users_holding_token() -> UsersInner {
+ let mut users = UsersInner::new();
+ let created =
+ StateHandler::apply(&token_create(TOKEN_NAME), &mut users, IggyTimestamp::now());
+ assert_eq!(created.code, 0, "the fixture token must be created");
+ users
+ }
+
+ /// A plane over `users` that caps each user at `TOKEN_CAP` tokens.
+ fn metadata_capped_over(
+ users: UsersInner,
+ ) -> IggyMetadata<VsrConsensus<NoopBus>, PrepareJournal, (), TestMux> {
+ let mut metadata = metadata_plane();
+ metadata.mux_stm = Rc::new(TestMux::new((
+ users.into(),
+ (StreamsInner::new().into(), ()),
+ )));
+ metadata.set_max_tokens_per_user(TOKEN_CAP);
+ metadata
+ }
+
/// Slab ids of `users_with_topic_manager`: root takes 0.
const TOPIC_MANAGER: u32 = 1;
const UNGRANTED: u32 = 2;
@@ -6143,22 +6450,31 @@ mod tests {
reply
}
- fn pat_create_request(client: u128, request: u64) -> Message<RoutedRequestHeader> {
+ fn pat_request(
+ client: u128,
+ request: u64,
+ operation: Operation,
+ body: &[u8],
+ ) -> Message<RoutedRequestHeader> {
let header_size = size_of::<RoutedRequestHeader>();
- let mut message = Message::<RoutedRequestHeader>::new(header_size);
- let header = bytemuck::checked::from_bytes_mut::<RoutedRequestHeader>(
- &mut message.as_mut_slice()[..header_size],
- );
- *header = RoutedRequestHeader {
- command: Command::Request,
- operation: Operation::CreatePersonalAccessToken,
- size: u32::try_from(header_size).unwrap(),
- client,
- session: 1,
- request,
- group: server_common::sharding::METADATA_GROUP,
- ..Default::default()
- };
+ let total = header_size + body.len();
+ let mut message = Message::<RoutedRequestHeader>::new(total);
+ {
+ let slice = message.as_mut_slice();
+ slice[header_size..total].copy_from_slice(body);
+ let header =
+ bytemuck::checked::from_bytes_mut::<RoutedRequestHeader>(&mut slice[..header_size]);
+ *header = RoutedRequestHeader {
+ command: Command::Request,
+ operation,
+ size: u32::try_from(total).unwrap(),
+ client,
+ session: 1,
+ request,
+ group: server_common::sharding::METADATA_GROUP,
+ ..Default::default()
+ };
+ }
message
}
diff --git a/core/metadata/src/stm/user.rs b/core/metadata/src/stm/user.rs
index f0388fdee..fbf10fd15 100644
--- a/core/metadata/src/stm/user.rs
+++ b/core/metadata/src/stm/user.rs
@@ -247,7 +247,7 @@ impl UsersInner {
/// Count of live personal access tokens for one user.
///
- /// Single-map read for the ingress-side create cap; the sibling
+ /// Single-map read for the primary's create cap; the sibling
/// `personal_access_tokens_of` allocates and sorts, too heavy for a
/// per-request check.
#[must_use]
diff --git a/core/partitions/src/iggy_partition.rs b/core/partitions/src/iggy_partition.rs
index 24cb51351..421595b38 100644
--- a/core/partitions/src/iggy_partition.rs
+++ b/core/partitions/src/iggy_partition.rs
@@ -16578,12 +16578,13 @@ mod tests {
.restore_retry_checkpoint(recovered.checkpoint_op())
.await
.unwrap();
- assert!(matches!(
- reopened
- .dedup
- .check_request(1, 1, 1, Operation::SendMessages),
- consensus::client_table::RequestStatus::Duplicate(_)
- ));
+ let consensus::client_table::RequestStatus::Duplicate(reply) = reopened
+ .dedup
+ .check_request(1, 1, 1, Operation::SendMessages)
+ else {
+ panic!("checkpoint must retain the committed result for a retry");
+ };
+ assert!(reply.header().has_committed_result());
}
}
diff --git a/core/sdk/README.md b/core/sdk/README.md
index ef4dd1e02..fcd4d05e6 100644
--- a/core/sdk/README.md
+++ b/core/sdk/README.md
@@ -36,7 +36,7 @@ Official Rust client SDK for [Apache Iggy](https://iggy.apache.org), the persist
- **Consumer**: standalone or consumer-group over binary transports; HTTP supports standalone consumers only. Consumed as an async `Stream`. Polling strategies: `next`, `offset`, `timestamp`, `first`, `last`.
- **Auto-commit** offset policies: `Interval`, `When`, `After`, `IntervalOrWhen`, `IntervalOrAfter`, or disabled.
- **Stream builder** (`IggyStream`, `IggyStreamProducer`, `IggyStreamConsumer`) for declarative producer + consumer setup on shared or separate stream/topic.
-- **Reliability**: automatic reconnection with retries, heartbeat, send retries, and offset auto-commit handled by the high-level API.
+- **Reliability**: managed replica connections, heartbeat, ordered mutation lanes, explicit recovery of uncertain mutations, and offset auto-commit.
- **Message features**: optional headers (`HeaderKey` / `HeaderValue`), client-side AES-256-GCM encryption (via `Aes256GcmEncryptor`), topic compression metadata (`None` and `Gzip`; no runtime compression yet), server-honored message expiry, and server-side deduplication.
- **Admin**: stream/topic/partition CRUD, consumer-group management, server-side consumer offsets, system stats.
@@ -45,16 +45,13 @@ Official Rust client SDK for [Apache Iggy](https://iggy.apache.org), the persist
Run from your application crate. Use a release compatible with your server; for
unreleased changes, build the SDK and server from the same source checkout.
-Cluster auto-commit polling requires servers that support consumer session
-attachment and primary poll routing (binary commands 15, 103 and 104).
-Rust manual and interval offset writes also require command 123. It discovers
-the primary while allowing final commits for partitions awaiting handoff;
-stores and deletes retain their existing wire formats and deduplication keys. Pause
-binary auto-commit consumers during this upgrade, upgrade every server first,
-then upgrade the SDKs and restart the consumers so they join their groups again.
-Older SDKs can lose group membership when a backup refuses an offset commit;
-the new SDK does not fall back to that path on an older server.
-HTTP clients use server-side forwarding and need no new routing commands.
+This checkout requires matching servers and SDKs with fresh storage. Older data
+directories are refused without modification; `--fresh` deletes existing data
+in the configured directory. See the [server recovery guide](../server/README.md#upgrade-recovery).
+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). Commands 14, 103, 104 and 123
+are retired. HTTP clients use server-side forwarding.
```bash
cargo add iggy
@@ -68,11 +65,61 @@ them, retain their logical identity and bind proof across transport reconnects,
and clear them on explicit logout. `VsrSessionSealed` is an implementation marker,
not a restriction on external implementations. The bind proof is a bearer
credential for internal session control and must never be logged or exposed.
+`refresh_session_password` and `refresh_session_username` are removed. A
+transport that signs in again applies a committed credential change where its
+calls complete.
An established session has its own lifetime. Password or PAT changes and PAT
expiry do not end it. Logout, session lease expiry, or user deactivation end the
session and prevent its bind proof from restoring it.
+## Mutation recovery
+
+TCP, QUIC and WebSocket serialize mutations within each partition history and
+within the metadata lane. Different lanes can progress concurrently. An
+`IggyError::OperationUncertain(operation_id)` retains the exact request for
+recovery. A later mutation on the same lane returns
+`IggyError::LaneBlocked(operation_id)` until that operation is resolved or abandoned.
+
+Call `client.resolve_operation(operation_id, deadline).await`, where `deadline`
+is a `std::time::Instant`. A proved success returns `Ok(())`; a proved committed
+business rejection returns its original error. Both release the lane. Another
+`OperationUncertain` keeps the request available for a later recovery attempt.
+The client keeps the proved outcomes of its last `max_pending_operations`
+replays, also across a session reset. So a later resolve returns the same
+outcome without a request, also after a producer or a consumer of the client
+resolved the operation first.
+`client.abandon_operation(operation_id).await` releases the lane while leaving
+the outcome unknown. A session reset drops retained requests. An
+`OperationNotRetained` error does not establish the outcome. A reset or an
+abandon came before a proved outcome, or the proved outcome aged out.
+Recovery is unavailable over HTTP.
+
+A committed password change or rename of the signed-in user updates the
+credentials that the client signs in with again. This holds for a typed call, a
+raw request and a change that `resolve_operation` proves. A committed rejection,
+such as a wrong current password, leaves them unchanged.
+
+The client defaults to 256 active or retained mutations and 64 MiB of frozen
+request frames. Configure positive limits through `PendingOperationsConfig`
+on the binary transport builder, or through connection-string options:
+
+```text
+iggy://iggy:iggy@localhost:8090?max_pending_operations=256&max_pending_operation_bytes=67108864
+```
+
+Admission waits within the call deadline before allocating a request ID or
+sending. A frame larger than the byte limit fails locally. Completion,
+abandonment and session reset release operation capacity; bytes remain charged
+while a writer still holds the frame. Replaying a retained request reuses its
+reservation.
+
+Auto-commit and `Next` polls share their partition's mutation barrier while the
+call is active. They retain their weak acknowledgement: cancellation or failover
+can leave progress unknown. Error 57 or a lost reply after send ends the call
+immediately without replay; errors 58/89 still retry known non-admission.
+These polls are not retained for recovery.
+
## Quick start
Start a source server from the repository root in a separate terminal:
diff --git a/core/sdk/src/binary/mod.rs b/core/sdk/src/binary/mod.rs
index d892b1910..34a7514ec 100644
--- a/core/sdk/src/binary/mod.rs
+++ b/core/sdk/src/binary/mod.rs
@@ -16,3 +16,193 @@
// under the License.
pub use iggy_common::{BinaryClient, BinaryTransport};
+
+macro_rules! impl_binary_client {
+ ($client:ty) => {
+ impl $client {
+ pub(crate) fn retains_operation(&self, op: u64) -> bool {
+ self.driver.session().retains_operation(op)
+ }
+
+ pub(crate) async fn keepalive(&self) -> Result<bool, iggy_common::IggyError> {
+ self.driver.links().keepalive().await
+ }
+
+ pub(crate) fn connection_address(&self) -> String {
+ self.driver.links().connection_address()
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl iggy_common::Client for $client {
+ async fn connect(&self) -> Result<(), iggy_common::IggyError> {
+ self.driver.links().connect().await
+ }
+
+ async fn disconnect(&self) -> Result<(), iggy_common::IggyError> {
+ self.driver.links().disconnect();
+ self.driver.session().forget();
+ self.driver.session().reset().map(|_| ())
+ }
+
+ async fn shutdown(&self) -> Result<(), iggy_common::IggyError> {
+ self.driver.links().shutdown().await;
+ self.driver.session().forget();
+ self.driver.session().reset().map(|_| ())
+ }
+
+ async fn subscribe_events(
+ &self,
+ ) -> async_broadcast::Receiver<iggy_common::DiagnosticEvent> {
+ self.driver.links().subscribe()
+ }
+
+ async fn resolve_operation(
+ &self,
+ op: u64,
+ deadline: std::time::Instant,
+ ) -> Result<(), iggy_common::IggyError> {
+ self.driver.resolve(op, deadline.into()).await
+ }
+
+ async fn abandon_operation(&self, op: u64) -> Result<(), iggy_common::IggyError> {
+ self.driver.abandon(op)
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl iggy_common::BinaryTransport for $client {
+ async fn get_state(&self) -> iggy_common::ClientState {
+ self.driver.links().state()
+ }
+
+ async fn set_state(&self, state: iggy_common::ClientState) {
+ self.driver.links().set_state(state);
+ }
+
+ async fn publish_event(&self, event: iggy_common::DiagnosticEvent) {
+ self.driver.links().publish(event);
+ }
+
+ async fn send_raw_with_context(
+ &self,
+ code: u32,
+ payload: bytes::Bytes,
+ context: iggy_common::PartitionContext,
+ ) -> Result<bytes::Bytes, iggy_common::IggyError> {
+ self.driver
+ .send_raw(
+ code,
+ payload,
+ (context != iggy_common::PartitionContext::default()).then_some(context),
+ )
+ .await
+ }
+
+ async fn send_offset_write_with_response(
+ &self,
+ code: u32,
+ payload: bytes::Bytes,
+ context: Option<iggy_common::PartitionContext>,
+ ) -> Result<bytes::Bytes, iggy_common::IggyError> {
+ self.driver.send_raw(code, payload, context).await
+ }
+
+ async fn send_poll_with_response(
+ &self,
+ request: &iggy_binary_protocol::requests::messages::PollMessagesRequest,
+ context: Option<iggy_common::PartitionContext>,
+ ) -> Result<bytes::Bytes, iggy_common::IggyError> {
+ self.driver.poll(request, context).await
+ }
+
+ fn routed_partition_count(
+ &self,
+ stream_id: &iggy_common::Identifier,
+ topic_id: &iggy_common::Identifier,
+ ) -> Option<u32> {
+ self.driver.partition_count(stream_id, topic_id)
+ }
+
+ fn get_heartbeat_interval(&self) -> iggy_common::NonZeroIggyDuration {
+ self.config.heartbeat_interval
+ }
+
+ fn consumer_group_state(
+ &self,
+ ) -> std::sync::Arc<iggy_common::ConsumerGroupClientState> {
+ self.driver.session().consumer_group_state()
+ }
+ }
+
+ impl iggy_common::VsrSessionSealed for $client {}
+
+ #[async_trait::async_trait]
+ impl iggy_common::VsrSessionControl for $client {
+ async fn prepare_sign_in(&self) -> Result<(), iggy_common::IggyError> {
+ self.driver.links().prepare_sign_in().await
+ }
+
+ async fn session_identity(
+ &self,
+ ) -> Result<
+ iggy_binary_protocol::requests::system::SessionIdentity,
+ iggy_common::IggyError,
+ > {
+ self.driver.session().identity()
+ }
+
+ async fn session_bind_secret(
+ &self,
+ ) -> Result<
+ iggy_binary_protocol::requests::users::login_register::BindSecret,
+ iggy_common::IggyError,
+ > {
+ self.driver.session().bind_secret()
+ }
+
+ async fn bind_vsr_session(&self, session: u64) -> Result<(), iggy_common::IggyError> {
+ self.driver
+ .session()
+ .bind_at(self.driver.session().fence(), session)
+ .map(|_| ())
+ }
+
+ fn session_fence(&self) -> u64 {
+ self.driver.session().fence()
+ }
+
+ async fn bind_vsr_session_at(
+ &self,
+ fence: u64,
+ session: u64,
+ ) -> Result<(), iggy_common::IggyError> {
+ self.driver.session().bind_at(fence, session).map(|_| ())
+ }
+
+ async fn reset_vsr_session(&self) -> Result<(), iggy_common::IggyError> {
+ self.driver.session().reset().map(|_| ())
+ }
+
+ async fn remember_session_credentials(
+ &self,
+ credentials: iggy_common::Credentials,
+ user_id: u32,
+ ) {
+ self.driver.remember(credentials, user_id).await;
+ }
+
+ async fn forget_session_credentials(&self) {
+ self.driver.session().forget();
+ }
+
+ fn sdk_version(&self) -> &'static str {
+ crate::SDK_VERSION
+ }
+ }
+
+ impl iggy_common::BinaryClient for $client {}
+ };
+}
+
+pub(crate) use impl_binary_client;
diff --git a/core/sdk/src/client_provider.rs b/core/sdk/src/client_provider.rs
index 6b431562a..b19e55916 100644
--- a/core/sdk/src/client_provider.rs
+++ b/core/sdk/src/client_provider.rs
@@ -89,6 +89,7 @@ impl ClientProviderConfig {
match config.transport {
TransportProtocol::Quic => {
config.quic = Some(Arc::new(QuicClientConfig {
+ pending_operations: Default::default(),
client_address: args.quic_client_address,
server_address: args.quic_server_address,
server_name: args.quic_server_name,
@@ -134,6 +135,7 @@ impl ClientProviderConfig {
}
TransportProtocol::Tcp => {
config.tcp = Some(Arc::new(TcpClientConfig {
+ pending_operations: Default::default(),
server_address: args.tcp_server_address,
tls_enabled: args.tcp_tls_enabled,
tls_domain: args.tcp_tls_domain,
@@ -164,6 +166,7 @@ impl ClientProviderConfig {
}
TransportProtocol::WebSocket => {
config.websocket = Some(Arc::new(WebSocketClientConfig {
+ pending_operations: Default::default(),
server_address: args.websocket_server_address,
heartbeat_interval: NonZeroIggyDuration::from_str(
&args.websocket_heartbeat_interval,
diff --git a/core/sdk/src/client_wrappers/binary_client.rs b/core/sdk/src/client_wrappers/binary_client.rs
index a8b4d34cd..5e91d6a9e 100644
--- a/core/sdk/src/client_wrappers/binary_client.rs
+++ b/core/sdk/src/client_wrappers/binary_client.rs
@@ -26,8 +26,6 @@ use std::time::Instant;
impl Client for ClientWrapper {
async fn connect(&self) -> Result<(), IggyError> {
match self {
- // The trait `connect` is the caller's: it clears a held disconnect,
- // where each transport's own `connect` keeps it.
ClientWrapper::Iggy(client) => Client::connect(client).await,
ClientWrapper::Http(client) => Client::connect(client).await,
ClientWrapper::Tcp(client) => Client::connect(client).await,
@@ -86,18 +84,3 @@ impl Client for ClientWrapper {
}
}
}
-
-impl ClientWrapper {
- /// Connects again through the transport's own `connect`, which leaves a
- /// caller's `disconnect()` in force: a reconnect the client starts on its
- /// own, such as after a leader redirect, is refused while it holds.
- pub(crate) async fn reconnect_keeping_intent(&self) -> Result<(), IggyError> {
- match self {
- ClientWrapper::Tcp(client) => client.connect().await,
- ClientWrapper::Quic(client) => client.connect().await,
- ClientWrapper::WebSocket(client) => client.connect().await,
- ClientWrapper::Iggy(client) => Client::connect(client).await,
- ClientWrapper::Http(client) => Client::connect(client).await,
- }
- }
-}
diff --git a/core/sdk/src/client_wrappers/client_wrapper.rs b/core/sdk/src/client_wrappers/client_wrapper.rs
index 4b347ab0c..12b918806 100644
--- a/core/sdk/src/client_wrappers/client_wrapper.rs
+++ b/core/sdk/src/client_wrappers/client_wrapper.rs
@@ -20,6 +20,11 @@ use crate::http::http_client::HttpClient;
use crate::quic::quic_client::QuicClient;
use crate::tcp::tcp_client::TcpClient;
use crate::websocket::websocket_client::WebSocketClient;
+use iggy_common::locking::IggyRwLockFn;
+use iggy_common::{
+ BinarySendPartitioning, Identifier, IggyError, IggyMessage, MessageClient,
+ SendMessagesResponse, SystemClient, send_binary_messages,
+};
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
@@ -30,3 +35,59 @@ pub enum ClientWrapper {
Quic(QuicClient),
WebSocket(WebSocketClient),
}
+
+impl ClientWrapper {
+ pub(crate) async fn send_messages_with_partitioning(
+ &self,
+ stream: &Identifier,
+ topic: &Identifier,
+ partitioning: &mut BinarySendPartitioning<'_>,
+ messages: &mut [IggyMessage],
+ ) -> Result<SendMessagesResponse, IggyError> {
+ match self {
+ Self::Iggy(client) => {
+ Box::pin(client.send_messages_with_partitioning(
+ stream,
+ topic,
+ partitioning,
+ messages,
+ ))
+ .await
+ }
+ Self::Http(client) => {
+ client
+ .send_messages(stream, topic, partitioning.original(), messages)
+ .await
+ }
+ Self::Tcp(client) => {
+ send_binary_messages(client, stream, topic, partitioning, messages).await
+ }
+ Self::Quic(client) => {
+ send_binary_messages(client, stream, topic, partitioning, messages).await
+ }
+ Self::WebSocket(client) => {
+ send_binary_messages(client, stream, topic, partitioning, messages).await
+ }
+ }
+ }
+
+ pub(crate) async fn keepalive(&self) -> Result<bool, IggyError> {
+ match self {
+ Self::Iggy(client) => Box::pin(client.client.read().await.keepalive()).await,
+ Self::Http(client) => client.ping().await.map(|()| true),
+ Self::Tcp(client) => client.keepalive().await,
+ Self::Quic(client) => client.keepalive().await,
+ Self::WebSocket(client) => client.keepalive().await,
+ }
+ }
+
+ pub(crate) async fn retains_operation(&self, op: u64) -> bool {
+ match self {
+ Self::Iggy(client) => Box::pin(client.client.read().await.retains_operation(op)).await,
+ Self::Http(_) => false,
+ Self::Tcp(client) => client.retains_operation(op),
+ Self::Quic(client) => client.retains_operation(op),
+ Self::WebSocket(client) => client.retains_operation(op),
+ }
+ }
+}
diff --git a/core/sdk/src/client_wrappers/connection_info.rs b/core/sdk/src/client_wrappers/connection_info.rs
index f2fc8063d..0895718bd 100644
--- a/core/sdk/src/client_wrappers/connection_info.rs
+++ b/core/sdk/src/client_wrappers/connection_info.rs
@@ -41,11 +41,11 @@ impl ClientWrapper {
}
ClientWrapper::Tcp(client) => ConnectionInfo {
protocol: TransportProtocol::Tcp,
- server_address: client.current_server_address.lock().await.clone(),
+ server_address: client.connection_address(),
},
ClientWrapper::Quic(client) => ConnectionInfo {
protocol: TransportProtocol::Quic,
- server_address: client.current_server_address.lock().await.clone(),
+ server_address: client.connection_address(),
},
ClientWrapper::Http(client) => ConnectionInfo {
protocol: TransportProtocol::Http,
@@ -53,7 +53,7 @@ impl ClientWrapper {
},
ClientWrapper::WebSocket(client) => ConnectionInfo {
protocol: TransportProtocol::WebSocket,
- server_address: client.current_server_address.lock().await.clone(),
+ server_address: client.connection_address(),
},
}
}
diff --git a/core/sdk/src/clients/binary_cluster.rs b/core/sdk/src/clients/binary_cluster.rs
index 4794b2d76..dfde70f39 100644
--- a/core/sdk/src/clients/binary_cluster.rs
+++ b/core/sdk/src/clients/binary_cluster.rs
@@ -23,6 +23,6 @@ use iggy_common::{ClusterMetadata, IggyError, locking::IggyRwLockFn};
#[async_trait]
impl ClusterClient for IggyClient {
async fn get_cluster_metadata(&self) -> Result<ClusterMetadata, IggyError> {
- self.client.read().await.get_cluster_metadata().await
+ super::with_client!(self, client => client.get_cluster_metadata().await)
}
}
diff --git a/core/sdk/src/clients/binary_consumer_group.rs b/core/sdk/src/clients/binary_consumer_group.rs
index 863143b8d..ccf836094 100644
--- a/core/sdk/src/clients/binary_consumer_group.rs
+++ b/core/sdk/src/clients/binary_consumer_group.rs
@@ -31,11 +31,7 @@ impl ConsumerGroupClient for IggyClient {
topic_id: &Identifier,
group_id: &Identifier,
) -> Result<Option<ConsumerGroupDetails>, IggyError> {
- self.client
- .read()
- .await
- .get_consumer_group(stream_id, topic_id, group_id)
- .await
+ super::with_client!(self, client => client.get_consumer_group(stream_id, topic_id, group_id).await)
}
async fn get_consumer_groups(
@@ -43,11 +39,7 @@ impl ConsumerGroupClient for IggyClient {
stream_id: &Identifier,
topic_id: &Identifier,
) -> Result<Vec<ConsumerGroup>, IggyError> {
- self.client
- .read()
- .await
- .get_consumer_groups(stream_id, topic_id)
- .await
+ super::with_client!(self, client => client.get_consumer_groups(stream_id, topic_id).await)
}
async fn create_consumer_group(
@@ -56,11 +48,7 @@ impl ConsumerGroupClient for IggyClient {
topic_id: &Identifier,
name: &str,
) -> Result<ConsumerGroupDetails, IggyError> {
- self.client
- .read()
- .await
- .create_consumer_group(stream_id, topic_id, name)
- .await
+ super::with_client!(self, client => client.create_consumer_group(stream_id, topic_id, name).await)
}
async fn delete_consumer_group(
@@ -69,11 +57,7 @@ impl ConsumerGroupClient for IggyClient {
topic_id: &Identifier,
group_id: &Identifier,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .delete_consumer_group(stream_id, topic_id, group_id)
- .await
+ super::with_client!(self, client => client.delete_consumer_group(stream_id, topic_id, group_id).await)
}
async fn join_consumer_group(
@@ -82,11 +66,7 @@ impl ConsumerGroupClient for IggyClient {
topic_id: &Identifier,
group_id: &Identifier,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .join_consumer_group(stream_id, topic_id, group_id)
- .await
+ super::with_client!(self, client => client.join_consumer_group(stream_id, topic_id, group_id).await)
}
async fn leave_consumer_group(
@@ -95,17 +75,13 @@ impl ConsumerGroupClient for IggyClient {
topic_id: &Identifier,
group_id: &Identifier,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .leave_consumer_group(stream_id, topic_id, group_id)
- .await
+ super::with_client!(self, client => client.leave_consumer_group(stream_id, topic_id, group_id).await)
}
}
#[async_trait]
impl AsyncDrop for IggyClient {
async fn async_drop(&mut self) {
- let _ = self.client.read().await.logout_user().await;
+ let _ = super::with_client!(self, client => client.logout_user().await);
}
}
diff --git a/core/sdk/src/clients/binary_consumer_offset.rs b/core/sdk/src/clients/binary_consumer_offset.rs
index 2a96b267d..8fd53963c 100644
--- a/core/sdk/src/clients/binary_consumer_offset.rs
+++ b/core/sdk/src/clients/binary_consumer_offset.rs
@@ -30,11 +30,7 @@ impl ConsumerOffsetClient for IggyClient {
topic_id: &Identifier,
position: ConsumerPosition,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .store_consumer_position(consumer, stream_id, topic_id, position)
- .await
+ super::with_client!(self, client => client.store_consumer_position(consumer, stream_id, topic_id, position).await)
}
async fn store_consumer_offset(
@@ -45,11 +41,7 @@ impl ConsumerOffsetClient for IggyClient {
partition_id: Option<u32>,
offset: u64,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .store_consumer_offset(consumer, stream_id, topic_id, partition_id, offset)
- .await
+ super::with_client!(self, client => client.store_consumer_offset(consumer, stream_id, topic_id, partition_id, offset).await)
}
async fn get_consumer_offset(
@@ -59,11 +51,7 @@ impl ConsumerOffsetClient for IggyClient {
topic_id: &Identifier,
partition_id: Option<u32>,
) -> Result<Option<ConsumerOffsetInfo>, IggyError> {
- self.client
- .read()
- .await
- .get_consumer_offset(consumer, stream_id, topic_id, partition_id)
- .await
+ super::with_client!(self, client => client.get_consumer_offset(consumer, stream_id, topic_id, partition_id).await)
}
async fn delete_consumer_offset(
@@ -73,10 +61,6 @@ impl ConsumerOffsetClient for IggyClient {
topic_id: &Identifier,
partition_id: Option<u32>,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .delete_consumer_offset(consumer, stream_id, topic_id, partition_id)
- .await
+ super::with_client!(self, client => client.delete_consumer_offset(consumer, stream_id, topic_id, partition_id).await)
}
}
diff --git a/core/sdk/src/clients/binary_message.rs b/core/sdk/src/clients/binary_message.rs
index 7e2e1f7b1..a8c62d8d6 100644
--- a/core/sdk/src/clients/binary_message.rs
+++ b/core/sdk/src/clients/binary_message.rs
@@ -18,8 +18,8 @@
use crate::prelude::IggyClient;
use async_trait::async_trait;
use bytes::Bytes;
-use iggy_common::MessageClient;
use iggy_common::locking::IggyRwLockFn;
+use iggy_common::{BinarySendPartitioning, MessageClient};
use iggy_common::{
Consumer, Identifier, IggyError, IggyMessage, Partitioning, PolledMessages, PollingStrategy,
SendMessagesResponse,
@@ -63,11 +63,7 @@ impl MessageClient for IggyClient {
return Err(IggyError::InvalidMessagesCount);
}
- let mut polled_messages = self
- .client
- .read()
- .await
- .poll_messages_with_strategy_for(
+ let mut polled_messages = super::with_client!(self, client => client.poll_messages_with_strategy_for(
stream_id,
topic_id,
partition_id,
@@ -75,8 +71,7 @@ impl MessageClient for IggyClient {
strategy_for,
count,
auto_commit,
- )
- .await?;
+ ).await)?;
if let Some(ref encryptor) = self.encryptor {
for message in &mut polled_messages.messages {
@@ -101,12 +96,32 @@ impl MessageClient for IggyClient {
topic_id: &Identifier,
partitioning: &Partitioning,
messages: &mut [IggyMessage],
+ ) -> Result<SendMessagesResponse, IggyError> {
+ self.send_messages_with_partitioning(
+ stream_id,
+ topic_id,
+ &mut BinarySendPartitioning::new(partitioning),
+ messages,
+ )
+ .await
+ }
+}
+
+impl IggyClient {
+ pub(crate) async fn send_messages_with_partitioning(
+ &self,
+ stream_id: &Identifier,
+ topic_id: &Identifier,
+ partitioning: &mut BinarySendPartitioning<'_>,
+ messages: &mut [IggyMessage],
) -> Result<SendMessagesResponse, IggyError> {
if messages.is_empty() {
return Err(IggyError::InvalidMessagesCount);
}
- if let Some(encryptor) = &self.encryptor {
+ if !partitioning.is_resolved()
+ && let Some(encryptor) = &self.encryptor
+ {
for message in &mut *messages {
message.payload = Bytes::from(encryptor.encrypt(&message.payload)?);
message.header.payload_length = message.payload.len() as u32;
@@ -119,10 +134,6 @@ impl MessageClient for IggyClient {
}
}
- self.client
- .read()
- .await
- .send_messages(stream_id, topic_id, partitioning, messages)
- .await
+ super::with_client!(self, client => client.send_messages_with_partitioning(stream_id, topic_id, partitioning, messages).await)
}
}
diff --git a/core/sdk/src/clients/binary_partitions.rs b/core/sdk/src/clients/binary_partitions.rs
index 6ae06116c..256a2718f 100644
--- a/core/sdk/src/clients/binary_partitions.rs
+++ b/core/sdk/src/clients/binary_partitions.rs
@@ -29,11 +29,7 @@ impl PartitionClient for IggyClient {
topic_id: &Identifier,
partitions_count: u32,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .create_partitions(stream_id, topic_id, partitions_count)
- .await
+ super::with_client!(self, client => client.create_partitions(stream_id, topic_id, partitions_count).await)
}
async fn delete_partitions(
@@ -42,10 +38,6 @@ impl PartitionClient for IggyClient {
topic_id: &Identifier,
partitions_count: u32,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .delete_partitions(stream_id, topic_id, partitions_count)
- .await
+ super::with_client!(self, client => client.delete_partitions(stream_id, topic_id, partitions_count).await)
}
}
diff --git a/core/sdk/src/clients/binary_personal_access_tokens.rs b/core/sdk/src/clients/binary_personal_access_tokens.rs
index c0456b441..1190beb2f 100644
--- a/core/sdk/src/clients/binary_personal_access_tokens.rs
+++ b/core/sdk/src/clients/binary_personal_access_tokens.rs
@@ -15,8 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use crate::clients::redirect_login_settled;
-use crate::prelude::{ClientWrapper, IggyClient};
+use crate::prelude::IggyClient;
use async_trait::async_trait;
use iggy_common::PersonalAccessTokenClient;
use iggy_common::locking::IggyRwLockFn;
@@ -24,12 +23,11 @@ use iggy_common::{
IdentityInfo, IggyError, PersonalAccessTokenExpiry, PersonalAccessTokenInfo,
RawPersonalAccessToken,
};
-use tracing::info;
#[async_trait]
impl PersonalAccessTokenClient for IggyClient {
async fn get_personal_access_tokens(&self) -> Result<Vec<PersonalAccessTokenInfo>, IggyError> {
- self.client.read().await.get_personal_access_tokens().await
+ super::with_client!(self, client => client.get_personal_access_tokens().await)
}
async fn create_personal_access_token(
@@ -37,59 +35,17 @@ impl PersonalAccessTokenClient for IggyClient {
name: &str,
expiry: PersonalAccessTokenExpiry,
) -> Result<RawPersonalAccessToken, IggyError> {
- self.client
- .read()
- .await
- .create_personal_access_token(name, expiry)
- .await
+ super::with_client!(self, client => client.create_personal_access_token(name, expiry).await)
}
async fn delete_personal_access_token(&self, name: &str) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .delete_personal_access_token(name)
- .await
+ super::with_client!(self, client => client.delete_personal_access_token(name).await)
}
async fn login_with_personal_access_token(
&self,
token: &str,
) -> Result<IdentityInfo, IggyError> {
- let identity = self
- .client
- .read()
- .await
- .login_with_personal_access_token(token)
- .await?;
-
- let should_redirect = {
- let client = self.client.read().await;
- match &*client {
- ClientWrapper::Tcp(tcp_client) => tcp_client.handle_leader_redirection().await?,
- ClientWrapper::Quic(quic_client) => quic_client.handle_leader_redirection().await?,
- ClientWrapper::WebSocket(ws_client) => {
- ws_client.handle_leader_redirection().await?
- }
- _ => false,
- }
- };
-
- if should_redirect {
- info!("Redirected to leader, reconnecting and re-authenticating");
- self.reconnect_after_redirect().await?;
- // The reconnect signs in with the credentials this very call just
- // remembered, so on a client without a configured `AutoLogin` the
- // session is already this user's: signing in again would cost a
- // logout and a second login (an argon2 each, on the server) for
- // nothing. With `AutoLogin::Enabled` the reconnect signed in the
- // configured user, who may not be this one, so the login runs.
- if redirect_login_settled(&*self.client.read().await).await {
- return Ok(identity);
- }
- self.login_with_personal_access_token(token).await
- } else {
- Ok(identity)
- }
+ super::with_client!(self, client => client.login_with_personal_access_token(token).await)
}
}
diff --git a/core/sdk/src/clients/binary_segments.rs b/core/sdk/src/clients/binary_segments.rs
index c931a7a4a..1eb475002 100644
--- a/core/sdk/src/clients/binary_segments.rs
+++ b/core/sdk/src/clients/binary_segments.rs
@@ -30,10 +30,6 @@ impl SegmentClient for IggyClient {
partition_id: u32,
segments_count: u32,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .delete_segments(stream_id, topic_id, partition_id, segments_count)
- .await
+ super::with_client!(self, client => client.delete_segments(stream_id, topic_id, partition_id, segments_count).await)
}
}
diff --git a/core/sdk/src/clients/binary_streams.rs b/core/sdk/src/clients/binary_streams.rs
index d6464a9a3..5c555fbcb 100644
--- a/core/sdk/src/clients/binary_streams.rs
+++ b/core/sdk/src/clients/binary_streams.rs
@@ -25,15 +25,15 @@ use iggy_common::{Identifier, IggyError, Stream, StreamDetails};
#[async_trait]
impl StreamClient for IggyClient {
async fn get_stream(&self, stream_id: &Identifier) -> Result<Option<StreamDetails>, IggyError> {
- self.client.read().await.get_stream(stream_id).await
+ super::with_client!(self, client => client.get_stream(stream_id).await)
}
async fn get_streams(&self) -> Result<Vec<Stream>, IggyError> {
- self.client.read().await.get_streams().await
+ super::with_client!(self, client => client.get_streams().await)
}
async fn create_stream(&self, name: &str) -> Result<StreamDetails, IggyError> {
- self.client.read().await.create_stream(name).await
+ super::with_client!(self, client => client.create_stream(name).await)
}
async fn update_stream(
@@ -42,14 +42,10 @@ impl StreamClient for IggyClient {
name: &str,
options: &StreamUpdateOptions,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .update_stream(stream_id, name, options)
- .await
+ super::with_client!(self, client => client.update_stream(stream_id, name, options).await)
}
async fn delete_stream(&self, stream_id: &Identifier) -> Result<(), IggyError> {
- self.client.read().await.delete_stream(stream_id).await
+ super::with_client!(self, client => client.delete_stream(stream_id).await)
}
}
diff --git a/core/sdk/src/clients/binary_system.rs b/core/sdk/src/clients/binary_system.rs
index 7d5d07c1c..ab885a961 100644
--- a/core/sdk/src/clients/binary_system.rs
+++ b/core/sdk/src/clients/binary_system.rs
@@ -27,27 +27,27 @@ use iggy_common::{
#[async_trait]
impl SystemClient for IggyClient {
async fn get_stats(&self) -> Result<Stats, IggyError> {
- self.client.read().await.get_stats().await
+ super::with_client!(self, client => client.get_stats().await)
}
async fn get_me(&self) -> Result<ClientInfoDetails, IggyError> {
- self.client.read().await.get_me().await
+ super::with_client!(self, client => client.get_me().await)
}
async fn get_client(&self, client_id: u32) -> Result<Option<ClientInfoDetails>, IggyError> {
- self.client.read().await.get_client(client_id).await
+ super::with_client!(self, client => client.get_client(client_id).await)
}
async fn get_clients(&self) -> Result<Vec<ClientInfo>, IggyError> {
- self.client.read().await.get_clients().await
+ super::with_client!(self, client => client.get_clients().await)
}
async fn describe_options(&self, scope: OptionsScope) -> Result<Vec<OptionSpec>, IggyError> {
- self.client.read().await.describe_options(scope).await
+ super::with_client!(self, client => client.describe_options(scope).await)
}
async fn ping(&self) -> Result<(), IggyError> {
- self.client.read().await.ping().await
+ super::with_client!(self, client => client.ping().await)
}
async fn heartbeat_interval(&self) -> NonZeroIggyDuration {
@@ -59,10 +59,6 @@ impl SystemClient for IggyClient {
compression: SnapshotCompression,
snapshot_types: Vec<SystemSnapshotType>,
) -> Result<Snapshot, IggyError> {
- self.client
- .read()
- .await
- .snapshot(compression, snapshot_types)
- .await
+ super::with_client!(self, client => client.snapshot(compression, snapshot_types).await)
}
}
diff --git a/core/sdk/src/clients/binary_topics.rs b/core/sdk/src/clients/binary_topics.rs
index 85bf27ac8..f62e66f21 100644
--- a/core/sdk/src/clients/binary_topics.rs
+++ b/core/sdk/src/clients/binary_topics.rs
@@ -30,15 +30,11 @@ impl TopicClient for IggyClient {
stream_id: &Identifier,
topic_id: &Identifier,
) -> Result<Option<TopicDetails>, IggyError> {
- self.client
- .read()
- .await
- .get_topic(stream_id, topic_id)
- .await
+ super::with_client!(self, client => client.get_topic(stream_id, topic_id).await)
}
async fn get_topics(&self, stream_id: &Identifier) -> Result<Vec<Topic>, IggyError> {
- self.client.read().await.get_topics(stream_id).await
+ super::with_client!(self, client => client.get_topics(stream_id).await)
}
async fn create_topic(
@@ -47,11 +43,7 @@ impl TopicClient for IggyClient {
name: &str,
options: &TopicCreateOptions,
) -> Result<TopicDetails, IggyError> {
- self.client
- .read()
- .await
- .create_topic(stream_id, name, options)
- .await
+ super::with_client!(self, client => client.create_topic(stream_id, name, options).await)
}
async fn update_topic(
@@ -61,11 +53,7 @@ impl TopicClient for IggyClient {
name: &str,
options: &TopicUpdateOptions,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .update_topic(stream_id, topic_id, name, options)
- .await
+ super::with_client!(self, client => client.update_topic(stream_id, topic_id, name, options).await)
}
async fn delete_topic(
@@ -73,10 +61,6 @@ impl TopicClient for IggyClient {
stream_id: &Identifier,
topic_id: &Identifier,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .delete_topic(stream_id, topic_id)
- .await
+ super::with_client!(self, client => client.delete_topic(stream_id, topic_id).await)
}
}
diff --git a/core/sdk/src/clients/binary_users.rs b/core/sdk/src/clients/binary_users.rs
index e014d4dd6..8049eee98 100644
--- a/core/sdk/src/clients/binary_users.rs
+++ b/core/sdk/src/clients/binary_users.rs
@@ -15,8 +15,6 @@
// specific language governing permissions and limitations
// under the License.
-use crate::client_wrappers::client_wrapper::ClientWrapper;
-use crate::clients::redirect_login_settled;
use crate::prelude::IggyClient;
use async_trait::async_trait;
use iggy_common::UserClient;
@@ -25,16 +23,15 @@ use iggy_common::locking::IggyRwLockFn;
use iggy_common::{
Identifier, IdentityInfo, IggyError, Permissions, UserInfo, UserInfoDetails, UserStatus,
};
-use tracing::info;
#[async_trait]
impl UserClient for IggyClient {
async fn get_user(&self, user_id: &Identifier) -> Result<Option<UserInfoDetails>, IggyError> {
- self.client.read().await.get_user(user_id).await
+ super::with_client!(self, client => client.get_user(user_id).await)
}
async fn get_users(&self) -> Result<Vec<UserInfo>, IggyError> {
- self.client.read().await.get_users().await
+ super::with_client!(self, client => client.get_users().await)
}
async fn create_user(
@@ -44,15 +41,11 @@ impl UserClient for IggyClient {
status: UserStatus,
permissions: Option<Permissions>,
) -> Result<UserInfoDetails, IggyError> {
- self.client
- .read()
- .await
- .create_user(username, password, status, permissions)
- .await
+ super::with_client!(self, client => client.create_user(username, password, status, permissions).await)
}
async fn delete_user(&self, user_id: &Identifier) -> Result<(), IggyError> {
- self.client.read().await.delete_user(user_id).await
+ super::with_client!(self, client => client.delete_user(user_id).await)
}
async fn update_user(
@@ -62,11 +55,7 @@ impl UserClient for IggyClient {
status: Option<UserStatus>,
options: &UserUpdateOptions,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .update_user(user_id, username, status, options)
- .await
+ super::with_client!(self, client => client.update_user(user_id, username, status, options).await)
}
async fn update_permissions(
@@ -74,11 +63,7 @@ impl UserClient for IggyClient {
user_id: &Identifier,
permissions: Option<Permissions>,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .update_permissions(user_id, permissions)
- .await
+ super::with_client!(self, client => client.update_permissions(user_id, permissions).await)
}
async fn change_password(
@@ -87,52 +72,14 @@ impl UserClient for IggyClient {
current_password: &str,
new_password: &str,
) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .change_password(user_id, current_password, new_password)
- .await
+ super::with_client!(self, client => client.change_password(user_id, current_password, new_password).await)
}
async fn login_user(&self, username: &str, password: &str) -> Result<IdentityInfo, IggyError> {
- let identity = self
- .client
- .read()
- .await
- .login_user(username, password)
- .await?;
-
- let should_redirect = {
- let client = self.client.read().await;
- match &*client {
- ClientWrapper::Tcp(tcp_client) => tcp_client.handle_leader_redirection().await?,
- ClientWrapper::Quic(quic_client) => quic_client.handle_leader_redirection().await?,
- ClientWrapper::WebSocket(ws_client) => {
- ws_client.handle_leader_redirection().await?
- }
- _ => false,
- }
- };
-
- if should_redirect {
- info!("Redirected to leader, reconnecting and re-authenticating");
- self.reconnect_after_redirect().await?;
- // The reconnect signs in with the credentials this very call just
- // remembered, so on a client without a configured `AutoLogin` the
- // session is already this user's: signing in again would cost a
- // logout and a second login (an argon2 each, on the server) for
- // nothing. With `AutoLogin::Enabled` the reconnect signed in the
- // configured user, who may not be this one, so the login runs.
- if redirect_login_settled(&*self.client.read().await).await {
- return Ok(identity);
- }
- self.login_user(username, password).await
- } else {
- Ok(identity)
- }
+ super::with_client!(self, client => client.login_user(username, password).await)
}
async fn logout_user(&self) -> Result<(), IggyError> {
- self.client.read().await.logout_user().await
+ super::with_client!(self, client => client.logout_user().await)
}
}
diff --git a/core/sdk/src/clients/client.rs b/core/sdk/src/clients/client.rs
index 94f7e017a..46698828c 100644
--- a/core/sdk/src/clients/client.rs
+++ b/core/sdk/src/clients/client.rs
@@ -152,8 +152,7 @@ const SESSION_CONTROL_CODES: [u32; 5] = [
/// .build()?;
/// client.connect().await?;
///
-/// // A background producer batches in the background, retries failed sends,
-/// // and creates a topic.
+/// // A background producer batches messages and creates a topic.
/// let producer = client
/// .producer("stream_name", "topic_name")?
/// .topic_durability(iggy::prelude::Durability::Persisted)
@@ -164,7 +163,6 @@ const SESSION_CONTROL_CODES: [u32; 5] = [
/// .build(),
/// )
/// .partitioning(Partitioning::balanced())
-/// .send_retries(Some(3), Some(NonZeroIggyDuration::ONE_SECOND))
/// .create_topic_if_not_exists(
/// 3,
/// IggyExpiry::ServerDefault,
@@ -242,8 +240,8 @@ pub struct IggyClient {
}
/// The heartbeat task, and whether an explicit `disconnect()` stopped it.
-/// Only `connect()` clears the stop, so a reconnect after a leader redirect
-/// that a `disconnect()` raced starts no heartbeat.
+/// Only `connect()` clears the stop. A racing `disconnect()` prevents the
+/// completed connection attempt from starting another heartbeat.
#[derive(Debug, Default)]
struct Heartbeat {
handle: Option<JoinHandle<()>>,
@@ -307,8 +305,10 @@ impl IggyClient {
/// - `tls_domain`: string. Server name to validate the certificate against. Default: unset.
/// - `tls_ca_file`: filesystem path. PEM roots replacing the built-in roots. Default: unset.
/// - `reconnection_retries`: "unlimited" or u32. Retry passes after the initial endpoint pass. Default: `unlimited`.
- /// - `reconnection_interval`: [`NonZeroIggyDuration`]. Wait between retry passes. Default: `1s`.
- /// - `reestablish_after`: [`IggyDuration`]. Cooldown measured from the last connection establishment. Default: `5s`.
+ /// - `reconnection_interval`: [`NonZeroIggyDuration`]. Full-jitter exponential backoff base, capped at 10 seconds. Default: `1s`.
+ /// - `reestablish_after`: [`IggyDuration`]. Stable connection duration that resets the retry count and backoff. Default: `5s`.
+ /// - `max_pending_operations`: positive usize. Active and retained mutations per session. Default: `256`.
+ /// - `max_pending_operation_bytes`: positive usize. Frozen mutation headers and bodies. Default: `67108864` (64 MiB).
/// - `heartbeat_interval`: [`NonZeroIggyDuration`]. Client heartbeat period. Default: `5s`.
/// - `nodelay`: `bool`. Disable Nagle's algorithm (`TCP_NODELAY`). Default: `false`.
///
@@ -331,9 +331,11 @@ impl IggyClient {
///
/// - `validate_certificate`: bool. Verify the server certificate. Default: `false`.
/// - `heartbeat_interval`: [`NonZeroIggyDuration`]. Client heartbeat period. Default: `5s`.
- /// - `reconnection_max_retries`: "unlimited" or u32. Number of attempts to connect. Default: `unlimited`.
- /// - `reconnection_interval`: [`NonZeroIggyDuration`]. Wait between reconnection attempts. Default: `1s`.
- /// - `reconnection_reestablish_after`: [`IggyDuration`]. Cooldown measured from the last connection establishment. Default: `5s`.
+ /// - `reconnection_max_retries`: "unlimited" or u32. Retry passes after the initial endpoint pass. Default: `unlimited`.
+ /// - `reconnection_interval`: [`NonZeroIggyDuration`]. Full-jitter exponential backoff base, capped at 10 seconds. Default: `1s`.
+ /// - `reconnection_reestablish_after`: [`IggyDuration`]. Stable connection duration that resets the retry count and backoff. Default: `5s`.
+ /// - `max_pending_operations`: positive usize. Active and retained mutations per session. Default: `256`.
+ /// - `max_pending_operation_bytes`: positive usize. Frozen mutation headers and bodies. Default: `67108864` (64 MiB).
/// - `response_buffer_size`: u64. Number of bytes in the response receive buffer. Default: `10000000`.
/// - `max_concurrent_bidi_streams`: u64. Number of concurrent bidirectional streams. Default: `10000`.
/// - `datagram_send_buffer_size`: u64. Number of bytes in the datagram send buffer. Default: `100000`.
@@ -386,9 +388,11 @@ impl IggyClient {
/// ## WebSocket
///
/// - `heartbeat_interval`: [`NonZeroIggyDuration`]. Client heartbeat period. Default: `5s`.
- /// - `reconnection_retries`: "unlimited" or u32. Number of attempts to connect. Default: `unlimited`.
- /// - `reconnection_interval`: [`NonZeroIggyDuration`]. Wait between reconnection attempts. Default: `1s`.
- /// - `reestablish_after`: [`IggyDuration`]. Cooldown measured from the last connection establishment. Default: `5s`.
+ /// - `reconnection_retries`: "unlimited" or u32. Retry passes after the initial endpoint pass. Default: `unlimited`.
+ /// - `reconnection_interval`: [`NonZeroIggyDuration`]. Full-jitter exponential backoff base, capped at 10 seconds. Default: `1s`.
+ /// - `reestablish_after`: [`IggyDuration`]. Stable connection duration that resets the retry count and backoff. Default: `5s`.
+ /// - `max_pending_operations`: positive usize. Active and retained mutations per session. Default: `256`.
+ /// - `max_pending_operation_bytes`: positive usize. Frozen mutation headers and bodies. Default: `67108864` (64 MiB).
/// - `read_buffer_size`: usize. Size of the read buffer in bytes. Default: `131072`.
/// - `write_buffer_size`: usize. Size of the write buffer in bytes. Default: `131072`.
/// - `max_write_buffer_size`: usize. Must exceed `write_buffer_size`. Default: `usize::MAX`.
@@ -760,7 +764,7 @@ impl IggyClient {
/// # Examples
///
/// Connect a client, build a producer that creates the topic if it is
- /// missing and retries failed sends, then publish a message.
+ /// missing, then publish a message.
///
/// ```no_run
/// use iggy::prelude::*;
@@ -776,7 +780,6 @@ impl IggyClient {
/// .producer("stream_name", "topic_name")?
/// .topic_durability(iggy::prelude::Durability::Persisted)
/// .partitioning(Partitioning::balanced())
- /// .send_retries(Some(3), Some(NonZeroIggyDuration::ONE_SECOND))
/// .create_topic_if_not_exists(
/// 3,
/// IggyExpiry::ServerDefault,
@@ -906,12 +909,12 @@ impl IggyClient {
if SESSION_CONTROL_CODES.contains(&code) {
return Err(IggyError::InvalidCommand);
}
- match &*self.client.read().await {
+ super::with_client!(self, client => match &*client {
ClientWrapper::Tcp(client) => client.send_raw_with_response(code, payload).await,
ClientWrapper::Quic(client) => client.send_raw_with_response(code, payload).await,
ClientWrapper::WebSocket(client) => client.send_raw_with_response(code, payload).await,
ClientWrapper::Http(_) | ClientWrapper::Iggy(_) => Err(IggyError::FeatureUnavailable),
- }
+ })
}
/// Invokes a HTTP endpoint and returns the raw response body.
@@ -976,15 +979,6 @@ impl Drop for IggyClient {
}
impl IggyClient {
- /// Connects again after a leader redirect without clearing the caller's
- /// `disconnect()`: one that lands during the redirect holds, and the
- /// transport refuses the reconnect.
- pub(crate) async fn reconnect_after_redirect(&self) -> Result<(), IggyError> {
- self.client.read().await.reconnect_keeping_intent().await?;
- self.start_heartbeat().await;
- Ok(())
- }
-
async fn start_heartbeat(&self) {
let heartbeat_interval = self.client.read().await.heartbeat_interval().await;
let mut heartbeat = self.heartbeat();
@@ -1002,21 +996,25 @@ impl IggyClient {
heartbeat.handle = Some(spawn(async move {
loop {
debug!("Sending the heartbeat...");
- if let Err(error) = client.read().await.ping().await {
- error!("There was an error when sending a heartbeat. {error}");
- if error == IggyError::ClientShutdown {
- warn!("The client has been shut down - stopping the heartbeat.");
- return;
+ let keepalive = client.read().await.keepalive().await;
+ match keepalive {
+ Err(error) => {
+ error!("There was an error when sending a heartbeat. {error}");
+ if error == IggyError::ClientShutdown {
+ warn!("The client has been shut down - stopping the heartbeat.");
+ return;
+ }
+ }
+ Ok(true) => {
+ debug!("Heartbeat was sent successfully.");
+ // Picks up a widened assignment without waiting for an ownership-fence rejection.
+ client
+ .read()
+ .await
+ .refresh_consumer_group_assignments()
+ .await;
}
- } else {
- debug!("Heartbeat was sent successfully.");
- // Picks up a widened assignment (e.g. partition-count
- // change) without waiting for an ownership-fence rejection.
- client
- .read()
- .await
- .refresh_consumer_group_assignments()
- .await;
+ Ok(false) => {}
}
sleep(heartbeat_interval.get_duration()).await
}
@@ -1047,6 +1045,8 @@ impl Client for IggyClient {
Ok(())
}
+ /// Stops the binary client's heartbeat. An explicit login can reconnect,
+ /// but only [`connect`](Client::connect) restarts the heartbeat.
async fn disconnect(&self) -> Result<(), IggyError> {
// HTTP keeps no connection, so its disconnect changes nothing and the
// heartbeat keeps running.
@@ -1071,25 +1071,99 @@ impl Client for IggyClient {
}
async fn resolve_operation(&self, op: u64, deadline: Instant) -> Result<(), IggyError> {
- self.client
- .read()
- .await
- .resolve_operation(op, deadline)
+ iggy_common::with_binary_deadline(deadline.into(), async {
+ let client = tokio::time::timeout_at(
+ iggy_common::binary_operation_deadline(),
+ self.client.read(),
+ )
.await
+ .map_err(|_| IggyError::OperationUncertain(op))?;
+ client.resolve_operation(op, deadline).await
+ })
+ .await
}
async fn abandon_operation(&self, op: u64) -> Result<(), IggyError> {
- self.client.read().await.abandon_operation(op).await
+ super::with_client!(self, client => client.abandon_operation(op).await)
}
}
#[cfg(test)]
mod tests {
use super::*;
+ use crate::links::OPERATION_TIMEOUT;
+ use crate::links::fake_cluster::{Answer, FakeCluster, connected, endpoint};
use crate::links::test_support::LOCALHOST;
- use iggy_common::TcpClientConfig;
+ use iggy_binary_protocol::codes::{CREATE_STREAM_CODE, GET_STATS_CODE};
+ use iggy_common::{StreamClient, TcpClientConfig};
+ use std::time::Duration;
use tokio::net::TcpListener;
+ #[tokio::test(start_paused = true)]
+ async fn given_nested_client_locks_when_reading_should_share_one_deadline() {
+ let cluster = FakeCluster::new(1);
+ let inner = IggyClient::new(ClientWrapper::Tcp(TcpClient::from_links(
+ connected(&cluster, 1).await,
+ )));
+ let inner_lock = inner.client.clone();
+ let outer = IggyClient::new(ClientWrapper::Iggy(inner));
+ let outer_lock = outer.client.clone();
+ let inner_guard = inner_lock.write().await;
+ let outer_guard = outer_lock.write().await;
+ let lock_wait = Duration::from_secs(20);
+ let start = tokio::time::Instant::now();
+
+ let ((result, finished), ()) = tokio::join!(
+ async { (outer.get_stats().await, tokio::time::Instant::now()) },
+ async {
+ sleep(lock_wait).await;
+ drop(outer_guard);
+ sleep(lock_wait).await;
+ drop(inner_guard);
+ }
+ );
+
+ assert!(matches!(result, Err(IggyError::TransientNotAccepted)));
+ assert_eq!(finished - start, OPERATION_TIMEOUT);
+ assert_eq!(cluster.count(GET_STATS_CODE), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_wrapper_lock_wait_when_a_mutation_times_out_should_preserve_its_operation() {
+ let cluster = FakeCluster::new(1);
+ let client = IggyClient::new(ClientWrapper::Tcp(TcpClient::from_links(
+ connected(&cluster, 1).await,
+ )));
+ cluster.script(&endpoint(0), CREATE_STREAM_CODE, [Answer::Silence]);
+ let client_lock = client.client.clone();
+ let guard = client_lock.write().await;
+ let start = tokio::time::Instant::now();
+ let (result, ()) = tokio::join!(client.create_stream("stream"), async {
+ sleep(Duration::from_secs(20)).await;
+ drop(guard);
+ });
+
+ let Err(IggyError::OperationUncertain(op)) = result else {
+ panic!("a sent mutation must return its retained operation identity");
+ };
+ assert_eq!(tokio::time::Instant::now() - start, OPERATION_TIMEOUT);
+ assert_eq!(cluster.count(CREATE_STREAM_CODE), 1);
+ assert!(client_lock.read().await.retains_operation(op).await);
+
+ let guard = client_lock.write().await;
+ let resolve_budget = Duration::from_secs(5);
+ let result = client
+ .resolve_operation(
+ op,
+ (tokio::time::Instant::now() + resolve_budget).into_std(),
+ )
+ .await;
+ assert_eq!(result, Err(IggyError::OperationUncertain(op)));
+ drop(guard);
+ assert!(client_lock.read().await.retains_operation(op).await);
+ client.abandon_operation(op).await.unwrap();
+ }
+
#[test]
fn should_fail_with_empty_connection_string() {
let value = "";
diff --git a/core/sdk/src/clients/client_builder.rs b/core/sdk/src/clients/client_builder.rs
index 20a960c6d..fd2e44a66 100644
--- a/core/sdk/src/clients/client_builder.rs
+++ b/core/sdk/src/clients/client_builder.rs
@@ -20,8 +20,8 @@ use crate::clients::client::IggyClient;
use crate::http::http_client::HttpClient;
use crate::prelude::{
AutoLogin, EncryptorKind, HttpClientConfigBuilder, IggyDuration, IggyError,
- NonZeroIggyDuration, Partitioner, QuicClientConfigBuilder, TcpClientConfigBuilder,
- WebSocketClientConfigBuilder,
+ NonZeroIggyDuration, Partitioner, PendingOperationsConfig, QuicClientConfigBuilder,
+ TcpClientConfigBuilder, WebSocketClientConfigBuilder,
};
use crate::quic::quic_client::QuicClient;
use crate::tcp::tcp_client::TcpClient;
@@ -160,6 +160,12 @@ impl TcpClientBuilder {
self
}
+ /// Sets the shared capacity for active and retained mutation frames.
+ pub fn with_pending_operations(mut self, pending_operations: PendingOperationsConfig) -> Self {
+ self.config = self.config.with_pending_operations(pending_operations);
+ self
+ }
+
/// Sets the auto sign in during connection.
pub fn with_auto_sign_in(mut self, auto_sign_in: AutoLogin) -> Self {
self.config = self.config.with_auto_sign_in(auto_sign_in);
@@ -247,6 +253,12 @@ impl QuicClientBuilder {
self
}
+ /// Sets the shared capacity for active and retained mutation frames.
+ pub fn with_pending_operations(mut self, pending_operations: PendingOperationsConfig) -> Self {
+ self.config = self.config.with_pending_operations(pending_operations);
+ self
+ }
+
/// Sets the auto sign in during connection.
pub fn with_auto_sign_in(mut self, auto_sign_in: AutoLogin) -> Self {
self.config = self.config.with_auto_sign_in(auto_sign_in);
@@ -343,6 +355,12 @@ impl WebSocketClientBuilder {
self
}
+ /// Sets the shared capacity for active and retained mutation frames.
+ pub fn with_pending_operations(mut self, pending_operations: PendingOperationsConfig) -> Self {
+ self.config = self.config.with_pending_operations(pending_operations);
+ self
+ }
+
/// Sets the auto sign in during connection.
pub fn with_auto_sign_in(mut self, auto_sign_in: AutoLogin) -> Self {
self.config = self.config.with_auto_sign_in(auto_sign_in);
diff --git a/core/sdk/src/clients/consumer.rs b/core/sdk/src/clients/consumer.rs
index f4e117262..24d80564e 100644
--- a/core/sdk/src/clients/consumer.rs
+++ b/core/sdk/src/clients/consumer.rs
@@ -16,6 +16,8 @@
// under the License.
use crate::client_wrappers::client_wrapper::ClientWrapper;
+use crate::driver::{operation_deadline, with_deadline};
+use crate::links::OPERATION_TIMEOUT;
use bytes::Bytes;
use dashmap::DashMap;
use futures::Stream;
@@ -42,12 +44,19 @@ use std::time::Duration;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tokio::time;
-use tokio::time::sleep;
+use tokio::time::{Instant, sleep, timeout_at};
use tracing::{debug, error, info, trace, warn};
const ORDERING: std::sync::atomic::Ordering = std::sync::atomic::Ordering::SeqCst;
type PollMessagesFuture = Pin<Box<dyn Future<Output = Result<PolledMessages, IggyError>> + Send>>;
+#[derive(Clone, Copy)]
+enum OffsetMutation {
+ Store { partition_id: u32, offset: u64 },
+ StorePosition(ConsumerPosition),
+ Delete { partition_id: Option<u32> },
+}
+
/// The auto-commit configuration for storing the offset on the server.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum AutoCommit {
@@ -195,20 +204,11 @@ impl IggyConsumerState {
offset,
context: PartitionContext::default(),
};
- if !self.allow_replay && self.stored_offset_covers(position) {
- return Ok(());
- }
- self.client
- .read()
- .await
- .store_consumer_offset(
- &self.consumer,
- &self.stream_id,
- &self.topic_id,
- Some(partition_id),
- offset,
- )
- .await?;
+ self.mutate_offset(OffsetMutation::Store {
+ partition_id,
+ offset,
+ })
+ .await?;
self.last_stored_offsets.insert(partition_id, position);
Ok(())
}
@@ -220,14 +220,13 @@ impl IggyConsumerState {
if partition_id.is_none() && !self.is_consumer_group {
partition_id = Some(self.partition_id());
}
- let client = self.client.read().await;
- client
- .delete_consumer_offset(
- &self.consumer,
- &self.stream_id,
- &self.topic_id,
- partition_id,
- )
+ // Cancellation can hide a committed delete, so a later store must reach the server.
+ if let Some(partition_id) = partition_id {
+ self.last_stored_offsets.remove(&partition_id);
+ } else {
+ self.last_stored_offsets.clear();
+ }
+ self.mutate_offset(OffsetMutation::Delete { partition_id })
.await
}
@@ -245,32 +244,89 @@ impl IggyConsumerState {
if !allow_replay && self.stored_offset_covers(position) {
return Ok(());
}
- self.client
- .read()
- .await
- .store_consumer_position(&self.consumer, &self.stream_id, &self.topic_id, position)
+ self.mutate_offset(OffsetMutation::StorePosition(position))
.await?;
self.last_stored_offsets
.insert(position.partition_id, position);
Ok(())
}
- /// Whether the offset last stored for the partition is at or ahead of `position`. A store made
- /// before anything was consumed from the partition has no captured context, so it is compared
- /// with stores of every context rather than only within one incarnation and owner. Such a
- /// comparison never covers offset 0. Every record covers it, so a record from an earlier
- /// incarnation of a recreated partition otherwise skips the first offset of the new one.
+ async fn mutate_offset(&self, mutation: OffsetMutation) -> Result<(), IggyError> {
+ with_deadline(Instant::now() + OPERATION_TIMEOUT, async {
+ let deadline = operation_deadline();
+ let client = timeout_at(deadline, self.client.read())
+ .await
+ .map_err(|_| IggyError::TransientNotAccepted)?;
+ match self.send_offset_mutation(&client, mutation).await {
+ Err(IggyError::LaneBlocked(op)) => {
+ if matches!(
+ client.resolve_operation(op, deadline.into_std()).await,
+ Err(IggyError::OperationUncertain(_))
+ ) {
+ return Err(IggyError::LaneBlocked(op));
+ }
+ // The blocker has its own outcome. Re-entering the lane either
+ // admits this new mutation or reports that it remains blocked.
+ self.send_offset_mutation(&client, mutation).await
+ }
+ result => result,
+ }
+ })
+ .await
+ }
+
+ async fn send_offset_mutation(
+ &self,
+ client: &ClientWrapper,
+ mutation: OffsetMutation,
+ ) -> Result<(), IggyError> {
+ match mutation {
+ OffsetMutation::Store {
+ partition_id,
+ offset,
+ } => {
+ client
+ .store_consumer_offset(
+ &self.consumer,
+ &self.stream_id,
+ &self.topic_id,
+ Some(partition_id),
+ offset,
+ )
+ .await
+ }
+ OffsetMutation::StorePosition(position) => {
+ client
+ .store_consumer_position(
+ &self.consumer,
+ &self.stream_id,
+ &self.topic_id,
+ position,
+ )
+ .await
+ }
+ OffsetMutation::Delete { partition_id } => {
+ client
+ .delete_consumer_offset(
+ &self.consumer,
+ &self.stream_id,
+ &self.topic_id,
+ partition_id,
+ )
+ .await
+ }
+ }
+ }
+
+ /// An uncaptured scalar store cannot prove coverage in any partition history.
fn stored_offset_covers(&self, position: ConsumerPosition) -> bool {
- let uncaptured = PartitionContext::default();
self.last_stored_offsets
.get(&position.partition_id)
.is_some_and(|stored| {
- let comparable = if stored.context == uncaptured || position.context == uncaptured {
- position.offset > 0
- } else {
- same_incarnation_and_owner(stored.context, position.context)
- };
- comparable && position.offset <= stored.offset
+ stored.context.incarnation != 0
+ && position.context.incarnation != 0
+ && same_incarnation_and_owner(stored.context, position.context)
+ && position.offset <= stored.offset
})
}
@@ -508,9 +564,10 @@ unsafe impl Sync for IggyConsumer {}
/// arrived yet.
///
/// A failed poll request waits [`polling_retry_interval()`] before yielding `Some(Err(..))` and leaves
-/// the consumer usable for the next call. This delay also applies to terminal server errors and when
-/// the ordinary poll interval is disabled. Connection and authentication failures are yielded at once
-/// and pause polling until the client has reconnected and signed in again, which the consumer handles
+/// the consumer usable for the next call. This delay also applies to terminal server errors, to a lost
+/// link, and when the ordinary poll interval is disabled. An authentication failure is yielded at once
+/// and pauses polling until the client has signed in again. A disconnect of the whole client also
+/// pauses polling, until the client has reconnected and signed in again. The consumer handles both
/// automatically; the next call parks for [`polling_retry_interval()`] while polling is paused. Hence,
/// deciding when to give up on repeated errors is up to you.
///
@@ -879,9 +936,8 @@ impl IggyConsumer {
///
/// An offset that is not ahead of the last one stored in the same captured context is
/// skipped and `Ok(())` is returned without a request, unless the consumer was built with
- /// [`allow_replay`](crate::prelude::IggyConsumerBuilder::allow_replay). When either of the two
- /// has no captured context, see below, they are compared regardless of context, and offset
- /// `0` is never skipped.
+ /// [`allow_replay`](crate::prelude::IggyConsumerBuilder::allow_replay). A store without a
+ /// captured context is always sent and cannot suppress a later captured position.
///
/// The offset is committed under the context of the latest message consumed from that
/// partition, or without a captured context when nothing was consumed from it. An offset taken
@@ -895,11 +951,17 @@ impl IggyConsumer {
/// [`delete_offset()`](Self::delete_offset) after [`shutdown()`](Self::shutdown) and build a new
/// consumer. A new consumer built with [`PollingStrategy::offset()`] re-reads from any point.
///
+ /// On binary transports, a retained operation blocking this partition is resolved before
+ /// the requested store. Recovery and the new store share one operation deadline. The store
+ /// goes on after a proved commit or committed rejection of that operation, and the client keeps
+ /// the proved outcome for the caller that owns the operation, see
+ /// [`Client::resolve_operation`].
+ ///
/// # Errors
///
- /// Returns any error the server raised while storing the offset, for example
- /// [`IggyError::Disconnected`] or a permission error. The offset is then not stored and the
- /// call can be retried.
+ /// [`IggyError::OperationUncertain`] means this store may have committed and remains retained.
+ /// [`IggyError::LaneBlocked`] means the earlier operation is still unresolved and this store
+ /// was not sent. Other failures include connection, permission, history and ownership errors.
pub async fn store_offset(
&self,
offset: u64,
@@ -913,7 +975,7 @@ impl IggyConsumer {
/// refused without updating replacement progress.
///
/// # Errors
- /// Returns the server's storage, permission, history or ownership error.
+ /// Uses the recovery and error contract of [`Self::store_offset`].
pub async fn store_position(&self, position: ConsumerPosition) -> Result<(), IggyError> {
self.state.store_position(position).await
}
@@ -931,14 +993,16 @@ impl IggyConsumer {
/// [`PollingStrategy::next()`] starts at the first message.
///
/// `None` as `partition_id` means [`partition_id()`](Self::partition_id) for a standalone
- /// consumer. A consumer group passes `None` through to the server. This consumer's own records
- /// are untouched, so its auto-commit or [`shutdown()`](Self::shutdown) can store the offset
- /// again. When starting over, call it after [`shutdown()`](Self::shutdown).
+ /// consumer. A binary consumer group requires an explicit partition. Starting a delete
+ /// clears this consumer's stored-offset record, while retaining its consumed position, so
+ /// auto-commit or [`shutdown()`](Self::shutdown) can store that position again. When starting
+ /// over, call it after [`shutdown()`](Self::shutdown).
///
/// # Errors
///
/// Returns [`IggyError::ConsumerOffsetNotFound`] when nothing is stored for that partition, or
- /// any other error the server raised, for example [`IggyError::Disconnected`].
+ /// any other error the server raised. Uses the recovery and uncertainty contract of
+ /// [`Self::store_offset`].
pub async fn delete_offset(&self, partition_id: Option<u32>) -> Result<(), IggyError> {
self.state.delete_offset(partition_id).await
}
@@ -1000,9 +1064,9 @@ impl IggyConsumer {
/// stays idle under [`AutoCommit::Disabled`].
///
/// Both skip an offset that is not ahead of this consumer's own record of what it stored
- /// ([`get_last_stored_offset()`](Self::get_last_stored_offset)) in the same captured context,
- /// or by a [`store_offset()`](Self::store_offset) made before anything was consumed from that
- /// partition, which never covers offset `0`. Under auto-commit-on-poll (the default) that record trails the server by one
+ /// ([`get_last_stored_offset()`](Self::get_last_stored_offset)) in the same captured context.
+ /// An earlier scalar store without a captured context cannot suppress these commits.
+ /// Under auto-commit-on-poll (the default) that record trails the server by one
/// batch, so every tick re-sends the reading position and the server, which takes an explicit
/// store as is, moves its offset back to it until the next poll.
///
@@ -1426,19 +1490,22 @@ impl IggyConsumer {
return Ok(PolledMessages::empty());
}
- // Connection and auth errors: disable polling until the event task
- // re-enables it after reconnection and rejoin complete. Yielded at
- // once: the next poll already parks on `can_poll`, so a retry sleep
- // here would only delay the caller's view of an error it does not
- // act on.
- if matches!(
- error,
- IggyError::Disconnected | IggyError::Unauthenticated | IggyError::StaleClient
- ) {
+ // A member joins again after these errors. The join keeps the
+ // membership of a session that survived.
+ if is_consumer_group
+ && matches!(
+ error,
+ IggyError::Disconnected | IggyError::Unauthenticated | IggyError::StaleClient
+ )
+ {
+ joined_consumer_group.store(false, ORDERING);
+ }
+ // Only an error that an event always follows can stop polling: the
+ // sign-in that an unauthenticated client waits for publishes
+ // SignedIn. A link can come back, or bind the same session again,
+ // with no event while other links stay up, so other errors retry.
+ if matches!(error, IggyError::Unauthenticated) {
can_poll.store(false, ORDERING);
- if is_consumer_group {
- joined_consumer_group.store(false, ORDERING);
- }
return Err(error);
}
trace!("Retrying to poll messages in {retry_interval}...");
@@ -1795,9 +1862,10 @@ impl IggyConsumer {
/// forcing it to abort.
/// - commit the reading position of every partition where it is ahead of this consumer's own
/// record of what it stored, unless [`auto_commit()`] is [`AutoCommit::Disabled`]. Under
- /// auto-commit-on-poll (the default) the poll already committed the whole batch, so this
- /// store moves the server offset back to the last message handed over, and the next run
- /// resumes right after it instead of after the last batch fetched.
+ /// auto-commit-on-poll (the default), the poll admitted progress for the whole batch. This
+ /// store requests the last message handed over, so the next run resumes after it when the
+ /// store succeeds. On binary transports, final stores and any blocker recovery share one
+ /// operation deadline. HTTP retains its configured request timeout.
/// - leave the consumer group, if this consumer is a group member. This lets the server give its partitions to
/// the remaining members immediately instead of waiting for the connection to time out.
/// - stop the task watching the connection lifecycle.
@@ -1854,15 +1922,18 @@ impl IggyConsumer {
if self.auto_commit != AutoCommit::Disabled {
// Replay governs reading only: this flush must never move a stored offset back.
let allow_replay = false;
- for position in self.state.last_consumed_positions() {
- if let Err(error) = self
- .state
- .store_consumer_position(position, allow_replay)
- .await
- {
- warn!(?position, %error, "Final consumer checkpoint was not acknowledged");
+ with_deadline(Instant::now() + OPERATION_TIMEOUT, async {
+ for position in self.state.last_consumed_positions() {
+ if let Err(error) = self
+ .state
+ .store_consumer_position(position, allow_replay)
+ .await
+ {
+ warn!(?position, %error, "Final consumer checkpoint was not acknowledged");
+ }
}
- }
+ })
+ .await;
}
if self.is_consumer_group && self.joined_consumer_group.load(ORDERING) {
@@ -1922,31 +1993,32 @@ mod tests {
use super::*;
use crate::client_wrappers::client_wrapper::ClientWrapper;
use crate::clients::consumer_builder::IggyConsumerBuilder;
+ use crate::links::fake_cluster::{
+ Answer, FakeCluster, TEST_BUDGET, connected, endpoint, eventually,
+ };
use crate::tcp::tcp_client::TcpClient;
use iggy_binary_protocol::codes::{
- GET_CLUSTER_METADATA_CODE, GET_CONSUMER_OFFSET_ROUTING_CODE, GET_POLL_ROUTING_CODE,
- POLL_MESSAGES_ON_PRIMARY_CODE, SYNC_CONSUMER_GROUP_CODE,
+ DELETE_CONSUMER_OFFSET_CODE, GET_CONSUMER_GROUP_CODE, JOIN_CONSUMER_GROUP_CODE,
+ LOGIN_REGISTER_CODE, POLL_MESSAGES_CODE, STORE_CONSUMER_OFFSET_CODE,
+ SYNC_CONSUMER_GROUP_CODE,
+ };
+ use iggy_binary_protocol::consensus::EvictionReason;
+ use iggy_binary_protocol::requests::consumer_offsets::{
+ DeleteConsumerOffsetRequest, StoreConsumerOffsetRequest,
};
- use iggy_binary_protocol::requests::consumer_offsets::StoreConsumerOffsetRequest;
use iggy_binary_protocol::requests::messages::PollMessagesRequest;
- use iggy_binary_protocol::requests::system::SessionIdentity;
- use iggy_binary_protocol::responses::consumer_groups::SyncConsumerGroupResponse;
- use iggy_binary_protocol::responses::messages::PollRoutingResponse;
- use iggy_binary_protocol::responses::system::get_cluster_metadata::{
- ClusterMetadataResponse, ClusterNodeResponse,
+ use iggy_binary_protocol::responses::consumer_groups::{
+ ConsumerGroupDetailsResponse, ConsumerGroupResponse, SyncConsumerGroupResponse,
};
- use iggy_binary_protocol::{
- Command, HEADER_SIZE, Operation, ReplyHeader, RequestHeader, STATUS_OK, WireDecode,
- WireEncode,
+ use iggy_binary_protocol::responses::messages::{
+ PartitionRouteResponse, PollMessagesResponseHeader,
};
+ use iggy_binary_protocol::{PartitionContext, WireDecode, WireEncode, WireName};
+ use iggy_common::Aes256GcmEncryptor;
use iggy_common::locking::IggyRwLockFn;
- use iggy_common::{
- Aes256GcmEncryptor, BinaryTransport, ClientState, TcpClientConfig, VsrSessionControl,
- };
+ use std::iter::repeat_n;
use std::str::FromStr;
use std::task::Waker;
- use tokio::io::{AsyncReadExt, AsyncWriteExt};
- use tokio::net::TcpListener;
use tokio::time::timeout;
use tracing::field::Field;
use tracing::span::{Attributes, Id, Record};
@@ -2102,114 +2174,79 @@ mod tests {
assert!(consumer.next_offsets.is_empty());
}
- /// The requests a server from [`connect_to_test_server`] served.
- #[derive(Debug, Default)]
- struct Served {
- polled_partitions: Vec<u32>,
- stored_offsets: Vec<u64>,
+ struct Served(Arc<FakeCluster>);
+
+ impl Served {
+ fn stored_offsets(&self) -> Vec<u64> {
+ self.0
+ .received(STORE_CONSUMER_OFFSET_CODE)
+ .iter()
+ .map(|request| {
+ StoreConsumerOffsetRequest::decode_from(&request.body)
+ .unwrap()
+ .offset
+ })
+ .collect()
+ }
+
+ fn deleted_partitions(&self) -> Vec<u32> {
+ self.0
+ .received(DELETE_CONSUMER_OFFSET_CODE)
+ .iter()
+ .map(|request| {
+ DeleteConsumerOffsetRequest::decode_from(&request.body)
+ .unwrap()
+ .partition_id
+ .unwrap()
+ })
+ .collect()
+ }
+
+ fn polled_partitions(&self) -> Vec<u32> {
+ self.0
+ .received(POLL_MESSAGES_CODE)
+ .iter()
+ .map(|request| {
+ PollMessagesRequest::decode_from(&request.body)
+ .unwrap()
+ .partition_id
+ .unwrap()
+ })
+ .collect()
+ }
}
- /// Connects a signed-in client to a single-node server whose group assigns `partitions`. The
- /// server refuses every poll with `poll_refusal` and accepts every offset store.
async fn connect_to_test_server(
partitions: Vec<u32>,
poll_refusal: IggyError,
- ) -> (TcpClient, Arc<std::sync::Mutex<Served>>) {
- /// A result section without entries, which accepts a replicated request.
- const ACCEPTED: [u8; size_of::<u32>()] = STATUS_OK.to_le_bytes();
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let address = listener.local_addr().unwrap();
- let node = ClusterNodeResponse {
- replica_id: 0,
- name: "node".to_owned(),
- ip: address.ip().to_string(),
- tcp_port: address.port(),
- quic_port: 0,
- http_port: 0,
- websocket_port: 0,
- role: 1,
- status: 1,
- };
- let served = Arc::new(std::sync::Mutex::new(Served::default()));
- let server_served = Arc::clone(&served);
- tokio::spawn(async move {
- let (mut stream, _) = listener.accept().await.unwrap();
- let mut header = [0; HEADER_SIZE];
- while stream.read_exact(&mut header).await.is_ok() {
- let request: RequestHeader =
- bytemuck::checked::try_pod_read_unaligned(&header).unwrap();
- let mut body = vec![0; request.size as usize - HEADER_SIZE];
- stream.read_exact(&mut body).await.unwrap();
- let mut status = STATUS_OK;
- let reply = match (request.operation, u32::from_le_bytes(request.reserved)) {
- (Operation::StoreConsumerOffset, _) => {
- let store = StoreConsumerOffsetRequest::decode_from(&body).unwrap();
- server_served
- .lock()
- .unwrap()
- .stored_offsets
- .push(store.offset);
- Bytes::from_static(&ACCEPTED)
- }
- (_, GET_CLUSTER_METADATA_CODE) => ClusterMetadataResponse {
- name: "cluster".to_owned(),
- nodes: vec![node.clone()],
- }
- .to_bytes(),
- (_, SYNC_CONSUMER_GROUP_CODE) => SyncConsumerGroupResponse {
- generation: 1,
- partitions: partitions.clone(),
- }
- .to_bytes(),
- (_, GET_POLL_ROUTING_CODE | GET_CONSUMER_OFFSET_ROUTING_CODE) => {
- PollRoutingResponse {
- consumer_session: SessionIdentity {
- client_id: 1,
- session: 1,
- metadata_watermark: 0,
- },
- context: PartitionContext::default(),
- primary: node.clone(),
- }
- .to_bytes()
- }
- (_, POLL_MESSAGES_ON_PRIMARY_CODE) => {
- let poll = PollMessagesRequest::decode_from(&body).unwrap();
- server_served
- .lock()
- .unwrap()
- .polled_partitions
- .push(poll.partition_id.unwrap());
- status = poll_refusal.as_code();
- Bytes::new()
- }
- (operation, code) => panic!("unexpected {operation:?} request, code: {code}"),
- };
- let reply_header = ReplyHeader {
- command: Command::Reply,
- operation: request.operation,
- client: request.client,
- request: request.request,
- size: u32::try_from(HEADER_SIZE + reply.len()).unwrap(),
- status,
- ..Default::default()
- };
- stream
- .write_all(bytemuck::bytes_of(&reply_header))
- .await
- .unwrap();
- stream.write_all(&reply).await.unwrap();
- }
+ ) -> (TcpClient, Served) {
+ let cluster = FakeCluster::new(1);
+ *cluster.route.lock().unwrap() = Some(PartitionRouteResponse {
+ incarnation: 1,
+ metadata_op: 1,
+ view: 0,
+ partitions_count: partitions.iter().copied().max().unwrap_or_default() + 1,
+ primary_replica: 0,
});
- let client = TcpClient::create(Arc::new(TcpClientConfig {
- server_address: address.to_string(),
- ..Default::default()
- }))
- .unwrap();
- Client::connect(&client).await.unwrap();
- client.bind_vsr_session(1).await.unwrap();
- client.set_state(ClientState::Authenticated).await;
- (client, served)
+ cluster.script(
+ &endpoint(0),
+ SYNC_CONSUMER_GROUP_CODE,
+ [Answer::Body(
+ SyncConsumerGroupResponse {
+ generation: 1,
+ partitions,
+ }
+ .to_bytes()
+ .to_vec(),
+ )],
+ );
+ cluster.script(
+ &endpoint(0),
+ POLL_MESSAGES_CODE,
+ [Answer::Refuse(poll_refusal)],
+ );
+ let links = connected(&cluster, 1).await;
+ (TcpClient::from_links(links), Served(cluster))
}
#[tokio::test]
@@ -2240,10 +2277,7 @@ mod tests {
matches!(&polled, Some(Err(error)) if *error == refusal),
"{refusal}"
);
- assert_eq!(
- served.lock().unwrap().polled_partitions,
- [REFUSED_PARTITION]
- );
+ assert_eq!(served.polled_partitions(), [REFUSED_PARTITION]);
assert_eq!(next_offset(&consumer, REFUSED_PARTITION), None, "{refusal}");
assert_eq!(
next_offset(&consumer, RETAINED_PARTITION),
@@ -2259,6 +2293,7 @@ mod tests {
partition_id: 1,
offset,
context: PartitionContext {
+ incarnation: 1,
metadata_op,
..PartitionContext::default()
},
@@ -2291,7 +2326,7 @@ mod tests {
consumer.shutdown().await.unwrap();
- assert!(served.lock().unwrap().stored_offsets.is_empty());
+ assert!(served.stored_offsets().is_empty());
assert_eq!(consumer.get_last_stored_offset(1), Some(stored.offset));
}
@@ -2306,7 +2341,7 @@ mod tests {
consumer.store_offset(OFFSET, Some(1)).await.unwrap();
- assert_eq!(served.lock().unwrap().stored_offsets, [OFFSET]);
+ assert_eq!(served.stored_offsets(), [OFFSET]);
assert_eq!(consumer.get_last_stored_offset(1), Some(OFFSET));
}
@@ -2330,7 +2365,7 @@ mod tests {
}
#[tokio::test]
- async fn store_offset_without_a_consumed_position_should_skip_a_lower_offset() {
+ async fn store_offset_without_a_consumed_position_should_send_every_offset() {
let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
.partition(Some(1))
@@ -2340,8 +2375,8 @@ mod tests {
consumer.store_offset(STORED_OFFSET, Some(1)).await.unwrap();
consumer.store_offset(LOWER_OFFSET, Some(1)).await.unwrap();
- assert_eq!(served.lock().unwrap().stored_offsets, [STORED_OFFSET]);
- assert_eq!(consumer.get_last_stored_offset(1), Some(STORED_OFFSET));
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, LOWER_OFFSET]);
+ assert_eq!(consumer.get_last_stored_offset(1), Some(LOWER_OFFSET));
}
#[tokio::test]
@@ -2356,15 +2391,12 @@ mod tests {
consumer.store_offset(STORED_OFFSET, Some(1)).await.unwrap();
consumer.store_offset(LOWER_OFFSET, Some(1)).await.unwrap();
- assert_eq!(
- served.lock().unwrap().stored_offsets,
- [STORED_OFFSET, LOWER_OFFSET]
- );
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, LOWER_OFFSET]);
assert_eq!(consumer.get_last_stored_offset(1), Some(LOWER_OFFSET));
}
#[tokio::test]
- async fn store_position_should_skip_an_offset_behind_one_stored_without_a_consumed_position() {
+ async fn store_position_should_send_after_an_uncaptured_scalar_store() {
let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
.partition(Some(1))
@@ -2377,8 +2409,8 @@ mod tests {
.await
.unwrap();
- assert_eq!(served.lock().unwrap().stored_offsets, [STORED_OFFSET]);
- assert_eq!(consumer.get_last_stored_offset(1), Some(STORED_OFFSET));
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, LOWER_OFFSET]);
+ assert_eq!(consumer.get_last_stored_offset(1), Some(LOWER_OFFSET));
}
/// A recreated partition starts again at 0, and the offset stored without a consumed position
@@ -2397,12 +2429,12 @@ mod tests {
.await
.unwrap();
- assert_eq!(served.lock().unwrap().stored_offsets, [STORED_OFFSET, 0]);
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, 0]);
assert_eq!(consumer.get_last_stored_offset(1), Some(0));
}
#[tokio::test]
- async fn store_offset_without_a_consumed_position_should_not_move_a_stored_position_back() {
+ async fn store_offset_without_a_consumed_position_should_not_compare_a_captured_store() {
let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
.partition(Some(1))
@@ -2415,12 +2447,12 @@ mod tests {
.unwrap();
consumer.store_offset(LOWER_OFFSET, Some(1)).await.unwrap();
- assert_eq!(served.lock().unwrap().stored_offsets, [STORED_OFFSET]);
- assert_eq!(consumer.get_last_stored_offset(1), Some(STORED_OFFSET));
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, LOWER_OFFSET]);
+ assert_eq!(consumer.get_last_stored_offset(1), Some(LOWER_OFFSET));
}
#[tokio::test]
- async fn shutdown_should_not_move_back_an_offset_stored_without_a_consumed_position() {
+ async fn shutdown_should_store_the_captured_position_after_an_uncaptured_scalar_store() {
let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
let mut consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
.partition(Some(1))
@@ -2433,8 +2465,320 @@ mod tests {
consumer.shutdown().await.unwrap();
- assert_eq!(served.lock().unwrap().stored_offsets, [STORED_OFFSET]);
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, LOWER_OFFSET]);
+ assert_eq!(consumer.get_last_stored_offset(1), Some(LOWER_OFFSET));
+ }
+
+ #[tokio::test]
+ async fn given_a_deleted_offset_when_storing_the_same_position_should_send_again() {
+ let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
+ .partition(Some(1))
+ .auto_commit(AutoCommit::Disabled)
+ .build();
+ let position = captured_position_at(STORED_OFFSET);
+ consumer.store_position(position).await.unwrap();
+
+ consumer
+ .delete_offset(Some(position.partition_id))
+ .await
+ .unwrap();
+
+ assert_eq!(consumer.get_last_stored_offset(position.partition_id), None);
+ consumer.store_position(position).await.unwrap();
+ assert_eq!(served.deleted_partitions(), [position.partition_id]);
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, STORED_OFFSET]);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_an_unconfirmed_delete_when_storing_the_same_position_should_resolve_and_store() {
+ for cancel in [false, true] {
+ let (client, served) =
+ connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
+ .partition(Some(1))
+ .auto_commit(AutoCommit::Disabled)
+ .build();
+ let position = captured_position_at(STORED_OFFSET);
+ consumer.store_position(position).await.unwrap();
+ served.0.script(
+ &endpoint(0),
+ DELETE_CONSUMER_OFFSET_CODE,
+ [Answer::Silence, Answer::Commit(2)],
+ );
+
+ if cancel {
+ assert!(
+ tokio::time::timeout(POLL_RETRY_INTERVAL, consumer.delete_offset(Some(1)))
+ .await
+ .is_err()
+ );
+ } else {
+ assert!(matches!(
+ consumer.delete_offset(Some(1)).await,
+ Err(IggyError::OperationUncertain(_))
+ ));
+ }
+ assert_eq!(served.0.count(DELETE_CONSUMER_OFFSET_CODE), 1);
+ consumer.store_position(position).await.unwrap();
+
+ let deletes = served.0.received(DELETE_CONSUMER_OFFSET_CODE);
+ assert_eq!(deletes.len(), 2);
+ assert_eq!(deletes[0].header.request, deletes[1].header.request);
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, STORED_OFFSET]);
+ }
+ }
+
+ #[tokio::test]
+ async fn given_a_rejected_delete_when_storing_the_same_position_should_refresh_coverage() {
+ let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
+ .partition(Some(1))
+ .auto_commit(AutoCommit::Disabled)
+ .build();
+ let position = captured_position_at(STORED_OFFSET);
+ consumer.store_position(position).await.unwrap();
+ served.0.script(
+ &endpoint(0),
+ DELETE_CONSUMER_OFFSET_CODE,
+ [Answer::CommitRejected(2, IggyError::InvalidCommand)],
+ );
+
+ assert_eq!(
+ consumer.delete_offset(Some(1)).await,
+ Err(IggyError::InvalidCommand)
+ );
+ consumer.store_position(position).await.unwrap();
+
assert_eq!(consumer.get_last_stored_offset(1), Some(STORED_OFFSET));
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, STORED_OFFSET]);
+ }
+
+ #[tokio::test]
+ async fn given_a_stored_position_when_its_owner_or_incarnation_changes_should_store_the_lower_offset()
+ {
+ for context in [
+ PartitionContext {
+ owner_generation: 2,
+ ..captured_position_at(LOWER_OFFSET).context
+ },
+ PartitionContext {
+ incarnation: 2,
+ ..captured_position_at(LOWER_OFFSET).context
+ },
+ ] {
+ let (client, served) =
+ connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let consumer = builder_on(client, Consumer::group(Identifier::numeric(1).unwrap()))
+ .partition(Some(1))
+ .auto_commit(AutoCommit::Disabled)
+ .build();
+ consumer
+ .store_position(captured_position_at(STORED_OFFSET))
+ .await
+ .unwrap();
+
+ consumer
+ .store_position(ConsumerPosition {
+ context,
+ ..captured_position_at(LOWER_OFFSET)
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(served.stored_offsets(), [STORED_OFFSET, LOWER_OFFSET]);
+ let stores = served.0.received(STORE_CONSUMER_OFFSET_CODE);
+ assert_eq!(stores[1].header.partition_incarnation, context.incarnation);
+ assert_eq!(stores[1].header.owner_generation, context.owner_generation);
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_an_uncertain_store_when_the_blocker_is_rejected_should_store_the_new_position() {
+ let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
+ .partition(Some(1))
+ .auto_commit(AutoCommit::Disabled)
+ .build();
+ served.0.script(
+ &endpoint(0),
+ STORE_CONSUMER_OFFSET_CODE,
+ [
+ Answer::Silence,
+ Answer::CommitRejected(1, IggyError::HistoryUnavailable),
+ Answer::Commit(2),
+ ],
+ );
+ let first = consumer
+ .store_position(captured_position_at(LOWER_OFFSET))
+ .await;
+ let old = served.0.received(STORE_CONSUMER_OFFSET_CODE)[0]
+ .header
+ .request;
+ assert_eq!(first, Err(IggyError::OperationUncertain(old)));
+
+ consumer
+ .store_position(captured_position_at(STORED_OFFSET))
+ .await
+ .unwrap();
+
+ let resolved = consumer
+ .client
+ .read()
+ .await
+ .resolve_operation(old, (Instant::now() + OPERATION_TIMEOUT).into_std())
+ .await;
+ assert_eq!(resolved, Err(IggyError::HistoryUnavailable));
+ let stores = served.0.received(STORE_CONSUMER_OFFSET_CODE);
+ assert_eq!(
+ served.stored_offsets(),
+ [LOWER_OFFSET, LOWER_OFFSET, STORED_OFFSET]
+ );
+ assert_eq!(stores[0].header.request, stores[1].header.request);
+ assert_eq!(stores[0].body, stores[1].body);
+ assert_ne!(stores[1].header.request, stores[2].header.request);
+ assert_eq!(consumer.get_last_stored_offset(1), Some(STORED_OFFSET));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_an_uncertain_store_when_deleting_should_resolve_before_sending_the_delete() {
+ let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
+ .partition(Some(1))
+ .auto_commit(AutoCommit::Disabled)
+ .build();
+ served.0.script(
+ &endpoint(0),
+ STORE_CONSUMER_OFFSET_CODE,
+ [Answer::Silence, Answer::Commit(1)],
+ );
+ assert!(matches!(
+ consumer
+ .store_position(captured_position_at(LOWER_OFFSET))
+ .await,
+ Err(IggyError::OperationUncertain(_))
+ ));
+
+ consumer.delete_offset(Some(1)).await.unwrap();
+
+ let mutations: Vec<_> = served
+ .0
+ .codes(&endpoint(0))
+ .into_iter()
+ .filter(|code| {
+ matches!(
+ *code,
+ STORE_CONSUMER_OFFSET_CODE | DELETE_CONSUMER_OFFSET_CODE
+ )
+ })
+ .collect();
+ assert_eq!(
+ mutations,
+ [
+ STORE_CONSUMER_OFFSET_CODE,
+ STORE_CONSUMER_OFFSET_CODE,
+ DELETE_CONSUMER_OFFSET_CODE
+ ]
+ );
+ assert_eq!(served.deleted_partitions(), [1]);
+ assert_eq!(consumer.get_last_stored_offset(1), None);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_still_uncertain_store_when_storing_again_should_leave_the_new_position_unsent()
+ {
+ let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
+ .partition(Some(1))
+ .auto_commit(AutoCommit::Disabled)
+ .build();
+ served.0.script(
+ &endpoint(0),
+ STORE_CONSUMER_OFFSET_CODE,
+ [Answer::Silence, Answer::Silence],
+ );
+ assert!(matches!(
+ consumer
+ .store_position(captured_position_at(LOWER_OFFSET))
+ .await,
+ Err(IggyError::OperationUncertain(_))
+ ));
+ let old = served.0.received(STORE_CONSUMER_OFFSET_CODE)[0]
+ .header
+ .request;
+ let started = Instant::now();
+
+ let result = consumer
+ .store_position(captured_position_at(STORED_OFFSET))
+ .await;
+
+ assert_eq!(result, Err(IggyError::LaneBlocked(old)));
+ assert!(started.elapsed() <= OPERATION_TIMEOUT);
+ assert_eq!(served.stored_offsets(), [LOWER_OFFSET, LOWER_OFFSET]);
+ assert_eq!(consumer.get_last_stored_offset(1), None);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_multiple_final_positions_when_shutdown_times_out_should_share_one_deadline() {
+ let (client, served) =
+ connect_to_test_server(vec![1, 2], IggyError::HistoryUnavailable).await;
+ let mut consumer =
+ builder_on(client, Consumer::new(Identifier::numeric(1).unwrap())).build();
+ for partition_id in [1, 2] {
+ consumer.state.last_consumed_offsets.insert(
+ partition_id,
+ ConsumerPosition {
+ partition_id,
+ ..captured_position_at(LOWER_OFFSET)
+ },
+ );
+ }
+ served.0.script(
+ &endpoint(0),
+ STORE_CONSUMER_OFFSET_CODE,
+ [Answer::Silence, Answer::Silence],
+ );
+ let started = Instant::now();
+
+ consumer.shutdown().await.unwrap();
+
+ assert!(started.elapsed() <= OPERATION_TIMEOUT);
+ assert_eq!(served.stored_offsets(), [LOWER_OFFSET]);
+ assert_eq!(consumer.get_last_stored_offset(1), None);
+ assert_eq!(consumer.get_last_stored_offset(2), None);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_an_inflight_background_store_when_shutdown_aborts_it_should_resolve_and_flush() {
+ let (client, served) = connect_to_test_server(vec![1], IggyError::HistoryUnavailable).await;
+ let mut consumer = builder_on(client, Consumer::new(Identifier::numeric(1).unwrap()))
+ .offset_drain_timeout(IggyDuration::new(POLL_RETRY_INTERVAL))
+ .build();
+ consumer
+ .state
+ .last_consumed_offsets
+ .insert(1, captured_position_at(LOWER_OFFSET));
+ served.0.script(
+ &endpoint(0),
+ STORE_CONSUMER_OFFSET_CODE,
+ [Answer::Silence, Answer::Commit(1), Answer::Commit(2)],
+ );
+ consumer.background_commit_task =
+ Some(consumer.store_offsets_in_background(
+ NonZeroIggyDuration::new(POLL_RETRY_INTERVAL).unwrap(),
+ ));
+ eventually("background store reached the primary", || {
+ served.0.count(STORE_CONSUMER_OFFSET_CODE) == 1
+ })
+ .await;
+
+ consumer.shutdown().await.unwrap();
+
+ let stores = served.0.received(STORE_CONSUMER_OFFSET_CODE);
+ assert_eq!(stores.len(), 3);
+ assert_eq!(stores[0].header.request, stores[1].header.request);
+ assert_ne!(stores[1].header.request, stores[2].header.request);
+ assert_eq!(consumer.get_last_stored_offset(1), Some(LOWER_OFFSET));
}
/// Records the error events emitted on the test thread. The current-thread runtime of
@@ -2652,4 +2996,181 @@ mod tests {
);
}
}
+
+ const POLLED_PARTITION: u32 = 1;
+ const PARTITION_PRIMARY: u8 = 1;
+
+ /// A signed-in client of three ready replicas. Replica 0 is the metadata
+ /// primary, and `PARTITION_PRIMARY` leads every partition.
+ async fn connect_to_three_replicas() -> (TcpClient, Arc<FakeCluster>) {
+ let cluster = FakeCluster::new(3);
+ *cluster.route.lock().unwrap() = Some(PartitionRouteResponse {
+ incarnation: 1,
+ metadata_op: 1,
+ view: 0,
+ partitions_count: POLLED_PARTITION + 1,
+ primary_replica: PARTITION_PRIMARY,
+ });
+ let links = connected(&cluster, 3).await;
+ (TcpClient::from_links(links), cluster)
+ }
+
+ /// A consumer of `POLLED_PARTITION` whose polling follows the client
+ /// events, as after `init`.
+ async fn polling_consumer(client: TcpClient, consumer: Consumer) -> IggyConsumer {
+ let mut consumer = builder_on(client, consumer)
+ .partition(Some(POLLED_PARTITION))
+ .polling_strategy(PollingStrategy::first())
+ .auto_commit(AutoCommit::Disabled)
+ .polling_retry_interval(NonZeroIggyDuration::new(POLL_RETRY_INTERVAL).unwrap())
+ .build();
+ consumer.events_task = Some(consumer.subscribe_events().await);
+ consumer
+ }
+
+ fn empty_poll() -> Answer {
+ let header = PollMessagesResponseHeader {
+ partition_id: POLLED_PARTITION,
+ current_offset: 0,
+ messages_count: 0,
+ context: PartitionContext::default(),
+ };
+ Answer::CommitBody(1, header.to_bytes().to_vec())
+ }
+
+ /// Polls one poll after another, as the consumer stream does, until one
+ /// succeeds.
+ async fn poll_until_success(consumer: &IggyConsumer) -> Option<PolledMessages> {
+ let polled = async {
+ loop {
+ if let Ok(polled) = consumer.create_poll_messages_future().await {
+ return polled;
+ }
+ }
+ };
+ timeout(TEST_BUDGET, polled).await.ok()
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_live_session_when_a_replica_refuses_a_poll_with_stale_client_should_poll_again_without_a_new_sign_in()
+ {
+ let (client, cluster) = connect_to_three_replicas().await;
+ let consumer =
+ polling_consumer(client, Consumer::new(Identifier::numeric(1).unwrap())).await;
+ cluster.script(
+ &endpoint(PARTITION_PRIMARY),
+ POLL_MESSAGES_CODE,
+ [Answer::Detached, empty_poll()],
+ );
+
+ let refused = consumer.create_poll_messages_future().await;
+
+ assert!(
+ matches!(refused, Err(IggyError::StaleClient)),
+ "{refused:?}"
+ );
+ assert!(poll_until_success(&consumer).await.is_some());
+ assert_eq!(cluster.count(POLL_MESSAGES_CODE), 2);
+ assert_eq!(cluster.count(LOGIN_REGISTER_CODE), 1);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_lost_route_link_when_a_poll_outlasts_it_should_poll_again_once_the_link_is_back()
+ {
+ let (client, cluster) = connect_to_three_replicas().await;
+ let consumer =
+ polling_consumer(client, Consumer::new(Identifier::numeric(1).unwrap())).await;
+ let primary = endpoint(PARTITION_PRIMARY);
+ cluster.down.lock().unwrap().insert(primary.clone());
+ cluster.drop_connections(&primary);
+
+ let lost = consumer.create_poll_messages_future().await;
+
+ assert!(matches!(lost, Err(IggyError::NotConnected)), "{lost:?}");
+ cluster.down.lock().unwrap().clear();
+ cluster.script(&primary, POLL_MESSAGES_CODE, [empty_poll()]);
+ assert!(poll_until_success(&consumer).await.is_some());
+ assert_eq!(cluster.count(LOGIN_REGISTER_CODE), 1);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_an_unauthenticated_poll_when_the_client_signs_in_again_should_wait_for_signed_in()
+ {
+ let (client, cluster) = connect_to_three_replicas().await;
+ let consumer =
+ polling_consumer(client, Consumer::new(Identifier::numeric(1).unwrap())).await;
+ *cluster.session.lock().unwrap() = None;
+ cluster
+ .held_registers
+ .lock()
+ .unwrap()
+ .insert("iggy".to_owned());
+ cluster.script(
+ &endpoint(PARTITION_PRIMARY),
+ POLL_MESSAGES_CODE,
+ [Answer::Evict(EvictionReason::NoSession), empty_poll()],
+ );
+
+ let evicted = consumer.create_poll_messages_future().await;
+
+ assert!(
+ matches!(evicted, Err(IggyError::Unauthenticated)),
+ "{evicted:?}"
+ );
+ eventually("the client signs in again", || {
+ cluster.count(LOGIN_REGISTER_CODE) == 2
+ })
+ .await;
+ let parked = timeout(POLL_TIMEOUT, consumer.create_poll_messages_future()).await;
+ assert!(parked.is_err(), "{parked:?}");
+ assert_eq!(cluster.count(POLL_MESSAGES_CODE), 1);
+ cluster.held_registers.lock().unwrap().clear();
+ assert!(poll_until_success(&consumer).await.is_some());
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_group_member_when_a_poll_finds_its_session_ended_should_sign_in_and_join_again()
+ {
+ let (client, cluster) = connect_to_three_replicas().await;
+ let consumer =
+ polling_consumer(client, Consumer::group(Identifier::numeric(1).unwrap())).await;
+ let group = ConsumerGroupDetailsResponse {
+ group: ConsumerGroupResponse {
+ id: 1,
+ partitions_count: POLLED_PARTITION + 1,
+ members_count: 0,
+ name: WireName::new("consumer").unwrap(),
+ },
+ members: Vec::new(),
+ };
+ let assignment = SyncConsumerGroupResponse {
+ generation: 1,
+ partitions: vec![POLLED_PARTITION],
+ };
+ cluster.script(
+ &endpoint(0),
+ GET_CONSUMER_GROUP_CODE,
+ repeat_n(Answer::Body(group.to_bytes().to_vec()), 2),
+ );
+ cluster.script(
+ &endpoint(0),
+ SYNC_CONSUMER_GROUP_CODE,
+ repeat_n(Answer::Body(assignment.to_bytes().to_vec()), 2),
+ );
+ cluster.script(
+ &endpoint(PARTITION_PRIMARY),
+ POLL_MESSAGES_CODE,
+ [Answer::Refuse(IggyError::StaleClient), empty_poll()],
+ );
+
+ let refused = consumer.create_poll_messages_future().await;
+
+ assert!(
+ matches!(refused, Err(IggyError::StaleClient)),
+ "{refused:?}"
+ );
+ assert!(poll_until_success(&consumer).await.is_some());
+ assert_eq!(cluster.count(LOGIN_REGISTER_CODE), 2);
+ assert_eq!(cluster.count(JOIN_CONSUMER_GROUP_CODE), 2);
+ }
}
diff --git a/core/sdk/src/clients/mod.rs b/core/sdk/src/clients/mod.rs
index 1a310450f..f83267693 100644
--- a/core/sdk/src/clients/mod.rs
+++ b/core/sdk/src/clients/mod.rs
@@ -15,8 +15,20 @@
// specific language governing permissions and limitations
// under the License.
-use crate::client_wrappers::client_wrapper::ClientWrapper;
-use iggy_common::{BinaryTransport, ClientState};
+macro_rules! with_client {
+ ($self:expr, $client:ident => $body:expr) => {{
+ let deadline = iggy_common::binary_operation_deadline();
+ iggy_common::with_binary_deadline(deadline, async {
+ let $client = tokio::time::timeout_at(deadline, $self.client.read())
+ .await
+ .map_err(|_| iggy_common::IggyError::TransientNotAccepted)?;
+ $body
+ })
+ .await
+ }};
+}
+
+pub(crate) use with_client;
mod binary_cluster;
mod binary_consumer_group;
@@ -42,34 +54,6 @@ pub mod producer_sharding;
const ORDERING: std::sync::atomic::Ordering = std::sync::atomic::Ordering::SeqCst;
-/// Whether the reconnect that followed a leader redirect already left this
-/// client signed in as the user the redirected sign-in was for.
-///
-/// The connect flow signs in with the credentials that sign-in just
-/// remembered, so on a client without a configured `AutoLogin` the session on
-/// the leader is already the right one: signing in again would run a logout
-/// plus a second login, an argon2 each on the server, to arrive where the
-/// client already is. With `AutoLogin::Enabled(a)` the reconnect signed in the
-/// configured user instead, who need not be the one signing in here, so the
-/// sign-in still has to run.
-pub(crate) async fn redirect_login_settled(client: &ClientWrapper) -> bool {
- let (state, auto_login_configured) = match client {
- ClientWrapper::Tcp(tcp_client) => (
- tcp_client.get_state().await,
- tcp_client.auto_login_configured(),
- ),
- ClientWrapper::Quic(quic_client) => (
- quic_client.get_state().await,
- quic_client.auto_login_configured(),
- ),
- ClientWrapper::WebSocket(ws_client) => (
- ws_client.get_state().await,
- ws_client.auto_login_configured(),
- ),
- _ => return false,
- };
-
- state == ClientState::Authenticated && !auto_login_configured
-}
-const MAX_BATCH_LENGTH: usize = 1000000;
+/// The messages per request of a direct producer whose `batch_length` is 0.
+pub const MAX_BATCH_LENGTH: std::num::NonZeroU32 = std::num::NonZeroU32::new(1_000_000).unwrap();
const MIB: usize = 1_048_576;
diff --git a/core/sdk/src/clients/producer.rs b/core/sdk/src/clients/producer.rs
index 9e234b60d..7c42a0b38 100644
--- a/core/sdk/src/clients/producer.rs
+++ b/core/sdk/src/clients/producer.rs
@@ -21,21 +21,24 @@ use crate::clients::MAX_BATCH_LENGTH;
use crate::clients::producer_builder::SendMode;
use crate::clients::producer_config::DirectConfig;
use crate::clients::producer_dispatcher::ProducerDispatcher;
+use crate::driver::{operation_deadline, with_deadline};
+use crate::links::OPERATION_TIMEOUT;
use bytes::Bytes;
-use futures_util::StreamExt;
use iggy_common::locking::{IggyRwLock, IggyRwLockFn};
-use iggy_common::{Client, MessageClient, StreamClient, TopicClient, TopicCreateOptions};
+use iggy_common::{BinarySendPartitioning, Client, StreamClient, TopicClient, TopicCreateOptions};
use iggy_common::{
- DiagnosticEvent, Durability, EncryptorKind, IdKind, Identifier, IggyError, IggyExpiry,
- IggyMessage, IggyTimestamp, MaxTopicSize, NonZeroIggyDuration, Partitioner, Partitioning,
- SendMessagesConfirmationResponse, SendMessagesResponse,
+ Durability, EncryptorKind, IdKind, Identifier, IggyError, IggyExpiry, IggyMessage,
+ IggyTimestamp, MaxTopicSize, Partitioner, Partitioning, SendMessagesConfirmationResponse,
+ SendMessagesResponse,
};
-use std::sync::Arc;
+use std::collections::HashSet;
+use std::num::NonZeroU32;
use std::sync::atomic::Ordering;
use std::sync::atomic::{AtomicBool, AtomicU64};
+use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
-use tokio::time::{Interval, sleep};
-use tracing::{error, info, trace, warn};
+use tokio::time::{Instant, sleep, timeout_at};
+use tracing::{error, info, trace};
#[cfg(test)]
use mockall::automock;
@@ -61,20 +64,8 @@ pub(crate) fn no_confirmations() -> SendMessagesResponse {
}
}
-/// A producer retry creates another request identity. Only a refusal or
-/// failure before submission permits that; ambiguous retries belong to the transport.
-const fn stops_send_retries(error: &IggyError) -> bool {
- !matches!(
- error,
- IggyError::TransientNotAccepted
- | IggyError::NotConnected
- | IggyError::CannotEstablishConnection
- )
-}
-
pub struct ProducerCore {
initialized: AtomicBool,
- can_send: Arc<AtomicBool>,
client: Arc<IggyRwLock<ClientWrapper>>,
stream_id: Arc<Identifier>,
stream_name: String,
@@ -91,8 +82,7 @@ pub struct ProducerCore {
topic_durability: Durability,
default_partitioning: Arc<Partitioning>,
last_sent_at: Arc<AtomicU64>,
- send_retries_count: Option<u32>,
- send_retries_interval: Option<NonZeroIggyDuration>,
+ uncertain_operations: Mutex<HashSet<u64>>,
direct_config: Option<DirectConfig>,
}
@@ -105,7 +95,6 @@ impl ProducerCore {
let stream_id = self.stream_id.clone();
let topic_id = self.topic_id.clone();
info!("Initializing producer for stream: {stream_id} and topic: {topic_id}...");
- self.subscribe_events().await;
let client = self.client.clone();
let client = client.read().await;
if client.get_stream(&stream_id).await?.is_none() {
@@ -174,43 +163,6 @@ impl ProducerCore {
Ok(())
}
- async fn subscribe_events(&self) {
- trace!("Subscribing to diagnostic events");
- let mut receiver;
- {
- let client = self.client.read().await;
- receiver = client.subscribe_events().await;
- }
-
- let can_send = self.can_send.clone();
-
- tokio::spawn(async move {
- while let Some(event) = receiver.next().await {
- trace!("Received diagnostic event: {event}");
- match event {
- DiagnosticEvent::Shutdown => {
- can_send.store(false, ORDERING);
- warn!("Client has been shutdown");
- }
- DiagnosticEvent::Connected => {
- can_send.store(false, ORDERING);
- trace!("Connected to the server");
- }
- DiagnosticEvent::Disconnected => {
- can_send.store(false, ORDERING);
- warn!("Disconnected from the server");
- }
- DiagnosticEvent::SignedIn => {
- can_send.store(true, ORDERING);
- }
- DiagnosticEvent::SignedOut => {
- can_send.store(false, ORDERING);
- }
- }
- }
- });
- }
-
async fn try_send_messages(
&self,
stream: &Identifier,
@@ -218,113 +170,56 @@ impl ProducerCore {
partitioning: &Arc<Partitioning>,
messages: &mut [IggyMessage],
) -> Result<SendMessagesResponse, IggyError> {
- let client = self.client.read().await;
-
- let Some(max_retries) = self.send_retries_count else {
- return client
- .send_messages(stream, topic, partitioning, messages)
- .await;
- };
-
- if max_retries == 0 {
- return client
- .send_messages(stream, topic, partitioning, messages)
+ with_deadline(Instant::now() + OPERATION_TIMEOUT, async {
+ let deadline = operation_deadline();
+ let client = timeout_at(deadline, self.client.read())
+ .await
+ .map_err(|_| IggyError::TransientNotAccepted)?;
+ timeout_at(deadline, self.prune_uncertain_operations(&client))
+ .await
+ .map_err(|_| IggyError::TransientNotAccepted)?;
+ let mut partitioning = BinarySendPartitioning::new(partitioning);
+ let mut result = client
+ .send_messages_with_partitioning(stream, topic, &mut partitioning, messages)
.await;
- }
-
- self.wait_until_connected(max_retries, stream, topic)
- .await?;
- self.send_with_retries(&client, max_retries, stream, topic, partitioning, messages)
- .await
- }
-
- async fn wait_until_connected(
- &self,
- max_retries: u32,
- stream: &Identifier,
- topic: &Identifier,
- ) -> Result<(), IggyError> {
- let mut retries = 0;
- let mut timer: Option<Interval> = None;
-
- while !self.can_send.load(ORDERING) {
- retries += 1;
- if retries > max_retries {
- error!(
- "Failed to send messages to topic: {topic}, stream: {stream} \
- after {max_retries} retries. Client is disconnected."
- );
- return Err(IggyError::CannotSendMessagesDueToClientDisconnection);
+ let blocker = match &result {
+ Err(IggyError::LaneBlocked(op)) if self.uncertain_operations().contains(op) => {
+ Some(*op)
+ }
+ _ => None,
+ };
+ if let Some(op) = blocker {
+ if matches!(
+ client.resolve_operation(op, deadline.into_std()).await,
+ Err(IggyError::OperationUncertain(_))
+ ) {
+ return Err(IggyError::LaneBlocked(op));
+ }
+ // This call's chunk has not been sent. The earlier chunk is
+ // resolved separately and is never submitted as a fresh request.
+ result = client
+ .send_messages_with_partitioning(stream, topic, &mut partitioning, messages)
+ .await;
}
-
- error!(
- "Trying to send messages to topic: {topic}, stream: {stream} \
- but the client is disconnected. Retrying {retries}/{max_retries}..."
- );
-
- if let Some(interval) = self.send_retries_interval {
- let timer =
- timer.get_or_insert_with(|| tokio::time::interval(interval.get_duration()));
- trace!(
- "Waiting for the next retry to send messages to topic: {topic}, \
- stream: {stream} for disconnected client..."
- );
- timer.tick().await;
+ if let Err(IggyError::OperationUncertain(op)) = &result {
+ self.uncertain_operations().insert(*op);
}
- }
- Ok(())
+ result
+ })
+ .await
}
- async fn send_with_retries(
- &self,
- client: &ClientWrapper,
- max_retries: u32,
- stream: &Identifier,
- topic: &Identifier,
- partitioning: &Arc<Partitioning>,
- messages: &mut [IggyMessage],
- ) -> Result<SendMessagesResponse, IggyError> {
- let mut retries = 0;
- let mut timer: Option<Interval> = None;
-
- loop {
- match client
- .send_messages(stream, topic, partitioning, messages)
- .await
- {
- // Only the attempt that finally succeeds yields a confirmation;
- // failed attempts have none to report.
- Ok(confirmation) => return Ok(confirmation),
- Err(error) => {
- if stops_send_retries(&error) {
- error!("Send stopped for topic: {topic}, stream: {stream}: {error}");
- return Err(error);
- }
-
- retries += 1;
- if retries > max_retries {
- error!(
- "Failed to send messages to topic: {topic}, stream: {stream} \
- after {max_retries} retries. {error}."
- );
- return Err(error);
- }
-
- error!(
- "Failed to send messages to topic: {topic}, stream: {stream}. \
- {error} Retrying {retries}/{max_retries}..."
- );
+ fn uncertain_operations(&self) -> MutexGuard<'_, HashSet<u64>> {
+ self.uncertain_operations
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
- if let Some(interval) = self.send_retries_interval {
- let timer = timer
- .get_or_insert_with(|| tokio::time::interval(interval.get_duration()));
- trace!(
- "Waiting for the next retry to send messages to topic: {topic}, \
- stream: {stream}..."
- );
- timer.tick().await;
- }
- }
+ async fn prune_uncertain_operations(&self, client: &ClientWrapper) {
+ let operations: Vec<_> = self.uncertain_operations().iter().copied().collect();
+ for op in operations {
+ if !client.retains_operation(op).await {
+ self.uncertain_operations().remove(&op);
}
}
}
@@ -432,11 +327,9 @@ impl ProducerCoreBackend for ProducerCore {
.await;
}
- let max = if cfg.batch_length == 0 {
- MAX_BATCH_LENGTH
- } else {
- cfg.batch_length as usize
- };
+ let max = NonZeroU32::new(cfg.batch_length)
+ .unwrap_or(MAX_BATCH_LENGTH)
+ .get() as usize;
let mut index = 0;
let mut confirmations = Vec::with_capacity(msgs.len().div_ceil(max));
while index < msgs.len() {
@@ -561,7 +454,6 @@ unsafe impl Sync for IggyProducer {}
/// .topic_durability(Durability::Persisted)
/// // Every message of this producer goes to the partition the server derives from the key.
/// .partitioning(Partitioning::messages_key_str("my-key")?)
-/// .send_retries(Some(5), Some(NonZeroIggyDuration::ONE_SECOND))
/// .build();
/// producer.init().await?;
///
@@ -671,51 +563,39 @@ unsafe impl Sync for IggyProducer {}
///
/// # Retrying and what a failure means
///
-/// A producer retry sends the same batch under a new request ID without rewriting, splitting, or
-/// reordering it. [`send_retries()`] sets how many times it may try and how
-/// later retries are paced. The default allows three retries and configures a one-second interval.
-/// The first retry is immediate. Later retries wait for the next tick of an interval timer, so they
-/// are at most one interval apart, and an attempt that outlasts the interval is followed by the next
-/// one right away. Passing `None` as the interval retries back-to-back without any delay. The retry
-/// policy applies to both direct and background producers.
-///
-/// A request can fail after the server has already appended it, so the first request of an
-/// unconfirmed tail may already be in the partition. Sending the tail again can therefore write the
-/// same messages twice, leaving the batch in the partition at multiple offsets. A consumer that
-/// cannot accept duplicates must recognize application resends itself. The producer stops on
-/// ambiguous failures such as [`IggyError::Disconnected`] and [`IggyError::TransientNotCommitted`].
-/// Binary transport retries keep the encoded request identity and can replay its durable result.
-/// [`IggyError::RequestTooOld`] is ambiguous as well, but the server returns it only after a later
-/// write of the same client session has committed to that partition. A resend would land behind
-/// that write, out of send order, so the producer stops and leaves the unconfirmed batch to the
-/// caller.
-///
-/// What is retried, and what is not:
+/// Each binary chunk uses one operation deadline. Transport retries preserve its
+/// request identity, body and partition context. The producer does not create a
+/// new identity to retry a chunk that might already have committed.
///
-/// | Situation | Retried | What the caller ends up with |
-/// | --- | --- | --- |
-/// | the client is not signed in, so nothing may be sent yet | yes | the send goes ahead as soon as the client is signed in, or fails with [`IggyError::CannotSendMessagesDueToClientDisconnection`] once the retry budget is spent |
-/// | the binary transport reports that the server refused admission ([`IggyError::TransientNotAccepted`]) | yes, as a new request | the confirmation of the admitted attempt, or the final refusal |
-/// | the binary transport cannot connect before submission ([`IggyError::NotConnected`] or [`IggyError::CannotEstablishConnection`]) | yes, as a new request | the confirmation of the submitted attempt, or the final connection error |
-/// | an HTTP request fails, including a server admission refusal | no producer retry | the HTTP error; HTTP transport retries are configured separately below |
-/// | another request error or an ambiguous failure | no | the cause and unconfirmed batch; the caller decides whether to resend |
-/// | the batch committed, but its confirmation could not be read ([`IggyError::InvalidBytesResponse`] or [`IggyError::InvalidJsonResponse`], raised on the HTTP transport only) | no | the write did happen and retrying would duplicate it on purpose |
-/// | the request aged out of the dedup window ([`IggyError::RequestTooOld`]) | no | its outcome is unknown, and the server refuses the resend while it retains the client entry |
-/// | encrypting or partitioning the batch failed | no | that cause, with the whole batch returned as unconfirmed because nothing was sent, although earlier messages may already have been encrypted in place |
-/// | [`send_retries()`] passed `None` or `0` | no | the outcome of the single producer attempt, which skips the sign-in check above and fails with the transport error when the client is disconnected |
+/// A chunk returned with [`IggyError::OperationUncertain`] stays retained by the
+/// client and blocks its partition lane. A later producer call blocked by one
+/// of this producer's uncertain chunks resolves that earlier operation first,
+/// then sends the new call's chunk within the same deadline. A blocker owned by
+/// another producer remains [`IggyError::LaneBlocked`] for the caller to handle.
+/// An [`IggyConsumer`](crate::clients::consumer::IggyConsumer) on the same client
+/// resolves any blocker, including an uncertain chunk owned by this producer.
///
-/// After the server evicts the client entry, an aged-out resend could execute behind later
-/// committed writes and duplicate the batch.
+/// `OperationUncertain(op)` identifies the first chunk of `failed`; it may
+/// already have committed. `LaneBlocked(op)` means none of `failed` was sent.
+/// Resolving the blocker never resubmits the earlier failed chunk as a new write.
+/// [`Client::resolve_operation`] tells the caller that got `OperationUncertain(op)`
+/// the outcome of that chunk, also after a later producer or consumer call
+/// resolved `op` first. That call only frees the lane, and the client keeps the
+/// proved outcome for its owner. A chunk carries no committed rejection, so
+/// `Ok(())` is its only proved outcome, and then only the messages after that
+/// chunk still need a send.
+/// A session reset or explicit abandonment can destroy the retained result
+/// before a replay proves it.
+/// [`IggyError::OperationNotRetained`] does not prove the earlier chunk failed,
+/// so resubmitting its payload as a new call can duplicate messages.
///
-/// To be precise: the budget is spent per request. Every chunk of a split is a request that gets its own retry budget.
-/// Also, waiting for the client to sign in is counted separately from retrying the write itself.
+/// A committed chunk whose confirmation cannot be decoded succeeds with no
+/// offset information. Missing confirmation or an aged-out request does not
+/// prove that no messages were appended.
///
-/// The HTTP transport also resends a failed POST on its own, up to [`HttpClientConfig::retries`]
-/// times (3 by default), when the server answers with a 5xx, 408 or 429 status or the connection
-/// fails. HTTP admission refusals remain [`IggyError::HttpResponseError`] and do not trigger
-/// producer retries. Each transport resend is a new write, even with `send_retries(None)`.
-/// A 504 or a connection lost mid-request leaves the outcome unknown, so such
-/// a resend can duplicate the batch.
+/// HTTP has no retained-operation recovery. Its configured transport retries
+/// may resend a failed POST under a new identity. An ambiguous HTTP failure can
+/// therefore leave duplicate messages; the producer adds no further retry.
///
/// Where a failure surfaces is the main difference between the two modes. Either way it names the
/// same three pieces: the `cause`, the unconfirmed tail, and confirmations returned for earlier
@@ -743,7 +623,6 @@ unsafe impl Sync for IggyProducer {}
/// | [`direct()`] / [`background()`] | [`direct()`] with the [`DirectConfig`] defaults, 1000 messages per request and no linger time | whether a send waits for the write |
/// | [`partitioning()`] | [`Partitioning::balanced()`] | which partition a batch lands in |
/// | [`partitioner()`] | none | computing the partition on the client instead |
-/// | [`send_retries()`] | three retries, one-second interval after the immediate first retry | retrying a failed request |
/// | [`topic_durability()`](crate::clients::producer_builder::IggyProducerBuilder::topic_durability) | `Durability::Replicated` | crash-safe retry receipts require `Durability::Persisted` |
/// | [`create_stream_if_not_exists()`] | on | creating the stream during [`init()`](Self::init) |
/// | [`create_topic_if_not_exists()`] | on, one partition, server defaults for expiry and max size | creating the topic during [`init()`](Self::init) |
@@ -793,7 +672,6 @@ unsafe impl Sync for IggyProducer {}
/// [`BackgroundConfig::sharding`]: crate::clients::producer_config::BackgroundConfig::sharding
/// [`BalancedSharding`]: crate::clients::producer_sharding::BalancedSharding
/// [`ErrorCallback`]: crate::clients::producer_error_callback::ErrorCallback
-/// [`HttpClientConfig::retries`]: iggy_common::HttpClientConfig::retries
/// [`OrderedSharding`]: crate::clients::producer_sharding::OrderedSharding
/// [`background()`]: crate::clients::producer_builder::IggyProducerBuilder::background
/// [`build()`]: crate::clients::producer_builder::IggyProducerBuilder::build
@@ -805,7 +683,6 @@ unsafe impl Sync for IggyProducer {}
/// [`encryptor()`]: crate::clients::producer_builder::IggyProducerBuilder::encryptor
/// [`partitioner()`]: crate::clients::producer_builder::IggyProducerBuilder::partitioner
/// [`partitioning()`]: crate::clients::producer_builder::IggyProducerBuilder::partitioning
-/// [`send_retries()`]: crate::clients::producer_builder::IggyProducerBuilder::send_retries
/// [`stream()`]: crate::clients::producer_builder::IggyProducerBuilder::stream
/// [`topic()`]: crate::clients::producer_builder::IggyProducerBuilder::topic
/// [`without_encryptor()`]: crate::clients::producer_builder::IggyProducerBuilder::without_encryptor
@@ -833,14 +710,11 @@ impl IggyProducer {
topic_message_expiry: IggyExpiry,
topic_max_size: MaxTopicSize,
topic_durability: Durability,
- send_retries_count: Option<u32>,
- send_retries_interval: Option<NonZeroIggyDuration>,
mode: SendMode,
) -> Self {
let core = Arc::new(ProducerCore {
initialized: AtomicBool::new(false),
client: Arc::new(client),
- can_send: Arc::new(AtomicBool::new(true)),
stream_id: Arc::new(stream),
stream_name,
topic_id: Arc::new(topic),
@@ -856,8 +730,7 @@ impl IggyProducer {
topic_durability,
default_partitioning: Arc::new(Partitioning::balanced()),
last_sent_at: Arc::new(AtomicU64::new(0)),
- send_retries_count,
- send_retries_interval,
+ uncertain_operations: Mutex::default(),
direct_config: match mode {
SendMode::Direct(ref cfg) => Some(cfg.clone()),
_ => None,
@@ -887,12 +760,6 @@ impl IggyProducer {
/// does nothing and returns immediately.
///
/// Initialization ensures that:
- /// - The producer subscribes to client [`DiagnosticEvent`] values and tracks whether sending is
- /// currently allowed. The gate starts open and follows the events observed after this call:
- /// connect, disconnect, sign-out, and shutdown close it, and only a sign-in reopens it. It is
- /// checked only when
- /// [`send_retries()`](crate::clients::producer_builder::IggyProducerBuilder::send_retries)
- /// allows at least one retry.
/// - the stream exists, creating it when `create_stream_if_not_exists` is set (the default).
/// - the topic exists, creating it when `create_topic_if_not_exists` is set (the default), with
/// the partitions count, message expiry and max size passed to
@@ -951,10 +818,10 @@ impl IggyProducer {
/// # Errors
///
/// A `direct` producer wraps a send failure in [`IggyError::ProducerSendFailed`]. The cause can be
- /// [`IggyError::CannotSendMessagesDueToClientDisconnection`] after the readiness retry budget is
- /// exhausted, an encryption or partitioning failure raised before anything left the producer,
- /// a server or transport error after write retries, or an unreadable confirmation for a request
- /// that may already have committed.
+ /// an encryption or partitioning failure before sending, a server rejection,
+ /// or [`IggyError::OperationUncertain`] when a binary chunk may have committed.
+ /// [`IggyError::LaneBlocked`] identifies an earlier retained operation and
+ /// means this call's failed chunk has not been sent.
///
/// A `background` producer only reports what queueing the batch ran into:
/// [`IggyError::ProducerClosed`] after [`shutdown()`](Self::shutdown),
@@ -1083,126 +950,393 @@ impl IggyProducer {
#[cfg(test)]
mod tests {
- use super::stops_send_retries;
+ use super::IggyProducer;
use crate::client_wrappers::client_wrapper::ClientWrapper;
use crate::clients::producer_builder::IggyProducerBuilder;
use crate::clients::producer_config::DirectConfig;
use crate::http::http_client::HttpClient;
+ use crate::links::OPERATION_TIMEOUT;
+ use crate::links::fake_cluster::{Answer, FakeCluster, connected, endpoint, topic_body};
use crate::tcp::tcp_client::TcpClient;
use bytes::Bytes;
- use iggy_binary_protocol::{Command, HEADER_SIZE, Operation, ReplyHeader, RequestHeader};
- use iggy_common::locking::{IggyRwLock, IggyRwLockFn};
- use iggy_common::{
- BinaryTransport, Client, ClientState, HttpClientConfig, Identifier, IggyError, IggyMessage,
- Partitioning, TcpClientConfig, VsrSessionControl,
+ use iggy_binary_protocol::codes::{GET_TOPIC_CODE, SEND_MESSAGES_CODE};
+ use iggy_binary_protocol::requests::messages::SendMessagesHeader;
+ use iggy_binary_protocol::responses::messages::{
+ PartitionRouteResponse, SendMessagesConfirmationResponse,
+ SendMessagesResponse as WireSendMessagesResponse,
};
+ use iggy_binary_protocol::{WireDecode, WireEncode, WirePartitioning};
+ use iggy_common::locking::{IggyRwLock, IggyRwLockFn};
+ use iggy_common::{Client, HttpClientConfig, Identifier, IggyError, IggyMessage, Partitioning};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
+ use tokio::time::Instant;
+
+ async fn connected_producer() -> (Arc<FakeCluster>, IggyProducer) {
+ let cluster = FakeCluster::new(1);
+ *cluster.route.lock().unwrap() = Some(PartitionRouteResponse {
+ incarnation: 7,
+ metadata_op: 11,
+ view: 0,
+ partitions_count: 1,
+ primary_replica: 0,
+ });
+ let client = TcpClient::from_links(connected(&cluster, 1).await);
+ let producer = producer_on(IggyRwLock::new(ClientWrapper::Tcp(client)));
+ (cluster, producer)
+ }
- #[test]
- fn test_unreadable_confirmation_of_a_committed_batch_stops_retrying() {
- assert!(stops_send_retries(&IggyError::InvalidBytesResponse));
- assert!(stops_send_retries(&IggyError::InvalidJsonResponse));
+ fn producer_on(client: IggyRwLock<ClientWrapper>) -> IggyProducer {
+ IggyProducerBuilder::new(
+ client,
+ Identifier::numeric(1).unwrap(),
+ "stream".to_owned(),
+ Identifier::numeric(1).unwrap(),
+ "topic".to_owned(),
+ None,
+ None,
+ )
+ .partitioning(Partitioning::partition_id(0))
+ .direct(DirectConfig::builder().batch_length(1).build())
+ .build()
}
- #[test]
- fn ambiguous_or_terminal_failures_stop_before_minting_another_request() {
- for error in [
- IggyError::Disconnected,
- IggyError::TransientNotCommitted,
- IggyError::HistoryUnavailable,
- IggyError::EmptyResponse,
- IggyError::Unauthenticated,
- IggyError::Unauthorized,
- IggyError::CannotSendMessagesDueToClientDisconnection,
- IggyError::HttpResponseError(500, String::new()),
- IggyError::ResourceNotFound(String::new()),
- ] {
- assert!(
- stops_send_retries(&error),
- "{error} must return the unconfirmed batch without another request"
- );
+ fn message(payload: &'static [u8]) -> IggyMessage {
+ IggyMessage::builder()
+ .payload(Bytes::from_static(payload))
+ .build()
+ .unwrap()
+ }
+
+ fn confirmation(base_offset: u64) -> Answer {
+ confirmation_on(0, base_offset)
+ }
+
+ fn confirmation_on(partition_id: u32, base_offset: u64) -> Answer {
+ let body = WireSendMessagesResponse {
+ confirmations: vec![SendMessagesConfirmationResponse {
+ stream_id: 1,
+ topic_id: 1,
+ partition_id,
+ base_offset,
+ }],
}
- assert!(!stops_send_retries(&IggyError::TransientNotAccepted));
- assert!(!stops_send_retries(&IggyError::NotConnected));
- assert!(!stops_send_retries(&IggyError::CannotEstablishConnection));
+ .to_bytes()
+ .to_vec();
+ Answer::CommitBody(base_offset + 1, body)
}
- #[tokio::test]
- async fn test_aged_out_request_stops_producer_retries_without_minting_another_request() {
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let address = listener.local_addr().unwrap().to_string();
- let peer = tokio::spawn(async move {
- let (mut stream, _) = listener.accept().await.unwrap();
- let mut requests = Vec::new();
- let mut header_bytes = [0u8; HEADER_SIZE];
- while stream.read_exact(&mut header_bytes).await.is_ok() {
- let request =
- bytemuck::checked::try_pod_read_unaligned::<RequestHeader>(&header_bytes)
- .unwrap();
- let mut body = vec![0u8; usize::try_from(request.size).unwrap() - HEADER_SIZE];
- stream.read_exact(&mut body).await.unwrap();
- if request.operation == Operation::NonReplicated {
- assert_eq!(
- u32::from_le_bytes(request.reserved),
- iggy_binary_protocol::codes::GET_PARTITION_ROUTE_CODE
- );
- let response =
- iggy_binary_protocol::responses::messages::PartitionRouteResponse {
- incarnation: 7,
- metadata_op: 11,
- view: 0,
- partitions_count: 1,
- primary_replica: 0,
- };
- let body = iggy_binary_protocol::WireEncode::to_bytes(&response);
- let reply = ReplyHeader {
- command: Command::Reply,
- operation: request.operation,
- client: request.client,
- request: request.request,
- size: u32::try_from(HEADER_SIZE + body.len()).unwrap(),
- ..Default::default()
- };
- stream.write_all(bytemuck::bytes_of(&reply)).await.unwrap();
- stream.write_all(&body).await.unwrap();
- continue;
- }
- assert_eq!(request.operation, Operation::SendMessages);
- assert_eq!(
- (request.partition_incarnation, request.minimum_metadata_op),
- (7, 11)
- );
- requests.push(request.request);
- let reply = ReplyHeader {
- command: Command::Reply,
- operation: request.operation,
- client: request.client,
- request: request.request,
- size: u32::try_from(HEADER_SIZE).unwrap(),
- status: IggyError::RequestTooOld.as_code(),
- ..Default::default()
- };
- stream.write_all(bytemuck::bytes_of(&reply)).await.unwrap();
+ /// Resolves `op` the way an application does, through the producer's client.
+ async fn resolve(producer: &IggyProducer, op: u64) -> Result<(), IggyError> {
+ producer
+ .core
+ .client
+ .read()
+ .await
+ .resolve_operation(op, (Instant::now() + OPERATION_TIMEOUT).into_std())
+ .await
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_missing_chosen_partition_when_sending_should_refresh_and_reselect_once() {
+ for succeeds in [true, false] {
+ let (cluster, producer) = connected_producer().await;
+ cluster
+ .route
+ .lock()
+ .unwrap()
+ .as_mut()
+ .unwrap()
+ .partitions_count = 2;
+ cluster.script(
+ &endpoint(0),
+ GET_TOPIC_CODE,
+ [Answer::Body(topic_body(1)), Answer::Body(topic_body(2))],
+ );
+ let missing = IggyError::PartitionNotFound(
+ 0,
+ Identifier::numeric(1).unwrap(),
+ Identifier::numeric(1).unwrap(),
+ );
+ cluster.script(
+ &endpoint(0),
+ SEND_MESSAGES_CODE,
+ [
+ Answer::Refuse(missing.clone()),
+ if succeeds {
+ confirmation_on(1, 0)
+ } else {
+ Answer::Refuse(missing)
+ },
+ ],
+ );
+
+ let result = producer
+ .send_with_partitioning(
+ vec![message(b"new")],
+ Some(Arc::new(Partitioning::balanced())),
+ )
+ .await;
+
+ assert_eq!(result.is_ok(), succeeds, "{result:?}");
+ if let Err(IggyError::ProducerSendFailed { cause, .. }) = result {
+ assert!(matches!(*cause, IggyError::PartitionNotFound(..)));
}
- requests
- });
- let client = TcpClient::create(Arc::new(TcpClientConfig {
- server_address: address,
- ..Default::default()
- }))
- .unwrap();
- Client::connect(&client).await.unwrap();
- client.bind_vsr_session(1).await.unwrap();
- client.set_state(ClientState::Authenticated).await;
- assert_send_stops_on_request_too_old(ClientWrapper::Tcp(client)).await;
+ assert_eq!(cluster.count(GET_TOPIC_CODE), 2);
+ let sends = cluster.received(SEND_MESSAGES_CODE);
+ assert_eq!(sends.len(), 2);
+ assert_eq!(
+ sent_partition(&sends[0].body),
+ WirePartitioning::PartitionId(0)
+ );
+ assert_eq!(
+ sent_partition(&sends[1].body),
+ WirePartitioning::PartitionId(1)
+ );
+ assert_ne!(sends[0].header.request, sends[1].header.request);
+ }
+ }
+
+ fn sent_partition(body: &[u8]) -> WirePartitioning {
+ let (metadata_length, body) = body.split_first_chunk().unwrap();
+ SendMessagesHeader::decode_from(&body[..u32::from_le_bytes(*metadata_length) as usize])
+ .unwrap()
+ .partitioning
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_balanced_send_blocked_by_its_producer_when_resolving_should_keep_the_chosen_partition()
+ {
+ let (cluster, producer) = connected_producer().await;
+ cluster
+ .route
+ .lock()
+ .unwrap()
+ .as_mut()
+ .unwrap()
+ .partitions_count = 2;
+ cluster.script(
+ &endpoint(0),
+ SEND_MESSAGES_CODE,
+ [
+ Answer::Silence,
+ confirmation(0),
+ confirmation(1),
+ confirmation_on(1, 0),
+ ],
+ );
+ assert!(producer.send(vec![message(b"old")]).await.is_err());
+ cluster.script(&endpoint(0), GET_TOPIC_CODE, [Answer::Body(topic_body(2))]);
+
+ for payload in [b"new".as_slice(), b"next".as_slice()] {
+ producer
+ .send_with_partitioning(
+ vec![message(payload)],
+ Some(Arc::new(Partitioning::balanced())),
+ )
+ .await
+ .unwrap();
+ }
+
+ let sends = cluster.received(SEND_MESSAGES_CODE);
+ let partitions: Vec<_> = sends
+ .iter()
+ .map(|sent| sent_partition(&sent.body))
+ .collect();
assert_eq!(
- peer.await.unwrap().len(),
- 1,
- "unknown outcome must not mint a fresh request"
+ partitions,
+ [
+ WirePartitioning::PartitionId(0),
+ WirePartitioning::PartitionId(0),
+ WirePartitioning::PartitionId(0),
+ WirePartitioning::PartitionId(1)
+ ]
+ );
+ assert_eq!(sends[0].header.request, sends[1].header.request);
+ assert_ne!(sends[1].header.request, sends[2].header.request);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn test_aged_out_request_stops_producer_retries_without_minting_another_request() {
+ let (cluster, producer) = connected_producer().await;
+ cluster.script(
+ &endpoint(0),
+ SEND_MESSAGES_CODE,
+ [Answer::Refuse(IggyError::RequestTooOld)],
+ );
+
+ let Err(IggyError::ProducerSendFailed { cause, failed, .. }) =
+ producer.send(vec![message(b"old")]).await
+ else {
+ panic!("the producer must return the unconfirmed chunk");
+ };
+
+ assert_eq!(*cause, IggyError::RequestTooOld);
+ assert_eq!(failed.len(), 1);
+ assert_eq!(cluster.count(SEND_MESSAGES_CODE), 1);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_partial_send_when_a_new_call_recovers_should_replay_only_the_uncertain_chunk()
+ {
+ let (cluster, producer) = connected_producer().await;
+ cluster.script(
+ &endpoint(0),
+ SEND_MESSAGES_CODE,
+ [
+ confirmation(0),
+ Answer::Silence,
+ confirmation(1),
+ confirmation(2),
+ ],
+ );
+ let Err(IggyError::ProducerSendFailed {
+ cause,
+ failed,
+ committed,
+ ..
+ }) = producer
+ .send(vec![
+ message(b"first"),
+ message(b"uncertain"),
+ message(b"unsent"),
+ ])
+ .await
+ else {
+ panic!("the producer must preserve the failed tail and prior confirmation");
+ };
+ let op = cluster.received(SEND_MESSAGES_CODE)[1].header.request;
+ assert_eq!(*cause, IggyError::OperationUncertain(op));
+ assert_eq!(committed.len(), 1);
+ assert_eq!(committed[0].base_offset, 0);
+ assert_eq!(failed.len(), 2);
+ assert_eq!(failed[0].payload, Bytes::from_static(b"uncertain"));
+ assert_eq!(failed[1].payload, Bytes::from_static(b"unsent"));
+
+ let response = producer.send(vec![message(b"later")]).await.unwrap();
+
+ assert_eq!(resolve(&producer, op).await, Ok(()));
+ let sends = cluster.received(SEND_MESSAGES_CODE);
+ assert_eq!(sends.len(), 4);
+ assert_eq!(sends[1].header.request, sends[2].header.request);
+ assert_eq!(sends[1].body, sends[2].body);
+ assert_ne!(sends[2].header.request, sends[3].header.request);
+ assert_ne!(sends[2].body, sends[3].body);
+ assert_eq!(response.confirmations.len(), 1);
+ assert_eq!(response.confirmations[0].base_offset, 2);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_new_call_and_the_owner_resolving_one_chunk_when_they_race_should_replay_once_and_share_the_outcome()
+ {
+ let (cluster, producer) = connected_producer().await;
+ cluster.script(
+ &endpoint(0),
+ SEND_MESSAGES_CODE,
+ [Answer::Silence, confirmation(0), confirmation(1)],
+ );
+ assert!(producer.send(vec![message(b"old")]).await.is_err());
+ let op = cluster.received(SEND_MESSAGES_CODE)[0].header.request;
+
+ // The new call is polled first, so its replay holds the lane while
+ // the owner's resolve waits for it.
+ let (sent, resolved) =
+ tokio::join!(producer.send(vec![message(b"new")]), resolve(&producer, op));
+
+ sent.unwrap();
+ assert_eq!(resolved, Ok(()));
+ let sends = cluster.received(SEND_MESSAGES_CODE);
+ assert_eq!(sends.len(), 3);
+ assert_eq!(sends[0].header.request, sends[1].header.request);
+ assert_ne!(sends[1].header.request, sends[2].header.request);
+ assert_eq!(resolve(&producer, op).await, Ok(()));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_another_producers_blocker_when_sending_should_return_it_without_resolving() {
+ let (cluster, producer) = connected_producer().await;
+ let other = producer_on((*producer.core.client).clone());
+ cluster.script(&endpoint(0), SEND_MESSAGES_CODE, [Answer::Silence]);
+ assert!(producer.send(vec![message(b"old")]).await.is_err());
+ let op = cluster.received(SEND_MESSAGES_CODE)[0].header.request;
+
+ let Err(IggyError::ProducerSendFailed { cause, .. }) =
+ other.send(vec![message(b"new")]).await
+ else {
+ panic!("another producer's blocker must be returned");
+ };
+
+ assert_eq!(*cause, IggyError::LaneBlocked(op));
+ assert_eq!(cluster.count(SEND_MESSAGES_CODE), 1);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_still_uncertain_owned_chunk_when_sending_again_should_preserve_its_blocker() {
+ let (cluster, producer) = connected_producer().await;
+ cluster.script(
+ &endpoint(0),
+ SEND_MESSAGES_CODE,
+ [Answer::Silence, Answer::Silence],
);
+ assert!(producer.send(vec![message(b"old")]).await.is_err());
+ let op = cluster.received(SEND_MESSAGES_CODE)[0].header.request;
+ let started = Instant::now();
+
+ let Err(IggyError::ProducerSendFailed { cause, .. }) =
+ producer.send(vec![message(b"new")]).await
+ else {
+ panic!("the new chunk must remain unsent");
+ };
+
+ assert_eq!(*cause, IggyError::LaneBlocked(op));
+ assert!(started.elapsed() <= OPERATION_TIMEOUT);
+ let sends = cluster.received(SEND_MESSAGES_CODE);
+ assert_eq!(sends.len(), 2);
+ assert_eq!(sends[0].body, sends[1].body);
+ assert!(producer.core.uncertain_operations().contains(&op));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_no_longer_retained_chunk_when_sending_new_data_should_never_resubmit_the_old_chunk()
+ {
+ for reset_session in [false, true] {
+ let (cluster, producer) = connected_producer().await;
+ cluster.script(
+ &endpoint(0),
+ SEND_MESSAGES_CODE,
+ [Answer::Silence, confirmation(8)],
+ );
+ assert!(producer.send(vec![message(b"old")]).await.is_err());
+ let op = cluster.received(SEND_MESSAGES_CODE)[0].header.request;
+ let client = producer.core.client.read().await;
+ if reset_session {
+ client.disconnect().await.unwrap();
+ client.connect().await.unwrap();
+ } else {
+ client.abandon_operation(op).await.unwrap();
+ }
+ assert_eq!(
+ client
+ .resolve_operation(op, (Instant::now() + OPERATION_TIMEOUT).into_std())
+ .await,
+ Err(IggyError::OperationNotRetained(op))
+ );
+ drop(client);
+
+ producer.send(vec![message(b"new")]).await.unwrap();
+
+ let sends = cluster.received(SEND_MESSAGES_CODE);
+ assert_eq!(sends.len(), 2);
+ assert_ne!(sends[0].header.request, sends[1].header.request);
+ assert_ne!(sends[0].body, sends[1].body);
+ assert_eq!(
+ sends[0].header.session != sends[1].header.session,
+ reset_session
+ );
+ assert!(producer.core.uncertain_operations().is_empty());
+ }
}
#[tokio::test]
@@ -1265,11 +1399,10 @@ mod tests {
assert!(request_lines[0].starts_with(TOPIC_REQUEST_LINE));
}
- /// Sends one message through a producer allowed to retry and asserts the
+ /// Sends one message through a producer and asserts the
/// send fails at once with `RequestTooOld`. Shuts the client down
/// afterwards so a peer serving its binary connection sees it close.
async fn assert_send_stops_on_request_too_old(client: ClientWrapper) {
- const RETRIES: u32 = 2;
const SEND_TIMEOUT: Duration = Duration::from_secs(1);
let producer = IggyProducerBuilder::new(
IggyRwLock::new(client),
@@ -1282,7 +1415,6 @@ mod tests {
)
.partitioning(Partitioning::partition_id(0))
.direct(DirectConfig::builder().build())
- .send_retries(Some(RETRIES), None)
.build();
let message = IggyMessage::builder()
.payload(Bytes::from_static(b"unknown-outcome"))
diff --git a/core/sdk/src/clients/producer_builder.rs b/core/sdk/src/clients/producer_builder.rs
index f8510bd0f..bf0fe8cd3 100644
--- a/core/sdk/src/clients/producer_builder.rs
+++ b/core/sdk/src/clients/producer_builder.rs
@@ -20,8 +20,7 @@ use crate::clients::producer_config::{BackgroundConfig, DirectConfig};
use crate::prelude::IggyProducer;
use iggy_common::locking::IggyRwLock;
use iggy_common::{
- Durability, EncryptorKind, Identifier, IggyExpiry, MaxTopicSize, NonZeroIggyDuration,
- Partitioner, Partitioning,
+ Durability, EncryptorKind, Identifier, IggyExpiry, MaxTopicSize, Partitioner, Partitioning,
};
use std::sync::Arc;
@@ -47,8 +46,6 @@ pub struct IggyProducerBuilder {
create_stream_if_not_exists: bool,
create_topic_if_not_exists: bool,
topic_partitions_count: u32,
- send_retries_count: Option<u32>,
- send_retries_interval: Option<NonZeroIggyDuration>,
topic_message_expiry: IggyExpiry,
topic_max_size: MaxTopicSize,
topic_durability: Durability,
@@ -82,8 +79,6 @@ impl IggyProducerBuilder {
topic_message_expiry: IggyExpiry::ServerDefault,
topic_max_size: MaxTopicSize::ServerDefault,
topic_durability: Durability::default(),
- send_retries_count: Some(3),
- send_retries_interval: Some(NonZeroIggyDuration::ONE_SECOND),
mode: SendMode::default(),
}
}
@@ -196,19 +191,6 @@ impl IggyProducerBuilder {
}
}
- /// Starts a new attempt only after `IggyError::TransientNotAccepted`.
- /// An ambiguous outcome or terminal refusal stops producer retries. The
- /// transport may replay the exact request within its original session.
- /// Defaults to 3 retries with a one-second interval. See the
- /// [retry contract](super::producer::IggyProducer#retrying-and-what-a-failure-means).
- pub fn send_retries(self, retries: Option<u32>, interval: Option<NonZeroIggyDuration>) -> Self {
- Self {
- send_retries_count: retries,
- send_retries_interval: interval,
- ..self
- }
- }
-
/// Sets the producer to use direct message sending.
/// This mode sends from the calling task without buffering between calls.
/// `DirectConfig::linger_time` can delay a call before its requests are sent.
@@ -240,8 +222,6 @@ impl IggyProducerBuilder {
self.topic_message_expiry,
self.topic_max_size,
self.topic_durability,
- self.send_retries_count,
- self.send_retries_interval,
self.mode,
)
}
diff --git a/core/sdk/src/clients/producer_config.rs b/core/sdk/src/clients/producer_config.rs
index 6da8553c2..bd7e32f08 100644
--- a/core/sdk/src/clients/producer_config.rs
+++ b/core/sdk/src/clients/producer_config.rs
@@ -249,7 +249,7 @@ pub struct DirectConfig {
/// A send carrying more than this is split into consecutive requests of this size, each awaited
/// before the next one starts. A batch of 2500 therefore becomes three requests at the default.
///
- /// `0` limits to 1,000,000 messages per request.
+ /// `0` limits to [`MAX_BATCH_LENGTH`](crate::clients::MAX_BATCH_LENGTH) messages per request.
#[builder(default = 1000)]
pub batch_length: u32,
/// Requested minimum gap between sequential direct sends.
diff --git a/core/sdk/src/clients/producer_error_callback.rs b/core/sdk/src/clients/producer_error_callback.rs
index 0c3a4758b..245e82117 100644
--- a/core/sdk/src/clients/producer_error_callback.rs
+++ b/core/sdk/src/clients/producer_error_callback.rs
@@ -41,6 +41,11 @@ use tracing::error;
/// Encryption mutates messages before the write, so this tail contains encrypted messages when the
/// producer uses an encryptor. Passing them back through the same producer would encrypt them again.
///
+/// When the cause is [`IggyError::OperationUncertain`], `messages` were one request that may have
+/// committed. [`Client::resolve_operation`] on the producer's client returns its proved outcome,
+/// also after the worker's next batch resolved it first, because the client keeps proved outcomes.
+/// `Ok(())` means that every message of `messages` committed, so none of them needs a resend.
+///
/// [`stream`](Self::stream) and [`topic`](Self::topic) identify the destination.
/// [`partitioning`](Self::partitioning) contains only the per-send override passed to the dispatcher.
/// `None` means the producer's configured or default partitioning was used, not that the request had
@@ -51,6 +56,7 @@ use tracing::error;
/// [`background()`]: crate::clients::producer_builder::IggyProducerBuilder::background
/// [`send()`]: crate::clients::producer::IggyProducer::send
/// [`BackgroundConfig::error_callback`]: crate::clients::producer_config::BackgroundConfig::error_callback
+/// [`Client::resolve_operation`]: iggy_common::Client::resolve_operation
/// [`Shard`]: crate::clients::producer_sharding::Shard
#[derive(Debug)]
pub struct ErrorCtx {
diff --git a/core/sdk/src/driver.rs b/core/sdk/src/driver.rs
index e58c21c7b..cb8a7a39c 100644
--- a/core/sdk/src/driver.rs
+++ b/core/sdk/src/driver.rs
@@ -20,38 +20,41 @@
//! A frame that can have taken effect is never frozen again, so a retry never
//! applies a request twice.
-// Unused until the clients send through the driver.
-#![allow(dead_code)]
-
-use crate::links::{
- Frame, Link, OPERATION_TIMEOUT, ReplicaLinks, Target, lost_link, pause_before_retry, read_reply,
-};
+use crate::links::{Frame, Link, ReplicaLinks, Target, lost_link, pause_before_retry, read_reply};
use crate::session_owner::{LaneKey, LaneTicket, RetainedOperation, SessionOwner};
+use crate::vsr::decode_reply_for;
use bytes::Bytes;
use iggy_binary_protocol::codes::{
- BIND_SESSION_CODE, GET_PARTITION_ROUTE_CODE, LOGIN_REGISTER_CODE, LOGIN_REGISTER_WITH_PAT_CODE,
- SEND_MESSAGES_CODE,
+ BIND_SESSION_CODE, CHANGE_PASSWORD_CODE, DELETE_CONSUMER_OFFSET_CODE, GET_CONSUMER_OFFSET_CODE,
+ GET_PARTITION_ROUTE_CODE, LOGIN_REGISTER_CODE, LOGIN_REGISTER_WITH_PAT_CODE,
+ POLL_MESSAGES_CODE, SEND_MESSAGES_CODE, STORE_CONSUMER_OFFSET_CODE, UPDATE_USER_CODE,
};
use iggy_binary_protocol::consensus::{Operation, operation_for_code};
use iggy_binary_protocol::primitives::partition_history::PartitionContext;
-use iggy_binary_protocol::requests::messages::GetPartitionRouteRequest;
+use iggy_binary_protocol::requests::consumer_offsets::{
+ DeleteConsumerOffsetRequest, GetConsumerOffsetRequest, StoreConsumerOffsetRequest,
+};
+use iggy_binary_protocol::requests::messages::{
+ GetPartitionRouteRequest, PollMessagesRequest, SendMessagesHeader,
+};
+use iggy_binary_protocol::requests::users::{ChangePasswordRequest, UpdateUserRequest};
use iggy_binary_protocol::responses::messages::PartitionRouteResponse;
use iggy_binary_protocol::responses::users::LoginRegisterResponse;
-use iggy_binary_protocol::{WireDecode, WireEncode};
-use iggy_common::{ClientState, Identifier, IggyError};
+use iggy_binary_protocol::{WireDecode, WireEncode, WirePartitioning, WirePollingStrategy};
+use iggy_common::{ClientState, Credentials, Identifier, IggyError};
use route_cache::RouteCache;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use tokio::time::{Instant, timeout_at};
use tracing::debug;
-mod poll_router;
mod route_cache;
-pub(crate) use poll_router::{
- PollRouter, PollTransport, ROSTER_READ_TIMEOUT, is_poll_routing_code,
-};
pub(crate) use route_cache::PartitionKey;
+pub(crate) use iggy_common::{
+ binary_operation_deadline as operation_deadline, with_binary_deadline as with_deadline,
+};
+
/// Where a binary client sends one request.
#[derive(Debug, Clone, Copy)]
pub(crate) enum RequestTarget<'a> {
@@ -70,6 +73,7 @@ pub(crate) struct PartitionTarget<'a> {
}
/// Sends the requests of one client over its replica links.
+#[derive(Debug)]
pub(crate) struct OperationDriver {
session: Arc<SessionOwner>,
links: ReplicaLinks,
@@ -86,6 +90,136 @@ impl OperationDriver {
}
}
+ pub(crate) fn links(&self) -> &ReplicaLinks {
+ &self.links
+ }
+
+ pub(crate) fn session(&self) -> &Arc<SessionOwner> {
+ &self.session
+ }
+
+ pub(crate) fn partition_count(
+ &self,
+ stream_id: &Identifier,
+ topic_id: &Identifier,
+ ) -> Option<u32> {
+ self.routes().partition_count(
+ stream_id,
+ topic_id,
+ self.session.fence(),
+ self.session.metadata_watermark(),
+ )
+ }
+
+ pub(crate) async fn remember(&self, credentials: Credentials, user_id: u32) {
+ if self
+ .session
+ .remember_unless(|| self.stopped().is_some(), credentials, user_id)
+ && let Ok(link) = self.links.link(Target::MetadataPrimary)
+ && let Err(error) = self.links.refresh_roster(&link).await
+ {
+ debug!("Failed to refresh replicas after sign-in: {error}");
+ }
+ }
+
+ pub(crate) async fn poll(
+ &self,
+ request: &PollMessagesRequest,
+ context: Option<PartitionContext>,
+ ) -> Result<Bytes, IggyError> {
+ let stream_id = Identifier::try_from(&request.stream_id)?;
+ let topic_id = Identifier::try_from(&request.topic_id)?;
+ let partition_id = match request.partition_id {
+ Some(partition) => partition,
+ None if request.consumer.kind
+ == iggy_binary_protocol::primitives::consumer::KIND_CONSUMER =>
+ {
+ 0
+ }
+ None => return Err(IggyError::InvalidIdentifier),
+ };
+ self.send(
+ POLL_MESSAGES_CODE,
+ request.to_bytes(),
+ RequestTarget::Partition(PartitionTarget {
+ stream_id: &stream_id,
+ topic_id: &topic_id,
+ partition_id,
+ context,
+ }),
+ )
+ .await
+ }
+
+ pub(crate) async fn send_raw(
+ &self,
+ code: u32,
+ payload: Bytes,
+ context: Option<PartitionContext>,
+ ) -> Result<Bytes, IggyError> {
+ let (stream, topic, partition_id) = match code {
+ SEND_MESSAGES_CODE => {
+ let (metadata_length, body) = payload
+ .split_first_chunk()
+ .ok_or(IggyError::InvalidCommand)?;
+ let request = body
+ .get(..u32::from_le_bytes(*metadata_length) as usize)
+ .and_then(|metadata| SendMessagesHeader::decode_from(metadata).ok())
+ .ok_or(IggyError::InvalidCommand)?;
+ let WirePartitioning::PartitionId(partition_id) = request.partitioning else {
+ return Err(IggyError::FeatureUnavailable);
+ };
+ (request.stream_id, request.topic_id, partition_id)
+ }
+ POLL_MESSAGES_CODE => {
+ let request = PollMessagesRequest::decode_from(&payload)
+ .map_err(|_| IggyError::InvalidCommand)?;
+ return self.poll(&request, context).await;
+ }
+ GET_CONSUMER_OFFSET_CODE => {
+ let request = GetConsumerOffsetRequest::decode_from(&payload)
+ .map_err(|_| IggyError::InvalidCommand)?;
+ (
+ request.stream_id,
+ request.topic_id,
+ request.partition_id.unwrap_or(0),
+ )
+ }
+ STORE_CONSUMER_OFFSET_CODE => {
+ let request = StoreConsumerOffsetRequest::decode_from(&payload)
+ .map_err(|_| IggyError::InvalidCommand)?;
+ (
+ request.stream_id,
+ request.topic_id,
+ request.partition_id.ok_or(IggyError::InvalidIdentifier)?,
+ )
+ }
+ DELETE_CONSUMER_OFFSET_CODE => {
+ let request = DeleteConsumerOffsetRequest::decode_from(&payload)
+ .map_err(|_| IggyError::InvalidCommand)?;
+ (
+ request.stream_id,
+ request.topic_id,
+ request.partition_id.ok_or(IggyError::InvalidIdentifier)?,
+ )
+ }
+ _ => return self.send(code, payload, RequestTarget::Metadata).await,
+ };
+ let stream_id = Identifier::try_from(&stream)?;
+ let topic_id = Identifier::try_from(&topic)?;
+ self.send(
+ code,
+ payload,
+ RequestTarget::Partition(PartitionTarget {
+ stream_id: &stream_id,
+ topic_id: &topic_id,
+ partition_id,
+ context,
+ }),
+ )
+ .await
+ }
+
/// Sends one request and returns the body of its reply.
pub(crate) async fn send(
&self,
@@ -93,14 +227,18 @@ impl OperationDriver {
payload: Bytes,
target: RequestTarget<'_>,
) -> Result<Bytes, IggyError> {
- let deadline = Instant::now() + OPERATION_TIMEOUT;
+ let deadline = operation_deadline();
self.drive(Call::new(code, payload, target, deadline)).await
}
/// Replays the retained operation `op` until it has an outcome or
- /// `deadline` passes. Its success frees the lane.
+ /// `deadline` passes. A proved outcome frees the lane. An operation that
+ /// is no longer retained returns the outcome that a replay proved for it.
pub(crate) async fn resolve(&self, op: u64, deadline: Instant) -> Result<(), IggyError> {
- let (ticket, retained) = self.session.resume(op, deadline).await?;
+ let (ticket, retained) = match self.session.resume(op, deadline).await {
+ Err(IggyError::OperationNotRetained(_)) => return self.session.proved_outcome(op),
+ resumed => resumed?,
+ };
self.drive(Call::resumed(ticket, retained, deadline))
.await
.map(|_| ())
@@ -116,7 +254,8 @@ impl OperationDriver {
loop {
let next = match self.attempt(&mut call).await {
Ok(body) => {
- call.complete();
+ self.refresh_sign_in(&call);
+ call.complete(Ok(()));
return Ok(body);
}
Err(next) => next,
@@ -131,7 +270,42 @@ impl OperationDriver {
}
}
Next::Fail(error) => return Err(call.end(error)),
+ Next::Committed(error) => {
+ call.complete(Err(error.clone()));
+ return Err(error);
+ }
+ }
+ }
+ }
+
+ /// Applies a committed password change or rename to the stored sign-in,
+ /// so a later sign-in does not replay the old credentials. Typed, raw and
+ /// resolved calls all succeed here, and only the request carries the new
+ /// credentials.
+ fn refresh_sign_in(&self, call: &Call) {
+ let Some(frame) = &call.frame else {
+ return;
+ };
+ match call.code {
+ CHANGE_PASSWORD_CODE => {
+ if let Ok(request) = ChangePasswordRequest::decode_from(&frame.body)
+ && let Ok(user) = Identifier::try_from(&request.user_id)
+ {
+ self.session.refresh_password(&user, &request.new_password);
+ }
+ }
+ UPDATE_USER_CODE => {
+ if let Ok(UpdateUserRequest {
+ user_id,
+ username: Some(username),
+ ..
+ }) = UpdateUserRequest::decode_from(&frame.body)
+ && let Ok(user) = Identifier::try_from(&user_id)
+ {
+ self.session.refresh_username(&user, username.as_str());
+ }
}
+ _ => {}
}
}
@@ -155,7 +329,15 @@ impl OperationDriver {
let context = self.context(call, route.as_ref());
// The lane comes first, so a blocked lane ends the call at once, also
// while no link is ready.
- let ticket = self.ticket(call, &context).await?;
+ let mut ticket = self.ticket(call, &context).await?;
+ let body_len = call
+ .frame
+ .as_ref()
+ .map_or(call.payload.len(), |frame| frame.body.len());
+ ticket
+ .reserve(call.code, body_len, call.deadline)
+ .await
+ .map_err(Next::Fail)?;
let hop = match self.hop(call, route).await {
Ok(hop) => hop,
Err(next) => {
@@ -165,13 +347,53 @@ impl OperationDriver {
};
let deadline = call.deadline;
let (frame, ticket) = call.frame(ticket, context)?;
+ let request = frame.header;
let result = hop.link.send(frame, deadline, ticket.sent_flag()).await;
let sent = *ticket.sent_flag();
- let result = result.and_then(|reply| read_reply(&self.session, reply));
+ let result = match result {
+ Ok(reply) => match decode_reply_for(&request, &reply.header, reply.body) {
+ Ok(outcome) => {
+ self.session.observe_metadata_reply(&reply.header);
+ close_if_detached(&hop.link, &outcome.result);
+ if outcome.committed && call.uncertain {
+ return match outcome.result {
+ Ok(body) => self.signed_in(call, &hop, body),
+ Err(error) => Err(Next::Committed(error)),
+ };
+ }
+ if call.uncertain
+ && !matches!(
+ request.operation,
+ Operation::NonReplicated | Operation::Register | Operation::Logout
+ )
+ && outcome.result.is_ok()
+ {
+ Err(IggyError::TransientNotCommitted)
+ } else {
+ outcome.result
+ }
+ }
+ Err(_) => {
+ hop.link.close();
+ Err(IggyError::Disconnected)
+ }
+ },
+ // An eviction closes the link for every request on it, so it does
+ // not tell whether the server admitted this one. A call that takes
+ // no lane, such as a read or a sign-in, ends with the eviction.
+ Err(error) => {
+ call.uncertain |= sent
+ && !lost_link(&error)
+ && (call.progress_poll
+ || LaneKey::of(call.code, &context, call.partition_id()).is_some());
+ Err(error)
+ }
+ };
self.settle(call, &hop, result, sent).await
}
- /// The error of a call on a client that nothing brings back.
+ /// The error of a call on a client without a link or a retrying slot.
+ /// Only a keepalive or a connect brings it back, so the call fails now.
fn stopped(&self) -> Option<IggyError> {
match self.links.state() {
ClientState::Shutdown => Some(IggyError::ClientShutdown),
@@ -241,7 +463,18 @@ impl OperationDriver {
match call.ticket.take() {
Some(ticket) => Ok(ticket),
None => {
- let key = LaneKey::of(call.code, context, call.partition_id());
+ let key = if call.code == POLL_MESSAGES_CODE {
+ let poll = PollMessagesRequest::decode_from(&call.payload)
+ .map_err(|_| Next::Fail(IggyError::InvalidCommand))?;
+ call.progress_poll =
+ poll.auto_commit || poll.strategy.kind == WirePollingStrategy::next().kind;
+ call.progress_poll.then_some(LaneKey::Partition {
+ incarnation: context.incarnation,
+ partition_id: call.partition_id(),
+ })
+ } else {
+ LaneKey::of(call.code, context, call.partition_id())
+ };
self.session
.enter_lane(key, call.deadline)
.await
@@ -288,6 +521,12 @@ impl OperationDriver {
Ok(body) => return self.signed_in(call, hop, body),
Err(error) => error,
};
+ if call.progress_poll
+ && (error == IggyError::TransientNotCommitted || (sent && lost_link(&error)))
+ {
+ call.uncertain = true;
+ return Err(Next::Fail(IggyError::TransientNotCommitted));
+ }
let repeated = std::mem::replace(
&mut call.not_primary,
matches!(error, IggyError::NotPrimary),
@@ -410,7 +649,8 @@ impl OperationDriver {
) -> Result<PartitionRouteResponse, IggyError> {
let body = GetPartitionRouteRequest::try_from(key)?.to_bytes();
let hinted = self.routes().ask_first(key);
- let first = hinted.or_else(|| self.links.metadata_primary());
+ let metadata_primary = self.links.metadata_primary();
+ let first = hinted.or(metadata_primary);
let mut replicas = self.links.ready_replicas();
let start = first.map_or(0, |first| replicas.partition_point(|id| *id < first));
replicas.rotate_left(start);
@@ -435,6 +675,17 @@ impl OperationDriver {
}
}
Err(error) if retries_lookup(&error) => refusal = error,
+ Err(
+ IggyError::StreamIdNotFound(_)
+ | IggyError::StreamNameNotFound(_)
+ | IggyError::TopicIdNotFound(_, _)
+ | IggyError::TopicNameNotFound(_, _)
+ | IggyError::PartitionNotFound(_, _, _),
+ ) if Some(replica) != metadata_primary => {
+ // A backup can miss metadata that another client just created.
+ // Only the metadata primary can make this miss terminal.
+ refusal = IggyError::TransientNotAccepted;
+ }
Err(error) => return Err(error),
}
}
@@ -452,7 +703,9 @@ impl OperationDriver {
let mut ticket = self.session.enter_lane(None, deadline).await?;
let frame = ticket.freeze(code, body, self.read_context(), None)?;
let reply = link.send(frame, deadline, ticket.sent_flag()).await?;
- read_reply(&self.session, reply)
+ let result = read_reply(&self.session, reply);
+ close_if_detached(link, &result);
+ result
}
/// Reads the roster on a ready link other than the metadata primary,
@@ -491,6 +744,8 @@ struct Call {
deadline: Instant,
ticket: Option<LaneTicket>,
frame: Option<Frame>,
+ /// Replaying a progress poll can advance its offset again without delivering the first result.
+ progress_poll: bool,
/// An attempt of the frame can have taken effect, so the call never
/// freezes again.
uncertain: bool,
@@ -522,6 +777,7 @@ enum Next {
Again,
Pause,
Fail(IggyError),
+ Committed(IggyError),
}
/// How an attempt failed before a definitive outcome.
@@ -547,6 +803,7 @@ impl Call {
deadline,
ticket: None,
frame: None,
+ progress_poll: false,
uncertain: false,
refusal: IggyError::TransientNotAccepted,
retries: 0,
@@ -561,6 +818,7 @@ impl Call {
code,
frame,
partition,
+ ..
} = retained;
Self {
partition: partition.map(|key| PartitionCall { key, context: None }),
@@ -648,9 +906,10 @@ impl Call {
pause_before_retry(retry, self.deadline, rand::random()).await
}
- fn complete(&mut self) {
+ /// Ends the call with the outcome that it proved.
+ fn complete(&mut self, outcome: Result<(), IggyError>) {
if let Some(ticket) = self.ticket.take() {
- ticket.complete();
+ ticket.prove(outcome);
}
}
@@ -687,18 +946,43 @@ fn retries_lookup(error: &IggyError) -> bool {
) || lost_link(error)
}
+/// A reply with `StaleClient` means that the server no longer attaches
+/// `link` to the session, for example because the session ended. The slot
+/// of a closed link binds the session again, as after an eviction. That
+/// bind resumes a session that the server still knows, and drops an ended
+/// one, so the slot signs in again.
+fn close_if_detached(link: &Link, result: &Result<Bytes, IggyError>) {
+ if matches!(result, Err(IggyError::StaleClient)) {
+ link.close();
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ use crate::links::OPERATION_TIMEOUT;
use crate::links::RETRY_BACKOFF_MAX;
use crate::links::fake_cluster::{
- Answer, FakeCluster, Received, UNANSWERED_CODE, connected, endpoint, eventually,
+ Answer, FIRST_SESSION, FakeCluster, Received, TEST_BUDGET, UNANSWERED_CODE, connected,
+ endpoint, eventually, policy, topic_body,
};
+ use crate::tcp::tcp_client::TcpClient;
+ use bytes::BytesMut;
use iggy_binary_protocol::codes::{
- CREATE_STREAM_CODE, GET_CLUSTER_METADATA_CODE, GET_STREAMS_CODE, POLL_MESSAGES_CODE,
+ CREATE_STREAM_CODE, GET_CLUSTER_METADATA_CODE, GET_STREAMS_CODE, GET_TOPIC_CODE,
STORE_CONSUMER_OFFSET_CODE,
};
+ use iggy_binary_protocol::consensus::EvictionReason;
+ use iggy_binary_protocol::requests::messages::{RawMessage, SendMessagesEncoder};
+ use iggy_binary_protocol::{WireConsumer, WireIdentifier};
+ use iggy_common::{
+ AutoLogin, Credentials, DiagnosticEvent, IggyMessage, MessageClient, Partitioning,
+ PendingOperationsConfig,
+ };
+ use secrecy::SecretString;
use std::iter::repeat_n;
+ use std::num::NonZeroUsize;
+ use std::str::FromStr;
use std::time::Duration;
use tokio::time::{sleep, timeout};
@@ -763,9 +1047,24 @@ mod tests {
}
async fn call(&self, code: u32, target: RequestTarget<'_>) -> Result<Bytes, IggyError> {
- self.driver
- .send(code, Bytes::from_static(PAYLOAD), target)
- .await
+ let payload = if code == POLL_MESSAGES_CODE {
+ self.poll(false, WirePollingStrategy::first()).to_bytes()
+ } else {
+ Bytes::from_static(PAYLOAD)
+ };
+ self.driver.send(code, payload, target).await
+ }
+
+ fn poll(&self, auto_commit: bool, strategy: WirePollingStrategy) -> PollMessagesRequest {
+ PollMessagesRequest {
+ consumer: WireConsumer::consumer(WireIdentifier::numeric(1)),
+ stream_id: WireIdentifier::numeric(1),
+ topic_id: WireIdentifier::numeric(2),
+ partition_id: Some(PARTITION_ID),
+ strategy,
+ count: 1,
+ auto_commit,
+ }
}
async fn send_messages(&self) -> Result<Bytes, IggyError> {
@@ -793,6 +1092,204 @@ mod tests {
assert_eq!(result.unwrap_err(), IggyError::OperationUncertain(op));
op
}
+
+ /// A call of `code` to the target of its kind. A poll moves the
+ /// consumer offset.
+ async fn call_to(&self, code: u32) -> Result<Bytes, IggyError> {
+ match code {
+ SEND_MESSAGES_CODE => self.send_messages().await,
+ POLL_MESSAGES_CODE => {
+ let poll = self.poll(true, WirePollingStrategy::first());
+ self.driver
+ .send(code, poll.to_bytes(), self.partition(None))
+ .await
+ }
+ _ => self.call(code, RequestTarget::Metadata).await,
+ }
+ }
+
+ /// Waits until the client dropped the session of `fence` and every
+ /// slot serves the next one.
+ async fn next_session(&self, fence: u64) {
+ eventually("every slot serves a new session", || {
+ self.driver.session.fence() > fence
+ && self.driver.links.ready_replicas().len() == usize::from(REPLICAS)
+ })
+ .await;
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_raw_send_metadata_when_validating_should_reject_malformed_and_unresolved_before_wire()
+ {
+ let f = Fixture::new().await;
+ for partitioning in [
+ WirePartitioning::Balanced,
+ WirePartitioning::MessagesKey(b"key".to_vec()),
+ ] {
+ let payload = encoded_send(&partitioning);
+ assert_eq!(
+ f.driver.send_raw(SEND_MESSAGES_CODE, payload, None).await,
+ Err(IggyError::FeatureUnavailable)
+ );
+ }
+ let mut invalid = encoded_send(&WirePartitioning::PartitionId(PARTITION_ID)).to_vec();
+ invalid[..size_of::<u32>()].copy_from_slice(&u32::MAX.to_le_bytes());
+ for payload in [Bytes::new(), Bytes::from(invalid)] {
+ assert_eq!(
+ f.driver.send_raw(SEND_MESSAGES_CODE, payload, None).await,
+ Err(IggyError::InvalidCommand)
+ );
+ }
+ assert!(f.sends().is_empty());
+ assert_eq!(f.cluster.count(GET_PARTITION_ROUTE_CODE), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_raw_send_with_length_prefixed_metadata_when_sent_should_route_the_unchanged_frame()
+ {
+ let f = Fixture::new().await;
+ let payload = encoded_send(&WirePartitioning::PartitionId(PARTITION_ID));
+ f.driver
+ .send_raw(SEND_MESSAGES_CODE, payload.clone(), None)
+ .await
+ .unwrap();
+ let sends = f.sends();
+ assert_eq!(sends.len(), 1);
+ assert_eq!(sends[0].endpoint, endpoint(PRIMARY));
+ assert_eq!(sends[0].body, payload);
+ assert_eq!(sends[0].header.partition_incarnation, ROUTE.incarnation);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_balanced_send_when_partition_disappears_should_refresh_count_and_reselect_only_once()
+ {
+ for rejected_again in [false, true] {
+ let f = Fixture::new().await;
+ *f.cluster.route.lock().unwrap() = Some(PartitionRouteResponse {
+ partitions_count: 2,
+ ..ROUTE
+ });
+ f.cluster.script(
+ &endpoint(0),
+ GET_TOPIC_CODE,
+ [Answer::Body(topic_body(2)), Answer::Body(topic_body(1))],
+ );
+ let missing = IggyError::PartitionNotFound(1, f.topic_id.clone(), f.stream_id.clone());
+ let final_answer = if rejected_again {
+ Answer::Refuse(missing.clone())
+ } else {
+ Answer::Commit(COMMIT)
+ };
+ f.script_sends([
+ Answer::Commit(COMMIT),
+ Answer::Refuse(missing.clone()),
+ final_answer,
+ ]);
+ let client = TcpClient::from_links(f.driver.links);
+ let mut messages = [IggyMessage::from_str("payload").unwrap()];
+ client
+ .send_messages(
+ &f.stream_id,
+ &f.topic_id,
+ &Partitioning::balanced(),
+ &mut messages,
+ )
+ .await
+ .unwrap();
+ let result = client
+ .send_messages(
+ &f.stream_id,
+ &f.topic_id,
+ &Partitioning::balanced(),
+ &mut messages,
+ )
+ .await;
+ if rejected_again {
+ assert_eq!(result.unwrap_err(), missing);
+ } else {
+ result.unwrap();
+ }
+ let sent = f.cluster.received(SEND_MESSAGES_CODE);
+ assert_eq!(
+ sent.iter().map(sent_partition).collect::<Vec<_>>(),
+ [0, 1, 0]
+ );
+ assert_ne!(sent[1].header.request, sent[2].header.request);
+ assert_eq!(f.cluster.count(GET_TOPIC_CODE), 2);
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_explicit_or_uncertain_send_when_partition_is_missing_should_never_choose_another()
+ {
+ for uncertain in [false, true] {
+ let f = Fixture::new().await;
+ f.cluster
+ .script(&endpoint(0), GET_TOPIC_CODE, [Answer::Body(topic_body(2))]);
+ let missing = IggyError::PartitionNotFound(1, f.topic_id.clone(), f.stream_id.clone());
+ let mut answers = Vec::new();
+ if uncertain {
+ answers.push(Answer::Refuse(IggyError::TransientNotCommitted));
+ }
+ answers.push(Answer::Refuse(missing.clone()));
+ f.script_sends(answers);
+ let client = TcpClient::from_links(f.driver.links);
+ let partitioning = if uncertain {
+ Partitioning::balanced()
+ } else {
+ Partitioning::partition_id(PARTITION_ID)
+ };
+ let mut messages = [IggyMessage::from_str("payload").unwrap()];
+ let result = client
+ .send_messages(&f.stream_id, &f.topic_id, &partitioning, &mut messages)
+ .await;
+ let sent = f.cluster.received(SEND_MESSAGES_CODE);
+ if uncertain {
+ assert_eq!(
+ result.unwrap_err(),
+ IggyError::OperationUncertain(sent[0].header.request)
+ );
+ assert_eq!(sent.len(), 2);
+ assert_eq!(
+ bytemuck::bytes_of(&sent[0].header),
+ bytemuck::bytes_of(&sent[1].header)
+ );
+ assert_eq!(f.cluster.count(GET_TOPIC_CODE), 1);
+ } else {
+ assert_eq!(result.unwrap_err(), missing);
+ assert_eq!(sent.len(), 1);
+ assert_eq!(f.cluster.count(GET_TOPIC_CODE), 0);
+ }
+ }
+ }
+
+ fn sent_partition(sent: &Received) -> u32 {
+ let (length, body) = sent.body.split_first_chunk().unwrap();
+ let header =
+ SendMessagesHeader::decode_from(&body[..u32::from_le_bytes(*length) as usize]).unwrap();
+ let WirePartitioning::PartitionId(partition) = header.partitioning else {
+ panic!("wire send must name a partition");
+ };
+ partition
+ }
+
+ fn encoded_send(partitioning: &WirePartitioning) -> Bytes {
+ let mut payload = BytesMut::new();
+ SendMessagesEncoder::encode(
+ &mut payload,
+ &WireIdentifier::numeric(1),
+ &WireIdentifier::numeric(2),
+ partitioning,
+ &[RawMessage {
+ id: 1,
+ origin_timestamp: 0,
+ headers: None,
+ payload: PAYLOAD,
+ }],
+ )
+ .unwrap();
+ payload.freeze()
}
fn route_body(route: PartitionRouteResponse) -> Answer {
@@ -986,6 +1483,46 @@ mod tests {
assert_eq!(stamped_context(&sends[1]), stamped_context(&sends[0]));
}
+ #[tokio::test(start_paused = true)]
+ async fn given_a_committed_lifecycle_refusal_when_retrying_should_restart_only_before_uncertainty()
+ {
+ for uncertain in [false, true] {
+ let fixture = Fixture::new().await;
+ let mut answers = Vec::new();
+ if uncertain {
+ answers.push(Answer::Refuse(IggyError::TransientNotCommitted));
+ }
+ answers.push(Answer::CommitRejected(COMMIT, IggyError::LifecycleBusy));
+ answers.push(Answer::Commit(COMMIT + 1));
+ fixture
+ .cluster
+ .script(&endpoint(0), CREATE_STREAM_CODE, answers);
+
+ let result = fixture
+ .call(CREATE_STREAM_CODE, RequestTarget::Metadata)
+ .await;
+
+ if uncertain {
+ assert_eq!(result, Err(IggyError::LifecycleBusy));
+ } else {
+ result.unwrap();
+ }
+ let requests = fixture.cluster.received(CREATE_STREAM_CODE);
+ assert_eq!(requests.len(), 2);
+ assert_eq!(
+ requests[0].header.request == requests[1].header.request,
+ uncertain
+ );
+ assert_eq!(requests[0].body, requests[1].body);
+ fixture
+ .call(CREATE_STREAM_CODE, RequestTarget::Metadata)
+ .await
+ .unwrap();
+ let next = fixture.cluster.received(CREATE_STREAM_CODE);
+ assert_ne!(next[2].header.request, requests[1].header.request);
+ }
+ }
+
#[tokio::test(start_paused = true)]
async fn given_87_on_a_send_when_refreshed_should_start_one_new_operation_under_the_new_incarnation()
{
@@ -1085,11 +1622,231 @@ mod tests {
assert_eq!(ops(&sends[..3]), [op; 3]);
assert_eq!(sends[2].body, PAYLOAD);
assert_ne!(sends[3].header.request, op);
- let again = f
+ let deadline = Instant::now() + OPERATION_TIMEOUT;
+ assert_eq!(f.driver.resolve(op, deadline).await, Ok(()));
+ let never_uncertain = sends[3].header.request;
+ assert_eq!(
+ f.driver.resolve(never_uncertain, deadline).await,
+ Err(IggyError::OperationNotRetained(never_uncertain))
+ );
+ assert_eq!(f.sends().len(), 4);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_full_mutation_budget_when_resolving_should_reuse_the_retained_reservation() {
+ let mut fixture = Fixture::new().await;
+ let session = Arc::new(SessionOwner::with_pending_operations(
+ AutoLogin::Enabled(Credentials::UsernamePassword(
+ "iggy".to_owned(),
+ SecretString::from("iggy"),
+ )),
+ PendingOperationsConfig {
+ max_operations: NonZeroUsize::MIN,
+ max_bytes: NonZeroUsize::new(iggy_binary_protocol::HEADER_SIZE + PAYLOAD.len())
+ .unwrap(),
+ },
+ ));
+ fixture.driver = OperationDriver::new(ReplicaLinks::new(
+ fixture.cluster.dialer(),
+ endpoint(0),
+ policy(),
+ session,
+ ));
+ fixture.driver.links.connect().await.unwrap();
+ let operation = fixture.uncertain_send().await;
+
+ fixture
.driver
- .resolve(op, Instant::now() + OPERATION_TIMEOUT)
+ .resolve(operation, Instant::now() + OPERATION_TIMEOUT)
+ .await
+ .unwrap();
+ fixture.send_messages().await.unwrap();
+
+ let sends = fixture.sends();
+ assert_eq!(ops(&sends[..3]), [operation; 3]);
+ assert_eq!(sends[2].body, PAYLOAD);
+ assert_ne!(sends[3].header.request, operation);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_an_uncertain_store_when_a_committed_rejection_replays_should_return_it_and_free_the_lane()
+ {
+ let f = Fixture::new().await;
+ f.cluster.script(
+ &endpoint(PRIMARY),
+ STORE_CONSUMER_OFFSET_CODE,
+ [
+ Answer::Refuse(IggyError::TransientNotCommitted),
+ Answer::Refuse(IggyError::RequestTooOld),
+ Answer::CommitRejected(COMMIT, IggyError::InvalidOffset(0)),
+ ],
+ );
+ let failed = f.call(STORE_CONSUMER_OFFSET_CODE, f.partition(None)).await;
+ let op = f.cluster.received(STORE_CONSUMER_OFFSET_CODE)[0]
+ .header
+ .request;
+ assert_eq!(failed, Err(IggyError::OperationUncertain(op)));
+
+ for _ in 0..2 {
+ let resolved = f
+ .driver
+ .resolve(op, Instant::now() + OPERATION_TIMEOUT)
+ .await;
+ assert_eq!(resolved, Err(IggyError::InvalidOffset(0)));
+ }
+
+ assert_eq!(
+ f.driver.abandon(op),
+ Err(IggyError::OperationNotRetained(op))
+ );
+ f.call(STORE_CONSUMER_OFFSET_CODE, f.partition(None))
+ .await
+ .unwrap();
+ let stores = f.cluster.received(STORE_CONSUMER_OFFSET_CODE);
+ assert_eq!(stores.len(), 4);
+ assert_eq!(ops(&stores[..3]), [op; 3]);
+ assert_ne!(stores[3].header.request, op);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_an_uncertain_send_when_an_unproved_reply_arrives_should_keep_its_lane() {
+ for answer in [
+ Answer::Refuse(IggyError::Unauthorized),
+ Answer::Body(Vec::new()),
+ ] {
+ let f = Fixture::new().await;
+ let op = f.uncertain_send().await;
+ f.script_sends(repeat_n(answer, ENDLESS));
+
+ let resolved = f.driver.resolve(op, Instant::now() + CALLER_TIMEOUT).await;
+
+ assert_eq!(resolved, Err(IggyError::OperationUncertain(op)));
+ assert_eq!(f.send_messages().await, Err(IggyError::LaneBlocked(op)));
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_uncertain_poll_progress_when_a_reply_is_lost_should_end_without_replay() {
+ for (auto_commit, strategy, progress) in [
+ (true, WirePollingStrategy::first(), true),
+ (false, WirePollingStrategy::next(), true),
+ (false, WirePollingStrategy::first(), false),
+ ] {
+ for (failure, uncertain) in [
+ (Answer::Refuse(IggyError::TransientNotCommitted), true),
+ (Answer::HangUp, true),
+ (Answer::Refuse(IggyError::TransientNotAccepted), false),
+ ] {
+ let f = Fixture::new().await;
+ f.cluster.script(
+ &endpoint(PRIMARY),
+ POLL_MESSAGES_CODE,
+ [failure, Answer::Body(Vec::new())],
+ );
+ let result = f
+ .driver
+ .send(
+ POLL_MESSAGES_CODE,
+ f.poll(auto_commit, strategy.clone()).to_bytes(),
+ f.partition(None),
+ )
+ .await;
+ let polls = f.cluster.received(POLL_MESSAGES_CODE);
+ if progress && uncertain {
+ assert_eq!(result, Err(IggyError::TransientNotCommitted));
+ assert_eq!(polls.len(), 1, "uncertain progress must not be replayed");
+ let operation_id = polls[0].header.request;
+ assert_eq!(
+ f.driver.abandon(operation_id),
+ Err(IggyError::OperationNotRetained(operation_id))
+ );
+ f.call(STORE_CONSUMER_OFFSET_CODE, f.partition(None))
+ .await
+ .unwrap();
+ } else {
+ assert_eq!(result, Ok(Bytes::new()));
+ assert_eq!(polls.len(), 2, "pure reads and unaccepted polls may retry");
+ }
+ }
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_progress_poll_when_cancelled_should_release_the_barrier_without_retention() {
+ for (auto_commit, strategy) in [
+ (true, WirePollingStrategy::first()),
+ (false, WirePollingStrategy::next()),
+ ] {
+ let f = Fixture::new().await;
+ f.cluster
+ .script(&endpoint(PRIMARY), POLL_MESSAGES_CODE, [Answer::Silence]);
+ let poll = f.driver.send(
+ POLL_MESSAGES_CODE,
+ f.poll(auto_commit, strategy).to_bytes(),
+ f.partition(None),
+ );
+ let store = f.call(STORE_CONSUMER_OFFSET_CODE, f.partition(None));
+ tokio::pin!(store);
+ let expired = timeout(CALLER_TIMEOUT, async {
+ tokio::pin!(poll);
+ tokio::select! {
+ _ = &mut poll => panic!("the unanswered poll returned"),
+ () = eventually("the progress poll arrived", || f.cluster.count(POLL_MESSAGES_CODE) == 1) => {}
+ }
+ tokio::select! {
+ _ = &mut poll => panic!("the unanswered poll returned"),
+ _ = &mut store => panic!("the store bypassed the progress barrier"),
+ }
+ }).await;
+ assert!(expired.is_err());
+ assert_eq!(f.cluster.count(STORE_CONSUMER_OFFSET_CODE), 0);
+ let poll_id = f.cluster.received(POLL_MESSAGES_CODE)[0].header.request;
+ assert_eq!(
+ f.driver.abandon(poll_id),
+ Err(IggyError::OperationNotRetained(poll_id))
+ );
+
+ store.await.unwrap();
+ assert_eq!(f.cluster.count(STORE_CONSUMER_OFFSET_CODE), 1);
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_retained_mutation_when_progress_poll_enters_should_return_its_blocking_id() {
+ let f = Fixture::new().await;
+ let op = f.uncertain_send().await;
+
+ let polled = f
+ .driver
+ .send(
+ POLL_MESSAGES_CODE,
+ f.poll(false, WirePollingStrategy::next()).to_bytes(),
+ f.partition(None),
+ )
.await;
- assert_eq!(again.unwrap_err(), IggyError::OperationNotRetained(op));
+
+ assert_eq!(polled, Err(IggyError::LaneBlocked(op)));
+ assert_eq!(f.cluster.count(POLL_MESSAGES_CODE), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn given_a_shared_deadline_when_a_nested_call_runs_should_keep_the_earliest_deadline() {
+ let f = Fixture::new().await;
+ let started = Instant::now();
+ let deadline = started + CALLER_TIMEOUT;
+
+ let result = with_deadline(
+ deadline,
+ with_deadline(
+ started + OPERATION_TIMEOUT,
+ f.call(UNANSWERED_CODE, RequestTarget::Metadata),
+ ),
+ )
... 71854 lines suppressed ...