Skip to content

Conversation

@Lyc-heng
Copy link
Contributor

@Lyc-heng Lyc-heng commented Oct 22, 2025

Thank you for your contribution to CloudRec!

What About:

  • Server (java)
  • Collector (go)
  • Rule (opa)

Description:

Fixed the issue of missing counts when retrieving AWS load balancers. The reason was that the original AWS LB retrieval repeatedly created EC2 clients (each LB query would create 2 EC2 clients), causing rate limiting by AWS after a large number of requests, making it impossible to retrieve data for a period of time.

Summary by Sourcery

Reuse a single EC2 client when retrieving ELB details and increase the DescribeLoadBalancers page size to prevent AWS rate limiting and ensure accurate load balancer counts

Bug Fixes:

  • Fix missing AWS load balancer counts caused by rate limiting from repeated EC2 client creation

Enhancements:

  • Add PageSize=400 to DescribeLoadBalancers requests
  • Include and initialize a shared EC2 client in Services and pass it into ELB detail functions
  • Update describeELBDetails to accept the shared EC2 client instead of instantiating new ones per call

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 22, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refactored ELB collector to reuse a single EC2 client for VPC and security group lookups and increased DescribeLoadBalancers page size to prevent AWS rate limiting and missing load balancers.

Sequence diagram for ELB detail retrieval with shared EC2 client

sequenceDiagram
    participant Collector
    participant Services
    participant ELBClient
    participant EC2Client
    Collector->>Services: InitServices()
    Services->>ELBClient: create ELB client
    Services->>EC2Client: create EC2 client
    Collector->>ELBClient: describeELBs()
    ELBClient-->>Collector: list of ELBs
    loop for each ELB
        Collector->>EC2Client: DescribeVPCDetailsByFilters(vpc-id)
        EC2Client-->>Collector: VPC details
        Collector->>EC2Client: DescribeSecurityGroupDetailsByFilters(group-id)
        EC2Client-->>Collector: Security group details
    end
    Collector-->>Services: ELBDetails
Loading

Entity relationship diagram for ELBDetail, VPC, and SecurityGroup

erDiagram
    ELBDetail {
        string ELB
        string VPC
        string[] SecurityGroups
    }
    VPCDetail {
        string VpcId
    }
    SecurityGroupDetail {
        string GroupId
    }
    ELBDetail ||--|{ VPCDetail : contains
    ELBDetail ||--|{ SecurityGroupDetail : contains
Loading

Class diagram for updated AWS Services and ELBDetail retrieval

classDiagram
    class Services {
        +string Region
        +EC2 *ec2.Client
        +ELB *elasticloadbalancingv2.Client
        +InitServices(cloudAccountParam)
    }
    class ELBDetail {
        +ELB types.LoadBalancer
        +VPC VPCDetail
        +SecurityGroups []SecurityGroupDetail
    }
    Services --> EC2 : uses
    Services --> ELB : uses
    ELBDetail --> VPCDetail : contains
    ELBDetail --> SecurityGroupDetail : contains
Loading

File-Level Changes

Change Details Files
Reuse a single EC2 client in ELB detail retrieval
  • Retrieve ec2Client once from Services in GetELBDetail
  • Change describeELBDetails signature to accept both elbClient and ec2Client
  • Replace inline ec2.NewFromConfig calls with the passed ec2Client
elasticloadbalancingv2.go
Increase DescribeLoadBalancers page size
  • Set PageSize to 400 in DescribeLoadBalancersInput to reduce number of AWS calls
elasticloadbalancingv2.go
Initialize EC2 client in Services for ELB collector
  • Add Region field to Services struct
  • Wire up s.EC2 initialization alongside s.ELB in InitServices
services.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@gemini-code-assist
Copy link

Summary of Changes

Hello @Lyc-heng, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical bug where the count of AWS load balancers was inaccurate due to frequent AWS API rate limiting. The fix involves a significant refactoring of how AWS EC2 clients are initialized and utilized within the collector. By ensuring that EC2 clients are created only once and then reused for subsequent calls, the changes prevent excessive API requests, thereby mitigating rate limiting issues and ensuring a complete and accurate retrieval of load balancer data.

Highlights

  • Eliminated Repeated EC2 Client Creation: The core issue of repeatedly creating new EC2 clients for each AWS Load Balancer query, which led to AWS API rate limiting, has been resolved.
  • Reused EC2 Client: The describeELBDetails function now accepts and reuses a single, pre-initialized EC2 client instance for fetching VPC and Security Group details, significantly reducing redundant client instantiations.
  • Optimized AWS API Calls: The DescribeLoadBalancers API call now includes a PageSize parameter set to 400, which helps in retrieving more results per call and potentially reduces the total number of API requests needed.
  • Centralized EC2 Client Initialization: The EC2 client is now initialized once within the Services struct when the ELB service is set up, making it readily available for reuse across related operations.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `collector/aws/collector/elasticloadbalancing/elasticloadbalancingv2.go:105-106` </location>
<code_context>

 func describeELBs(ctx context.Context, c *elasticloadbalancingv2.Client) (elbs []types.LoadBalancer, err error) {
-	input := &elasticloadbalancingv2.DescribeLoadBalancersInput{}
+	input := &elasticloadbalancingv2.DescribeLoadBalancersInput{
+		PageSize: aws.Int32(400),
+	}
 	output, err := c.DescribeLoadBalancers(ctx, input)
</code_context>

<issue_to_address>
**suggestion:** Hardcoded PageSize may not be optimal for all AWS accounts.

Making PageSize configurable or implementing pagination will help ensure all load balancers are retrieved, regardless of account size or future API changes.

Suggested implementation:

```golang
func describeELBs(ctx context.Context, c *elasticloadbalancingv2.Client, pageSize int32) (elbs []types.LoadBalancer, err error) {
	var marker *string
	elbs = []types.LoadBalancer{}
	for {
		input := &elasticloadbalancingv2.DescribeLoadBalancersInput{
			PageSize: aws.Int32(pageSize),
			Marker:   marker,
		}
		output, err := c.DescribeLoadBalancers(ctx, input)
		if err != nil {
			log.CtxLogger(ctx).Warn("DescribeLoadBalancers error", zap.Error(err))
			return nil, err
		}
		elbs = append(elbs, output.LoadBalancers...)
		if output.NextMarker == nil {
			break
		}
		marker = output.NextMarker
	}

```

- You will need to update all calls to `describeELBs` to pass the desired `pageSize` (e.g., `describeELBs(ctx, client, 400)`).
- Consider making `pageSize` a configurable value (e.g., from a config file or environment variable) if you want to avoid hardcoding it in function calls.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +105 to +106
input := &elasticloadbalancingv2.DescribeLoadBalancersInput{
PageSize: aws.Int32(400),
Copy link

Choose a reason for hiding this comment

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

suggestion: Hardcoded PageSize may not be optimal for all AWS accounts.

Making PageSize configurable or implementing pagination will help ensure all load balancers are retrieved, regardless of account size or future API changes.

Suggested implementation:

func describeELBs(ctx context.Context, c *elasticloadbalancingv2.Client, pageSize int32) (elbs []types.LoadBalancer, err error) {
	var marker *string
	elbs = []types.LoadBalancer{}
	for {
		input := &elasticloadbalancingv2.DescribeLoadBalancersInput{
			PageSize: aws.Int32(pageSize),
			Marker:   marker,
		}
		output, err := c.DescribeLoadBalancers(ctx, input)
		if err != nil {
			log.CtxLogger(ctx).Warn("DescribeLoadBalancers error", zap.Error(err))
			return nil, err
		}
		elbs = append(elbs, output.LoadBalancers...)
		if output.NextMarker == nil {
			break
		}
		marker = output.NextMarker
	}
  • You will need to update all calls to describeELBs to pass the desired pageSize (e.g., describeELBs(ctx, client, 400)).
  • Consider making pageSize a configurable value (e.g., from a config file or environment variable) if you want to avoid hardcoding it in function calls.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses the AWS rate limiting issue by reusing the EC2 client, which prevents the creation of multiple clients during load balancer discovery. The addition of PageSize to the DescribeLoadBalancers call is also a good optimization to reduce API calls. The implementation is sound. I have one minor suggestion to improve code maintainability by removing an unused field.


// Services contains regional client of AWS services
type Services struct {
Region string

Choose a reason for hiding this comment

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

medium

The Region field has been added to the Services struct, but it is not used anywhere in the codebase. To keep the code clean and avoid potential confusion, it's best to remove this unused field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant