Skip to content

feat(customer): csv export #2828

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

feat(customer): csv export #2828

wants to merge 5 commits into from

Conversation

hekike
Copy link
Contributor

@hekike hekike commented May 15, 2025

out.csv

Summary by CodeRabbit

  • New Features
    • CSV exports of meter query results now include enriched customer information such as name and email.
  • Enhancements
    • Improved customer filtering by supporting multiple subject keys instead of a single subject.
  • Bug Fixes
    • Added validation to prevent empty subject lists when filtering customers.
  • Chores
    • Integrated customer service into meter HTTP handlers and routing.
    • Added utilities for retrieving customers by subject keys with pagination support.
    • Removed deprecated CSV query handler to streamline functionality.

@hekike hekike requested a review from tothandras May 15, 2025 23:56
@hekike hekike requested a review from a team as a code owner May 15, 2025 23:56
Copy link

coderabbitai bot commented May 15, 2025

📝 Walkthrough

Walkthrough

The changes introduce support for filtering customers by multiple subjects instead of a single subject throughout the customer listing flow. This involves updating the input struct, validation, query construction, and HTTP handling logic. Additionally, the meter CSV query endpoint is reintroduced with enhancements to enrich results with customer information, requiring new dependencies, utility functions for customer lookup and pagination, and modifications to handler construction and routing.

Changes

File(s) Change Summary
openmeter/customer/customer.go Renamed Subject field to Subjects in ListCustomersInput struct and changed its type from *string to *[]string. Updated the Validate method to ensure Subjects, if set, is not empty.
openmeter/customer/adapter/customer.go Modified customer filtering logic in ListCustomers to support multiple subject keys, constructing an OR predicate for each subject in the provided slice.
openmeter/customer/httpdriver/customer.go Updated HTTP handler to set the new Subjects field (as a pointer to a slice) in ListCustomersInput when a subject parameter is present, replacing the previous single string assignment.
openmeter/meter/httphandler/handler.go, openmeter/server/router/router.go Added a customerService field to the handler struct and updated its constructor and router initialization to accept and assign the customer service dependency.
openmeter/meter/httphandler/query.go Removed the previous QueryMeterCSV handler and related types and methods, including CSV response implementation and imports related to CSV.
openmeter/meter/httphandler/query_csv.go Added a new QueryMeterCSV HTTP handler with enriched meter query rows including customer data, CSV response struct and methods, helper functions for customer enrichment, and error handling.
openmeter/meter/httphandler/util.go Added listAllCustomers function to paginate through all customers and listCustomersBySubjectKey to map subject keys to customers, supporting customer enrichment in queries.
openmeter/server/server_test.go Updated CSV query test cases to include additional columns for customer_name and customer_email in CSV output headers and data rows, with empty placeholders in test data.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0391154 and 2a6a8a0.

📒 Files selected for processing (1)
  • openmeter/server/server_test.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
openmeter/server/server_test.go (1)

321-322: Test updated correctly to reflect new CSV export format with customer fields.

The test cases for CSV export now include the additional customer_name and customer_email columns in the expected output format, aligning with the feature to enrich meter query results with customer information. The empty values for these fields in the test data are appropriate since this is using mock data.

Also applies to: 341-342

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

@hekike hekike added the release-note/feature Release note: Exciting New Features label May 15, 2025
Copy link

@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: 2

🧹 Nitpick comments (1)
openmeter/meter/httphandler/util.go (1)

14-37: Shadowed parameter and pagination tuning

params := params inside the loop re-assigns to a new variable that shadows the function parameter.
Although harmless, it is confusing and blocks accidental future writes back to the outer variable.
At the same time, limit is hard-coded to 100, and we never look at result.TotalCount, so we cannot pre-allocate the slice, and callers cannot influence page size.

-	params := params
-	params.Page = pagination.NewPage(page, limit)
+	local := params        // copy to avoid mutating caller-supplied struct
+	local.Page = pagination.NewPage(page, limit)

Consider:

  1. Renaming local to something explicit (e.g. pageParams).
  2. Accepting pageSize as a function argument or a constant at the package level so it can be tuned centrally.
  3. Pre-allocating customers when result.TotalCount is available to reduce reallocations.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1705591 and 6cff5ad.

📒 Files selected for processing (7)
  • openmeter/customer/adapter/customer.go (1 hunks)
  • openmeter/customer/customer.go (2 hunks)
  • openmeter/customer/httpdriver/customer.go (1 hunks)
  • openmeter/meter/httphandler/handler.go (3 hunks)
  • openmeter/meter/httphandler/query.go (9 hunks)
  • openmeter/meter/httphandler/util.go (1 hunks)
  • openmeter/server/router/router.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
openmeter/server/router/router.go (2)
openmeter/customer/customer.go (1)
  • Customer (15-23)
app/common/customer.go (1)
  • Customer (18-20)
openmeter/customer/httpdriver/customer.go (3)
api/api.gen.go (1)
  • Subject (6343-6360)
api/client/go/client.gen.go (1)
  • Subject (5807-5824)
api/client/javascript/src/client/subjects.ts (1)
  • Subjects (10-89)
openmeter/customer/customer.go (2)
api/client/javascript/src/client/subjects.ts (1)
  • Subjects (10-89)
pkg/models/error.go (1)
  • NewGenericValidationError (138-140)
openmeter/meter/httphandler/util.go (1)
openmeter/customer/customer.go (2)
  • ListCustomersInput (139-156)
  • Customer (15-23)
openmeter/meter/httphandler/query.go (4)
api/api.gen.go (3)
  • Subject (6343-6360)
  • Customer (2129-2176)
  • MeterQueryRow (4748-4764)
openmeter/customer/customer.go (2)
  • Customer (15-23)
  • ListCustomersInput (139-156)
openmeter/meter/httphandler/util.go (1)
  • ListAllCustomers (13-37)
openmeter/meter/meter.go (1)
  • MeterQueryRow (333-339)
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Commit hooks
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
openmeter/server/router/router.go (1)

266-272: Approved: Clean dependency injection

The customer service is now properly passed to the meter handler constructor, enabling the new CSV export functionality with customer data enrichment.

openmeter/customer/httpdriver/customer.go (1)

70-73: Approved: Good backward compatibility

The code elegantly preserves API compatibility by converting a single subject parameter to the new multi-subject structure, supporting the new CSV export feature without breaking existing integrations.

openmeter/meter/httphandler/handler.go (3)

8-8: Approved: Necessary import

Adding the customer package import to support the new dependency.


39-39: Approved: New dependency field

Adding the customer service field to the handler struct to enable customer data enrichment in CSV exports.


51-64: Approved: Constructor update

The constructor function is properly updated to accept and store the customer service dependency, maintaining the handler's initialization pattern.

openmeter/customer/customer.go (2)

153-153: Approved: Enhanced filtering capability

Changing from a single subject to multiple subjects allows more flexible customer filtering, which directly supports the CSV export feature.


163-165: Approved: Proper validation

The added validation ensures that if a subjects filter is provided, it contains at least one value, preventing meaningless empty filter queries.

openmeter/customer/adapter/customer.go (1)

69-77: Predicate may unintentionally match partially

SubjectKeyContainsFold(subject) performs a contains match (ILIKE %subject%).
If callers expect exact matching (previous API accepted a single exact subject), this widens the query surface and may return the wrong customers, especially with short tokens (e.g. "abc" will match "xabcx").

If exact matching is desired, switch to SubjectKeyEQ(subject) (or SubjectKey(subject) in ent):

-	return customerdb.HasSubjectsWith(customersubjectsdb.SubjectKeyContainsFold(subject))
+	return customerdb.HasSubjectsWith(customersubjectsdb.SubjectKeyEQ(subject))

Otherwise, document the new fuzzy-matching behaviour in the API.

openmeter/meter/httphandler/query.go (1)

293-297: Nil-safe email extraction can drop compile if lo.FromPtrOr is unavailable

lo.FromPtrOr exists only in ≥ v1.38. Ensure the project is pinned to a recent samber/lo or replace with a trivial helper:

email := ""
if row.Customer.PrimaryEmail != nil {
    email = *row.Customer.PrimaryEmail
}
data = append(data, row.Customer.ID, row.Customer.Name, email)

@hekike hekike changed the title Feat/csv export customer feat(customer): csv export May 16, 2025
Copy link

@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: 1

🧹 Nitpick comments (6)
openmeter/meter/httphandler/util.go (3)

32-36: Duplicate‐key overwrites are silent – consider detecting / logging collisions

When multiple customers share the same SubjectKey, the later customer will overwrite the earlier one in customersBySubjectKey.
Depending on your data-model this may be undesirable or at least something you want to be aware of.

for i, c := range customers {
    for _, key := range c.UsageAttribution.SubjectKeys {
        if _, exists := customersBySubjectKey[key]; exists {
            // log/debug or return an error?
        }
        customersBySubjectKey[key] = &customers[i]
    }
}

Even a simple debug-level log would make troubleshooting easier if the mapping ever behaves unexpectedly.


43-67: Shadowing the params identifier makes the code harder to read

Inside the loop you re-declare params := params. While legal, the shadowing is easy to stumble over when skimming the code.

- for {
-     params := params          // shadowed
+ for {
+     pageParams := params      // explicit copy
      pageParams.Page = pagination.NewPage(page, limit)

A distinct variable name clarifies intent and avoids confusion about which value is being mutated.


45-64: Expose page size and back-off strategy for large customer bases

The hard-coded limit := 100 combined with a tight loop means listing 10 000 customers will
perform 100 synchronous requests without any pacing. Consider:

  • Making the limit configurable (env or constant).
  • Adding a small back-off / context check to respect cancellation.
  • Exploring a streaming or cursor-based API on the customer service to avoid holding all rows in memory.

These tweaks improve scalability without changing semantics.

openmeter/meter/httphandler/query_csv.go (3)

152-157: Avoid %f default formatting for metric values

fmt.Sprintf("%f", row.Value) always prints six decimals (e.g. 12.340000) which bloats the CSV
and may mislead users into thinking the precision is fixed.
Consider:

- data = append(data, fmt.Sprintf("%f", row.Value))
+ data = append(data, strconv.FormatFloat(row.Value, 'g', -1, 64))

'g' chooses the shortest representation that round-trips, keeping files smaller and neater.


65-74: Potentially expensive customer lookup not paginated by caller

getSubjectsFromQueryResult can return hundreds/thousands of subjects.
listCustomersBySubjectKey then fetches all matching customers in one go.

If the customer service is remote this may introduce latency spikes.
You might:

  1. Short-circuit when subjects is empty (already done 👍).
  2. Batch the Subjects slice into pages matching CustomerService’s pagination instead of the fixed 100 used in listAllCustomers.
  3. Cache subjects seen in prior requests.

These optimisations are optional but will help once the feature is used on large datasets.


196-210: Minor optimisation: pre-allocate and deduplicate in one pass

Currently you (1) collect all subjects, (2) call lo.Uniq for deduplication.
You can avoid the extra slice and allocation by using a map[string]struct{}.

Not critical at this size, but worth considering for hot paths.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6cff5ad and 880e908.

📒 Files selected for processing (3)
  • openmeter/meter/httphandler/query.go (0 hunks)
  • openmeter/meter/httphandler/query_csv.go (1 hunks)
  • openmeter/meter/httphandler/util.go (1 hunks)
💤 Files with no reviewable changes (1)
  • openmeter/meter/httphandler/query.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/meter/httphandler/util.go (2)
openmeter/customer/customer.go (2)
  • Customer (15-23)
  • ListCustomersInput (139-156)
api/client/javascript/src/client/subjects.ts (1)
  • Subjects (10-89)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Commit hooks
  • GitHub Check: Build
  • GitHub Check: Test
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)

Copy link

@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

🧹 Nitpick comments (6)
openmeter/meter/httphandler/query_csv.go (6)

157-157: Consider more control over numeric formatting

The current implementation uses fmt.Sprintf("%f", row.Value) which doesn't provide control over decimal precision or handling of very large/small numbers.

-		data = append(data, fmt.Sprintf("%f", row.Value))
+		data = append(data, fmt.Sprintf("%.6f", row.Value))

Alternatively, consider using a more specialized formatting function that handles different numeric ranges appropriately.


143-145: Inconsistent handling of Name vs PrimaryEmail

The code directly uses row.Customer.Name but uses lo.FromPtrOr(row.Customer.PrimaryEmail, "") for email. This suggests that Name is a string while PrimaryEmail is a pointer to a string. For consistency, consider handling both fields similarly.

-			data = append(data, row.Customer.Name, lo.FromPtrOr(row.Customer.PrimaryEmail, ""))
+			data = append(data, lo.FromPtrOr(&row.Customer.Name, ""), lo.FromPtrOr(row.Customer.PrimaryEmail, ""))

Or if Name is guaranteed to be non-nil:

-			data = append(data, row.Customer.Name, lo.FromPtrOr(row.Customer.PrimaryEmail, ""))
+			// Name is a string, PrimaryEmail is a *string
+			data = append(data, row.Customer.Name, lo.FromPtrOr(row.Customer.PrimaryEmail, ""))

65-77: Consider handling the case of no matching customers

While there's good error handling for when listCustomersBySubjectKey returns an error, there's no specific handling for when it successfully returns an empty map. Consider adding a log message or metric to track this scenario to help diagnose potential customer data issues.

			customersBySubjectKey, err := listCustomersBySubjectKey(
				ctx,
				h.customerService,
				request.namespace,
				subjects,
			)
			if err != nil {
				return nil, fmt.Errorf("failed to get customers by subject key: %w", err)
			}
+			
+			// Log when no customers found for any subjects
+			if len(subjects) > 0 && len(customersBySubjectKey) == 0 {
+				// Consider adding logging or metrics here
+				// log.Info("No customers found for any subjects", "subjectCount", len(subjects))
+			}

126-132: Consider using constants for column headers

The CSV header strings are hardcoded. Consider defining these as constants or in a configuration to make them easier to maintain and reference elsewhere in the code.

+	// Define header constants
+	const (
+		HeaderWindowStart  = "window_start"
+		HeaderWindowEnd    = "window_end"
+		HeaderSubject      = "subject"
+		HeaderCustomerName = "customer_name"
+		HeaderCustomerEmail = "customer_email"
+		HeaderValue        = "value"
+	)

	// CSV headers
-	headers := []string{"window_start", "window_end", "subject", "customer_name", "customer_email"}
+	headers := []string{HeaderWindowStart, HeaderWindowEnd, HeaderSubject, HeaderCustomerName, HeaderCustomerEmail}
	if len(groupByKeys) > 0 {
		headers = append(headers, groupByKeys...)
	}
-	headers = append(headers, "value")
+	headers = append(headers, HeaderValue)

196-212: Efficient subject extraction, but consider early return

The subject extraction logic efficiently deduplicates the subjects using lo.Uniq. For slight optimization and readability, consider adding an early return for empty rows.

func getSubjectsFromQueryResult(rows []meter.MeterQueryRow) []string {
+	// Early return for empty result set
+	if len(rows) == 0 {
+		return []string{}
+	}

	// Collect subjects from query results if any
	subjects := []string{}
	for _, row := range rows {
		if row.Subject == nil {
			continue
		}

		subjects = append(subjects, *row.Subject)
	}

	// Deduplicate subjects
	subjects = lo.Uniq(subjects)

	return subjects
}

166-168: Consider adding timestamp to CSV filename

The current implementation uses only the meter slug for the filename. Consider adding a timestamp to prevent overwriting previous exports and to help with file organization.

func (a *queryMeterCSVResult) FileName() string {
-	return fmt.Sprintf("%s.csv", a.meterSlug)
+	return fmt.Sprintf("%s_%s.csv", a.meterSlug, time.Now().Format("20060102150405"))
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 880e908 and 0391154.

📒 Files selected for processing (1)
  • openmeter/meter/httphandler/query_csv.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
openmeter/meter/httphandler/query_csv.go (1)

143-147: Fixed column count issue correctly

The code now properly appends two empty strings when a customer is absent, which matches the two columns in the header for customer information. This addresses the previous issue where three empty strings were being appended, causing column misalignment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
release-note/feature Release note: Exciting New Features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant