Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat : streamlining client request handling #1202

Merged
merged 3 commits into from
Apr 23, 2024
Merged

Conversation

rajadilipkolli
Copy link
Owner

@rajadilipkolli rajadilipkolli commented Apr 23, 2024

Summary by CodeRabbit

  • New Features

    • Introduced enhanced HTTP client service with retry capabilities for improved reliability.
    • Extended network request configurations to include a longer read timeout.
  • Refactor

    • Updated HTTP services to utilize the new client service, streamlining request handling.
  • Bug Fixes

    • Renamed and updated exception class for clearer error management.

Copy link
Contributor

coderabbitai bot commented Apr 23, 2024

Warning

Rate Limit Exceeded

@rajadilipkolli has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 27 minutes and 5 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.

Commits Files that changed from the base of the PR and between 337be2f and 5e863e9.

Walkthrough

The recent update enhances the HTTP client module in a Spring Boot application by introducing retry capabilities, improving timeout settings, and refactoring service classes for better structure and readability. Key changes include adding dependencies, enabling retries, and streamlining HTTP request handling through a new service class.

Changes

File Path Change Summary
.../pom.xml Added spring-retry and spring-aspects dependencies.
.../config/RestClientConfiguration.java Added @EnableRetry, updated timeout settings in jdkClientHttpRequestFactory.
.../exception/MyCustomClientException.java Renamed class from MyCustomRuntimeException, updated constructor.
.../services/HttpClientService.java New service class for handling HTTP requests with retry and response processing.
.../services/PostService.java Refactored to use HttpClientService for HTTP requests.

🐇✨
In the land of code and wire,
A rabbit hopped, with an aim so dire.
To tweak and tune with utmost flair,
Spring's web clients, handled with care.
Now retries dance, and timeouts sing,
A tale of HTTP joy they bring! 🌟🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@rajadilipkolli rajadilipkolli self-assigned this Apr 23, 2024
@github-actions github-actions bot added type: dependency-upgrade Pull requests that update a dependency file component: httpclients labels Apr 23, 2024
@rajadilipkolli rajadilipkolli changed the title feat : modularize httpClient Call feat : streamlining client request handling Apr 23, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Out of diff range and nitpick comments (1)
httpClients/boot-restclient/src/main/java/com/example/restclient/bootrestclient/services/HttpClientService.java (1)

16-20: Retry configuration with @Retryable is correctly set up for generic exceptions. Consider specifying more specific exception types if applicable.

Copy link

Quality Gate Passed Quality Gate passed

Issues
1 New issue
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

@Service
public class PostService {
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai, can you please generate junits for this class using @AutoConfigureMockRestServiceServer and @SpringBootTest

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rajadilipkolli, here are the JUnit tests for the PostService class using @AutoConfigureMockRestServiceServer and @SpringBootTest. Each test ensures that the service methods interact correctly with the HttpClientService.

package com.example.restclient.bootrestclient.services;

import com.example.restclient.bootrestclient.model.response.PostDto;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureMockRestServiceServer;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Optional;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockRestServiceServer
public class PostServiceTest {

    @Autowired
    private PostService postService;

    @MockBean
    private HttpClientService httpClientService;

    @Test
    public void testFindAllPosts() {
        when(httpClientService.callAndFetchResponse(any(), eq(HttpMethod.GET), isNull(), any()))
                .thenReturn(List.of(new PostDto()));
        List<PostDto> result = postService.findAllPosts();
        assertNotNull(result);
        assertFalse(result.isEmpty());
        verify(httpClientService).callAndFetchResponse(any(), eq(HttpMethod.GET), isNull(), any());
    }

    @Test
    public void testFindPostById() {
        when(httpClientService.callAndFetchResponse(any(), eq(HttpMethod.GET), any(), eq(PostDto.class)))
                .thenReturn(new PostDto());
        Optional<PostDto> result = postService.findPostById(1L);
        assertTrue(result.isPresent());
        verify(httpClientService).callAndFetchResponse(any(), eq(HttpMethod.GET), any(), eq(PostDto.class));
    }

    @Test
    public void testSavePost() {
        PostDto post = new PostDto();
        when(httpClientService.callAndFetchResponse(any(), eq(HttpMethod.POST), eq(post), eq(PostDto.class)))
                .thenReturn(post);
        PostDto result = postService.savePost(post);
        assertNotNull(result);
        verify(httpClientService).callAndFetchResponse(any(), eq(HttpMethod.POST), eq(post), eq(PostDto.class));
    }

    @Test
    public void testUpdatePostById() {
        PostDto post = new PostDto();
        when(httpClientService.callAndFetchResponse(any(), eq(HttpMethod.PUT), eq(post), eq(PostDto.class)))
                .thenReturn(post);
        Optional<PostDto> result = postService.updatePostById(1L, post);
        assertTrue(result.isPresent());
        verify(httpClientService).callAndFetchResponse(any(), eq(HttpMethod.PUT), eq(post), eq(PostDto.class));
    }

    @Test
    public void testDeletePostById() {
        when(httpClientService.callAndFetchResponse(any(), eq(HttpMethod.DELETE), isNull(), eq(String.class)))
                .thenReturn("Deleted");
        String result = postService.deletePostById(1L);
        assertEquals("Deleted", result);
        verify(httpClientService).callAndFetchResponse(any(), eq(HttpMethod.DELETE), isNull(), eq(String.class));
    }
}

These tests mock the HttpClientService to verify that PostService is making the correct calls and handling the responses as expected. Let me know if you need any more specific scenarios tested or further modifications!

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai, I don't see using MockRestServiceServer in the response, can you please use it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rajadilipkolli, I've revised the JUnit tests for the PostService class to explicitly use MockRestServiceServer. This will allow us to set up expectations and responses for the HTTP requests made by the service methods. Here's the updated test class:

package com.example.restclient.bootrestclient.services;

import com.example.restclient.bootrestclient.model.response.PostDto;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureMockRestServiceServer;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Optional;

import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockRestServiceServer
public class PostServiceTest {

    @Autowired
    private PostService postService;

    @Autowired
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @BeforeEach
    public void setUp() {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void testFindAllPosts() {
        mockServer.expect(requestTo("/posts"))
                  .andExpect(method(HttpMethod.GET))
                  .andRespond(withSuccess("[{}]", MediaType.APPLICATION_JSON));
        List<PostDto> result = postService.findAllPosts();
        assertNotNull(result);
        assertFalse(result.isEmpty());
        mockServer.verify();
    }

    @Test
    public void testFindPostById() {
        mockServer.expect(requestTo("/posts/1"))
                  .andExpect(method(HttpMethod.GET))
                  .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
        Optional<PostDto> result = postService.findPostById(1L);
        assertTrue(result.isPresent());
        mockServer.verify();
    }

    @Test
    public void testSavePost() {
        PostDto post = new PostDto();
        mockServer.expect(requestTo("/posts"))
                  .andExpect(method(HttpMethod.POST))
                  .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
        PostDto result = postService.savePost(post);
        assertNotNull(result);
        mockServer.verify();
    }

    @Test
    public void testUpdatePostById() {
        PostDto post = new PostDto();
        mockServer.expect(requestTo("/posts/1"))
                  .andExpect(method(HttpMethod.PUT))
                  .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
        Optional<PostDto> result = postService.updatePostById(1L, post);
        assertTrue(result.isPresent());
        mockServer.verify();
    }

    @Test
    public void testDeletePostById() {
        mockServer.expect(requestTo("/posts/1"))
                  .andExpect(method(HttpMethod.DELETE))
                  .andRespond(withSuccess("Deleted", MediaType.TEXT_PLAIN));
        String result = postService.deletePostById(1L);
        assertEquals("Deleted", result);
        mockServer.verify();
    }
}

These tests now use MockRestServiceServer to set up expectations on the HTTP requests and provide mock responses, ensuring that PostService is making the correct calls and handling the responses as expected. Let me know if you need any more specific scenarios tested or further modifications!

@rajadilipkolli rajadilipkolli merged commit 22a3e1a into main Apr 23, 2024
6 checks passed
@rajadilipkolli rajadilipkolli deleted the modularize-client branch April 23, 2024 11:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: httpclients type: dependency-upgrade Pull requests that update a dependency file
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant