ryerraguntla commented on code in PR #4043: URL: https://github.com/apache/iggy/pull/4043#discussion_r4001448410
########## gateways/kafka/src/bridge/error.rs: ########## @@ -0,0 +1,257 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use iggy::prelude::IggyError; +use thiserror::Error; + +use crate::protocol::api::{ + ERROR_NOT_LEADER_OR_FOLLOWER, ERROR_REQUEST_TIMED_OUT, ERROR_TOPIC_ALREADY_EXISTS, + ERROR_TOPIC_AUTHORIZATION_FAILED, ERROR_UNKNOWN_SERVER_ERROR, ERROR_UNKNOWN_TOPIC_OR_PARTITION, +}; + +/// Errors from the `IggyBridge`: connection lifecycle, config, and Iggy SDK calls. +#[derive(Debug, Error)] +pub enum BridgeError { + /// Bridge config is structurally invalid (empty address, missing credentials, malformed + /// topic-mapping TOML) - caught before any connection attempt. + #[error("invalid bridge configuration: {0}")] + InvalidConfig(String), + /// The Iggy client could not connect or authenticate, or a call failed after connecting. + /// Wraps the SDK's own error rather than re-deriving a parallel taxonomy. + /// + /// Caution logging or otherwise trusting this variant's `Display`: a server-side rejection + /// crosses the wire as a bare numeric code (`ReplyHeader.status` / a committed metadata + /// result), and the SDK reconstructs the full `IggyError` from just that code via + /// `IggyError::from_code` (`vsr.rs`). Any data-carrying variant's fields get + /// `Default::default()` in that path, not the real value - `Identifier::default()` is numeric + /// `0`, itself a valid id, so e.g. a reconstructed `StreamIdNotFound` can print "ID: 0" whether + /// or not stream 0 is the one that actually failed. Locally-constructed variants (this + /// module's own `ok_or_else` calls, for instance) carry real data; only ones that came back + /// from an actual server rejection are affected. + #[error("Iggy client error: {0}")] + Iggy(#[from] IggyError), + /// `high_watermark` was asked about a partition index the topic doesn't have. + #[error( + "partition {partition} out of range for topic '{topic}' ({partitions_count} partitions)" + )] + PartitionOutOfRange { + topic: String, + partition: u32, + partitions_count: u32, + }, + /// `ensure_topic` was asked to ensure a topic that already exists with a different partition + /// count. `ensure_topic`'s whole contract is "the topic has `partition_count` partitions + /// afterward" - silently keeping the old count and returning `Ok(())` would let two + /// concurrent callers requesting different counts for the same topic both believe they + /// succeeded. + #[error( + "topic '{topic}' already exists with {existing} partitions, but {requested} were requested" + )] + PartitionCountMismatch { + topic: String, + existing: u32, + requested: u32, + }, +} + +impl BridgeError { + /// Maps this error to the Kafka protocol error code a handler should answer with. + /// + /// Connection-shaped failures reuse `NOT_LEADER_OR_FOLLOWER` (6) - the same retriable code + /// the foundation's Produce/Fetch stubs already send - so a client backs off and retries + /// rather than treating a transient Iggy outage as a permanent failure. Not-found maps to + /// `UNKNOWN_TOPIC_OR_PARTITION` (3). Anything without a closer analogue falls back to + /// `UNKNOWN_SERVER_ERROR` (-1). + #[must_use] + pub const fn to_kafka_error_code(&self) -> i16 { + match self { + Self::Iggy(err) => iggy_error_to_kafka_code(err), + Self::PartitionOutOfRange { .. } => ERROR_UNKNOWN_TOPIC_OR_PARTITION, + Self::PartitionCountMismatch { .. } => ERROR_TOPIC_ALREADY_EXISTS, + // Not a wire-response case in practice: an invalid bridge config is caught at + // `IggyBridge::connect` before any handler exists to answer a Kafka request, so this + // is reachable only if a future caller starts constructing configs at request time. + // `UNKNOWN_SERVER_ERROR` at least doesn't claim a specific, wrong cause the way + // `UNSUPPORTED_VERSION` (misleadingly implies a Kafka API version mismatch) would. + Self::InvalidConfig(_) => ERROR_UNKNOWN_SERVER_ERROR, + } + } +} + +/// Kept private so this association can change without touching call sites. +/// +/// The connection-shaped set (`Disconnected`, `EmptyResponse`, `Unauthenticated`, `StaleClient`, +/// `NotConnected`, `CannotEstablishConnection`, `TcpError`) mirrors exactly what +/// `TcpClient::send_raw_with_response` (`tcp_client.rs`) itself treats as worth a reconnect retry. +/// A mapping that only covered some of these would send a permanent-looking Kafka error for a +/// condition the SDK itself considers transient. `Unauthenticated` belongs here, not with the +/// credential-rejection group below: `fail_if_not_authenticated` (`binary_auth.rs`) returns it for +/// `ClientState::Connected`, the ordinary window between a reconnect's TCP handshake completing +/// and its auto-sign-in landing, not for a rejected login. +/// +/// `TransientNotAccepted` (Iggy replica-side "retry, on any replica") is retriable the same way. +/// `TransientNotCommitted` is not folded into that set: its outcome is genuinely unknown rather +/// than known-safe-to-retry, so it maps to `REQUEST_TIMED_OUT` instead of +/// `NOT_LEADER_OR_FOLLOWER` - a caller must not treat it as an ordinary retriable failure and risk +/// a duplicate write. +const fn iggy_error_to_kafka_code(err: &IggyError) -> i16 { + match err { + IggyError::StreamIdNotFound(_) + | IggyError::StreamNameNotFound(_) + | IggyError::TopicIdNotFound(_, _) + | IggyError::TopicNameNotFound(_, _) => ERROR_UNKNOWN_TOPIC_OR_PARTITION, + IggyError::Unauthorized + | IggyError::InvalidCredentials + | IggyError::InvalidUsername + | IggyError::InvalidPassword => ERROR_TOPIC_AUTHORIZATION_FAILED, + IggyError::Disconnected + | IggyError::EmptyResponse + | IggyError::Unauthenticated + | IggyError::StaleClient + | IggyError::NotConnected + | IggyError::CannotEstablishConnection + | IggyError::TcpError + | IggyError::TransientNotAccepted => ERROR_NOT_LEADER_OR_FOLLOWER, + IggyError::TransientNotCommitted => ERROR_REQUEST_TIMED_OUT, + _ => ERROR_UNKNOWN_SERVER_ERROR, Review Comment: **Partially fixed**. TooManyPartitions now maps to ERROR_INVALID_PARTITIONS (37), with a new test (too_many_partitions_maps_to_invalid_partitions). InvalidIdentifier was deliberately left on the catch-all - to be cautios , the server also raises it for an absent partition id, and a blanket arm to INVALID_TOPIC_EXCEPTION would mislabel that case. Didn't see a safe narrower mapping without a stream-name-vs-partition-id lookup this method has no basis for, but open to a suggestion . -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
