ronantakizawa/codereview-bench huggingface dataset:
Repository: juspay/hyperswitch
File: crates/router/src/routes/app.rs (Rust)

Code before:
#[cfg(all(feature = "olap", feature = "v2"))]
impl ProcessTracker {
    pub fn server(state: AppState) -> Scope {
        use super::process_tracker::revenue_recovery;
        web::scope("/v2/process_tracker/revenue_recovery_workflow")
            .app_data(web::Data::new(state.clone()))
            .service(
                web::resource("/{revenue_recovery_id}")
                    .route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)),
            )
    }
}

#[cfg(feature = "olap")]
pub struct ProfileAcquirer;

#[cfg(all(feature = "olap", feature = "v1"))]
impl ProfileAcquirer {
    pub fn server(state: AppState) -> Scope {
        web::scope("/profile_acquirer")
            .app_data(web::Data::new(state))
            .service(
                web::resource("").route(web::post().to(profile_acquirer::create_profile_acquirer)),
            )
            .service(
                web::resource("{profile_id}/{profile_acquirer_id}")
                    .route(web::post().to(profile_acquirer::profile_acquirer_update)),
            )
    }
}


Review comment (suggestion):
Nit: We should probably add a leading `/`.

```suggestion
                web::resource("/{profile_id}/{profile_acquirer_id}")
```

Code after:
#[cfg(all(feature = "olap", feature = "v2"))]
impl ProcessTracker {
    pub fn server(state: AppState) -> Scope {
        use super::process_tracker::revenue_recovery;
        web::scope("/v2/process_tracker/revenue_recovery_workflow")
            .app_data(web::Data::new(state.clone()))
            .service(
                web::resource("/{revenue_recovery_id}")
                    .route(web::get().to(revenue_recovery::revenue_recovery_pt_retrieve_api)),
            )
    }
}

#[cfg(feature = "olap")]
pub struct ProfileAcquirer;

#[cfg(all(feature = "olap", feature = "v1"))]
impl ProfileAcquirer {
    pub fn server(state: AppState) -> Scope {
        web::scope("/profile_acquirer")
            .app_data(web::Data::new(state))
            .service(
                web::resource("").route(web::post().to(profile_acquirer::create_profile_acquirer)),
            )
            .service(
                web::resource("/{profile_id}/{profile_acquirer_id}")
                    .route(web::post().to(profile_acquirer::profile_acquirer_update)),
            )
    }
}
Repository: juspay/hyperswitch
File: crates/masking/src/strong_secret.rs (Rust)

Code before:
    fn strong_eq(&self, other: &Self) -> bool {
        let lhs = &self;
        let rhs = &other;

        bool::from(lhs.ct_eq(rhs))
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for StrongSecret<T, crate::WithType>
where
    T: prost::Message + Default + Clone + ZeroizableSecret,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        self.peek_mut().merge_field(tag, wire_type, buf, ctx)?;
        Ok(())
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear();
    }
}


Review comment (suggestion):
Nit:
```suggestion
        self.peek_mut().merge_field(tag, wire_type, buf, ctx)
```

Code after:
    fn strong_eq(&self, other: &Self) -> bool {
        let lhs = &self;
        let rhs = &other;

        bool::from(lhs.ct_eq(rhs))
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for StrongSecret<T, crate::WithType>
where
    T: prost::Message + Default + Clone + ZeroizableSecret,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        if tag == 1 {
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)
        } else {
            prost::encoding::skip_field(wire_type, tag, buf, ctx)
        }
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear();
    }
}
Repository: juspay/hyperswitch
File: crates/masking/src/secret.rs (Rust)

Code before:
                // For booleans, we can show a hint about which one it is
                write!(f, "{}", if *b { "**true" } else { "**false" })
            }
            serde_json::Value::Null => write!(f, "null"),
        }
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for Secret<T, crate::WithType>
where
    T: prost::Message + Default + Clone,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        self.peek_mut().merge_field(tag, wire_type, buf, ctx)?;
        Ok(())
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear()
    }
}

#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    #[allow(clippy::expect_used)]
    fn test_json_mask_strategy() {
        // Create a sample JSON with different types for testing
        let original = json!({ "user": { "name": "John Doe", "email": "john@example.com", "age": 35, "verified": true }, "card": { "number": "4242424242424242", "cvv": 123, "amount": 99.99 }, "tags": ["personal", "premium"], "null_value": null, "short": "hi" });

        // Apply the JsonMaskStrategy

Review comment (suggestion):
Nit:

```suggestion
        self.peek_mut().merge_field(tag, wire_type, buf, ctx)
```

Code after:
                // For booleans, we can show a hint about which one it is
                write!(f, "{}", if *b { "**true" } else { "**false" })
            }
            serde_json::Value::Null => write!(f, "null"),
        }
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for Secret<T, crate::WithType>
where
    T: prost::Message + Default + Clone,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        if tag == 1 {
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)
        } else {
            prost::encoding::skip_field(wire_type, tag, buf, ctx)
        }
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear();
    }
}

#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    #[allow(clippy::expect_used)]
    fn test_json_mask_strategy() {
        // Create a sample JSON with different types for testing
Repository: juspay/hyperswitch
File: crates/masking/src/secret.rs (Rust)

Code before:
                write!(f, "{}", if *b { "**true" } else { "**false" })
            }
            serde_json::Value::Null => write!(f, "null"),
        }
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for Secret<T, crate::WithType>
where
    T: prost::Message + Default + Clone,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        if tag == 1 {
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)?;
            Ok(())
        } else {
            prost::encoding::skip_field(wire_type, tag, buf, ctx)
        }
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear()
    }
}

#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    #[allow(clippy::expect_used)]
    fn test_json_mask_strategy() {
        // Create a sample JSON with different types for testing

Review comment (suggestion):
Nit:
```suggestion
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)
```

Code after:
                write!(f, "{}", if *b { "**true" } else { "**false" })
            }
            serde_json::Value::Null => write!(f, "null"),
        }
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for Secret<T, crate::WithType>
where
    T: prost::Message + Default + Clone,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        if tag == 1 {
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)
        } else {
            prost::encoding::skip_field(wire_type, tag, buf, ctx)
        }
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear();
    }
}

#[cfg(test)]
#[cfg(feature = "serde")]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    #[allow(clippy::expect_used)]
    fn test_json_mask_strategy() {
        // Create a sample JSON with different types for testing
        let original = json!({ "user": { "name": "John Doe", "email": "john@example.com", "age": 35, "verified": true }, "card": { "number": "4242424242424242", "cvv": 123, "amount": 99.99 }, "tags": ["personal", "premium"], "null_value": null, "short": "hi" });
Repository: juspay/hyperswitch
File: crates/masking/src/strong_secret.rs (Rust)

Code before:
        let lhs = &self;
        let rhs = &other;

        bool::from(lhs.ct_eq(rhs))
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for StrongSecret<T, crate::WithType>
where
    T: prost::Message + Default + Clone + ZeroizableSecret,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        if tag == 1 {
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)?;
            Ok(())
        } else {
            prost::encoding::skip_field(wire_type, tag, buf, ctx)
        }
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear();
    }
}


Review comment (suggestion):
Same here.

```suggestion
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)
```

Code after:
        let lhs = &self;
        let rhs = &other;

        bool::from(lhs.ct_eq(rhs))
    }
}

#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for StrongSecret<T, crate::WithType>
where
    T: prost::Message + Default + Clone + ZeroizableSecret,
{
    fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
        self.peek().encode_raw(buf);
    }

    fn merge_field(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut impl bytes::Buf,
        ctx: prost::encoding::DecodeContext,
    ) -> Result<(), prost::DecodeError> {
        if tag == 1 {
            self.peek_mut().merge_field(tag, wire_type, buf, ctx)
        } else {
            prost::encoding::skip_field(wire_type, tag, buf, ctx)
        }
    }

    fn encoded_len(&self) -> usize {
        self.peek().encoded_len()
    }

    fn clear(&mut self) {
        self.peek_mut().clear();
    }
}
Repository: juspay/hyperswitch
File: cypress-tests/cypress/e2e/configs/Payment/Paypal.js (JavaScript)

Code before:
      Response: {
        status: 200,
        body: {
          status: "succeeded",
        },
      },
    },
    IncrementalAuth: {
      Request: {
        amount: 8000,
      },
      Response: {
        status: 200,
        body: {
          status: "requires_capture",
          amount: 8000,
          amount_capturable: 6000, // Incremental Authorization can be done atleast 4 days after the authorization in case of Paypal
          amount_received: null,
          is_error_code_expected: true,
          incremental_authorizations: [
            {
              error_code: "REAUTHORIZATION_TOO_SOON",
              error_message: "REAUTHORIZATION_TOO_SOON",
            },
          ],
        },
      },
    },
    ZeroAuthMandate: {
      Request: {
        payment_method: "card",
        payment_method_data: {
          card: successfulNo3DSCardDetails,
        },
        currency: "USD",
        mandate_data: singleUseMandateData,
      },
      Response: {
        status: 200,
        body: {
          status: "succeeded",
        },
      },
    },
    ZeroAuthPaymentIntent: {
      Request: {
        amount: 0,
        setup_future_usage: "off_session",
        currency: "USD",
      },
      Response: {

Review comment (bug):
Can you add the other keys as well as discussed.
```suggestion
          incremental_authorizations: [
            {
              amount: 8000,
              previously_authorized_amount: 6000,
              status: "failure",
              error_code: "REAUTHORIZATION_TOO_SOON",
              error_message: "REAUTHORIZATION_TOO_SOON",
            },
          ],
        },
```

Code after:
      Response: {
        status: 200,
        body: {
          status: "succeeded",
        },
      },
    },
    IncrementalAuth: {
      Request: {
        amount: 8000,
      },
      Response: {
        status: 200,
        body: {
          status: "requires_capture",
          amount: 8000,
          amount_capturable: 6000, // Incremental Authorization can be done atleast 4 days after the authorization in case of Paypal
          amount_received: null,
          incremental_authorizations: [
            {
              amount: 8000,
              previously_authorized_amount: 6000,
              status: "failure",
              error_code: "REAUTHORIZATION_TOO_SOON",
              error_message: "REAUTHORIZATION_TOO_SOON",
            },
          ],
        },
      },
    },
    ZeroAuthMandate: {
      Request: {
        payment_method: "card",
        payment_method_data: {
          card: successfulNo3DSCardDetails,
        },
        currency: "USD",
        mandate_data: singleUseMandateData,
      },
      Response: {
        status: 200,
        body: {
          status: "succeeded",
        },
      },
    },
    ZeroAuthPaymentIntent: {
      Request: {
        amount: 0,
        setup_future_usage: "off_session",
        currency: "USD",
Repository: juspay/hyperswitch
File: crates/common_types/src/domain.rs (Rust)

Code before:

impl_to_sql_from_sql_json!(AcquirerConfigMap);

/// Merchant connector details
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[cfg(feature = "v2")]
pub struct MerchantConnectorAuthDetails {
    /// The connector used for the payment
    #[schema(value_type = Connector)]
    pub connector_name: common_enums::connector_enums::Connector,

    /// The merchant connector credentials used for the payment
    #[schema(value_type = Object, example = r#"{
        "merchant_connector_creds": {
            "auth_type": "HeaderKey",
            "api_key":"sk_test_xxxxxexamplexxxxxx12345"
        },
    }"#)]
    pub merchant_connector_creds: common_utils::pii::SecretSerdeValue,
}

/// Connector Response Data that are required to be populated in response
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct ConnectorResponseData {
    /// Stringified connector raw response body, but not persisted in DB.
    pub raw_connector_response: Option<Secret<String>>,
}


Review comment (suggestion):
```suggestion
    /// Stringified connector raw response body.
```

`, but not persisted in DB.` should be mentioned on the struct. Not here.

Code after:
/// Merchant connector details
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[cfg(feature = "v2")]
pub struct MerchantConnectorAuthDetails {
    /// The connector used for the payment
    #[schema(value_type = Connector)]
    pub connector_name: common_enums::connector_enums::Connector,

    /// The merchant connector credentials used for the payment
    #[schema(value_type = Object, example = r#"{
        "merchant_connector_creds": {
            "auth_type": "HeaderKey",
            "api_key":"sk_test_xxxxxexamplexxxxxx12345"
        },
    }"#)]
    pub merchant_connector_creds: common_utils::pii::SecretSerdeValue,
}

/// Connector Response Data that are required to be populated in response, but not persisted in DB.
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct ConnectorResponseData {
    /// Stringified connector raw response body
    pub raw_connector_response: Option<Secret<String>>,
}
Repository: juspay/hyperswitch
File: cypress-tests/cypress/e2e/configs/Payment/Stripe.js (JavaScript)

Code before:
          unified_message: "Something went wrong",
        },
      },
    },
    Capture: {
      Request: {
        amount_to_capture: 6000,
      },
      Response: {
        status: 200,
        body: {
          status: "succeeded",
          amount: 6000,
          amount_capturable: 0,
          amount_received: 6000,
        },
      },
      ResponseCustom: {
        status: 200,
        body: {
          status: "succeeded",
          amount: 8000,
          amount_capturable: 0,
          amount_received: 8000,
        },
      },
    },
    PartialCapture: {
      Request: {
        amount_to_capture: 2000,
      },
      Response: {
        status: 200,
        body: {
          status: "partially_captured",
          amount: 6000,
          amount_capturable: 0,
          amount_received: 2000,
        },
      },
    },
    Void: {
      Request: {},
      Response: {
        status: 200,
        body: {
          status: "cancelled",
        },
      },
    },
    Refund: {

Review comment (bug):
this ain't gonna work. support for `ResponseCustom` is broken / dependent on spec file. 

cc: @likhinbopanna 

Code after:
          unified_message: "Something went wrong",
        },
      },
    },
    Capture: {
      Request: {
        amount_to_capture: 6000,
      },
      Response: {
        status: 200,
        body: {
          status: "succeeded",
          amount: 6000,
          amount_capturable: 0,
          amount_received: 6000,
        },
      },
    },
    PartialCapture: {
      Request: {
        amount_to_capture: 2000,
      },
      Response: {
        status: 200,
        body: {
          status: "partially_captured",
          amount: 6000,
          amount_capturable: 0,
          amount_received: 2000,
        },
      },
    },
    Void: {
      Request: {},
      Response: {
        status: 200,
        body: {
          status: "cancelled",
        },
      },
    },
    Refund: {
      Request: {
        amount: 6000,
      },
      Response: {
        status: 200,
        body: {
          status: "succeeded",
        },
      },
Repository: juspay/hyperswitch
File: crates/router/src/core/chat.rs (Rust)

Code before:
    let url = format!("{}/webhook", state.conf.chat.hyperswitch_ai_host);

    let request_body = chat_domain::EmbeddedAiDataRequest {
        query: chat_domain::GetDataMessage {
            message: req.message,
        },
        org_id: user_from_token.org_id,
        merchant_id: user_from_token.merchant_id,
        profile_id: user_from_token.profile_id,
    };

    let request = RequestBuilder::new()
        .method(Method::Post)
        .url(&url)
        .attach_default_headers()
        .set_body(RequestContent::Json(Box::new(request_body)))
        .build();

    let response = http_client::send_request(&state.conf.proxy, request, None)
        .await
        .change_context(ChatErrors::InternalServerError)
        .attach_printable("Error in send request")?
        .json::<_>()
        .await
        .change_context(ChatErrors::InternalServerError)
        .attach_printable("Error in deserializing response")?;

    Ok(ApplicationResponse::Json(response))
}


Review comment (suggestion):
Nit: Better error messages.
```suggestion
        .change_context(ChatErrors::InternalServerError)
        .attach_printable("Error when sending request to AI service")?
        .json::<_>()
        .await
        .change_context(ChatErrors::InternalServerError)
        .attach_printable("Error when deserializing response from AI service")?;
```



Code after:
    user_from_token: auth::UserFromToken,
    req: chat_api::ChatRequest,
) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> {
    let url = format!("{}/webhook", state.conf.chat.hyperswitch_ai_host);

    let request_body = chat_domain::HyperswitchAiDataRequest {
        query: chat_domain::GetDataMessage {
            message: req.message,
        },
        org_id: user_from_token.org_id,
        merchant_id: user_from_token.merchant_id,
        profile_id: user_from_token.profile_id,
    };
    logger::info!("Request for AI service: {:?}", request_body);

    let request = RequestBuilder::new()
        .method(Method::Post)
        .url(&url)
        .attach_default_headers()
        .set_body(RequestContent::Json(Box::new(request_body.clone())))
        .build();

    let response = http_client::send_request(
        &state.conf.proxy,
        request,
        Some(consts::REQUEST_TIME_OUT_FOR_AI_SERVICE),
    )
    .await
    .change_context(ChatErrors::InternalServerError)
    .attach_printable("Error when sending request to AI service")?
    .json::<_>()
    .await
    .change_context(ChatErrors::InternalServerError)
    .attach_printable("Error when deserializing response from AI service")?;

    Ok(ApplicationResponse::Json(response))
}