Repository navigation
feat(api): add csv support for v3 meter query - #4196
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (7)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughAdds explicit JSON and CSV query operations for meters, a new CSV handler and handler method, content-negotiating routing to dispatch CSV vs JSON, buffered CSV encoding before send, and regenerated embedded OpenAPI spec reflecting the new operations. (≤50 words) Changes
Sequence DiagramsequenceDiagram
participant Client
participant Router
participant MeterHandler
participant StreamingService
participant CustomerService
participant Response
Client->>Router: POST /meters/{id}/query\nAccept: text/csv
Router->>Router: GetMediaType(request)
alt text/csv detected
Router->>MeterHandler: QueryMeterCSV()
else JSON or other
Router->>MeterHandler: QueryMeter()
end
MeterHandler->>MeterHandler: Parse request & resolve namespace
MeterHandler->>StreamingService: QueryMeter(params)
StreamingService->>MeterHandler: Return rows
MeterHandler->>MeterHandler: Extract distinct CustomerIDs
alt Customer IDs present
MeterHandler->>CustomerService: ListCustomers(ids)
CustomerService->>MeterHandler: Return customer metadata
end
MeterHandler->>MeterHandler: Build CSV headers & records (dynamic)
MeterHandler->>Response: Return CSV response (buffered)
Response->>Client: 200 OK + CSV payload
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested Reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
eb2d8a0 to
69b7c2f
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (5)
api/spec/packages/aip/src/meters/operations.tsp (2)
98-109: Doc comment reads great — small clarification request.Love the expanded column layout description. One small ambiguity: "The three
customer_*columns are emitted together when any result row has an associated customer." Does "any row" mean all rows get the columns (with blanks where no customer is attached), or only when every row has a customer? A one-word tweak would remove the doubt for API consumers building parsers.✏️ Suggested wording
- * The three `customer_*` columns are emitted together when any result row - * has an associated customer. + * The three `customer_*` columns are emitted together whenever at least one + * result row has an associated customer; rows without a customer leave these + * fields blank.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/spec/packages/aip/src/meters/operations.tsp` around lines 98 - 109, Update the doc comment describing CSV columns so the behavior is unambiguous: change the sentence about the three customer_* columns (near the CSV columns list in the comment) to state that the three customer_* columns are included whenever any result row has an associated customer and, when included, they appear for all rows with blank values for rows without a customer.
122-128: Add a doc comment toqueryCsvto complete the operation's documentation.The
queryoperation has detailed inline docs explaining CSV output and column layout, butqueryCsvcurrently has neither a doc comment nor a@summary(it's intentionally suppressed to avoid OpenAPI duplication). This creates a gap where some codegen toolchains may generate a separate symbol with no description at all. A brief doc comment linking back to thequeryoperation's full details would keep SDKs self-documenting and guard against codegen quirks.Suggested addition
`#suppress` "@openmeter/api-spec-aip/operation-summary" "Avoid duplicating the summary in OpenAPI yaml" `@extension`(Shared.PrivateExtension, true) `@extension`(Shared.UnstableExtension, true) `@extension`(Shared.InternalExtension, true) `@post` `@operationId`("query-meter") `@sharedRoute` + /** + * Query a meter for usage and download the result as CSV. + * See the `query` operation above for the full description and column layout. + */ queryCsv(🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/spec/packages/aip/src/meters/operations.tsp` around lines 122 - 128, Add a short doc comment to the queryCsv operation so generated SDKs get a description; specifically, place a brief comment above the queryCsv declaration that references the main query operation (e.g., mentions CSV output and column layout and points to the query operation details / operationId "query-meter" or symbol `query`) and optionally note that a `@summary` is intentionally suppressed—this should be a one- or two-line description linking back to `query` so codegen tools produce a non-empty docstring for `queryCsv`.api/v3/handlers/meters/query_csv.go (3)
109-118: Tiny nit: collect distinct IDs in one pass.
append+lo.Uniqworks, but on large result sets it allocates a slice proportional to row count before dedup. A smallmap[string]struct{}keeps it O(distinct) on both time and space — and reads just as clearly.♻️ Optional tidy
func collectCustomerIDs(rows []meter.MeterQueryRow) []string { - ids := make([]string, 0) - for _, row := range rows { - if row.CustomerID == nil { - continue - } - ids = append(ids, *row.CustomerID) - } - return lo.Uniq(ids) + seen := make(map[string]struct{}) + ids := make([]string, 0) + for _, row := range rows { + if row.CustomerID == nil { + continue + } + if _, ok := seen[*row.CustomerID]; ok { + continue + } + seen[*row.CustomerID] = struct{}{} + ids = append(ids, *row.CustomerID) + } + return ids }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/v3/handlers/meters/query_csv.go` around lines 109 - 118, collectCustomerIDs currently appends every non-nil CustomerID then calls lo.Uniq, which allocates proportional to row count; change it to collect unique IDs in one pass by using a map[string]struct{} inside collectCustomerIDs: iterate rows, skip nil CustomerID, set seen[*row.CustomerID] = struct{}{}, then build and return a slice of keys from the map (this keeps memory/time proportional to distinct IDs while preserving the function's output).
154-226: Heads-up on memory footprint for big exports.
Records()materializes the entire CSV as[][]stringin memory, which is on top of the already in-memoryrowsslice andcustomersByIDmap. For the JSON endpoint that's fine — you're producing JSON anyway — but CSV is the format people reach for precisely when they want large historical exports. With wide time ranges or high-cardinality group-bys this could be a noticeable allocator spike on a shared API process.Not a blocker for shipping — just worth keeping on the radar. If/when
commonhttp.CSVResponse(or a sibling) grows a streaming variant (Write(w *csv.Writer) error-ish), this handler is a prime candidate: write header, then stream each row, without holding the whole[][]string. You could also skip the intermediate row buffering andcsv.Writer.Flush()periodically.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/v3/handlers/meters/query_csv.go` around lines 154 - 226, Records() currently builds a full [][]string in memory (on top of queryMeterCSVResult.rows and customersByID) which can spike memory for large CSV exports; change to a streaming API: add a method like WriteCSV(w *csv.Writer) on queryMeterCSVResult that writes the header then iterates r.rows and writes each record directly (format WindowStart/WindowEnd, subject, customer id/key/name from r.customersByID, otherDimensions from r.GroupBy, and value) and periodically calls w.Flush()/check w.Error(); update the CSV handler to call queryMeterCSVResult.WriteCSV with the response writer or to use a streaming variant on commonhttp.CSVResponse instead of calling Records(), so we never materialize the entire [][]string.
154-162: Minor asymmetry: subject column detection vs customer column detection.Tiny inconsistency worth a quick look:
hasCustomerColumnsis decided by scanning actual rows for a non-nilCustomerID, whilehasSubjectColumnis decided purely by whetherquery.DimensionSubjectappears ingroupBy. If someone builds a params whereSubjectends up populated on rows without being in the requestedgroupBy(or vice versa — grouped by subject but all rows have nil Subject), the two code paths disagree on "presence".Probably fine given how
BuildQueryParamsworks today, but since the two are written right next to each other it reads as a small surprise. Consider aligning them — either both row-driven or both groupBy-driven — for future-proofing.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/v3/handlers/meters/query_csv.go` around lines 154 - 162, The subject vs customer presence detection in queryMeterCSVResult.Records() is inconsistent: hasCustomerColumns is derived by scanning r.rows for non-nil CustomerID but hasSubjectColumn is derived from query.DimensionSubject being in groupBy; make them symmetrical by changing hasSubjectColumn to also scan r.rows for non-nil Subject (i.e., iterate r.rows and set hasSubjectColumn = true if a row's Subject != nil), keeping the rest of the Records() logic the same and referencing the same symbols (Records(), r.rows, Subject, CustomerID) so presence is determined the same way for both columns.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/spec/packages/aip/src/meters/operations.tsp`:
- Around line 137-143: Update the CSV in the `@example` block so the time windows
are strictly increasing, non-overlapping, and consistently sized (e.g., 1-minute
buckets); specifically, correct the erroneous "to" timestamp in the second
example row (currently 2023-01-02T00:02:00Z) and adjust subsequent rows so each
row's from/to form consecutive 1-minute windows (e.g.,
2023-01-01T00:00:00Z→00:01:00Z, 00:01:00Z→00:02:00Z, 00:02:00Z→00:03:00Z) in the
`@example` CSV associated with the _: string; example.
- Around line 129-144: The TypeSpec operation queryCsv currently omits the
request body but the server handler QueryMeterCSV expects a MeterQueryRequest;
restore the body by adding "@body request: MeterQueryRequest" to the queryCsv
signature (so generated SDKs can send filters/groupBy/window sizes) or, if you
intentionally want CSV to be HTTP-only, add a clear docstring comment on
queryCsv stating that CSV requests do not accept a body and are unsupported by
SDKs—ensure the change aligns with the QueryMeterCSV handler behavior.
In `@api/v3/handlers/meters/query_csv.go`:
- Line 221: Replace fmt.Sprintf("%f", row.Value) with
strconv.FormatFloat(row.Value, 'f', -1, 64) when building the CSV record so
numbers are rendered without unnecessary trailing zeros; add an import for
"strconv" and remove "fmt" only if it becomes unused elsewhere (note the current
call sites: the record append using fmt.Sprintf and the row.Value identifier).
---
Nitpick comments:
In `@api/spec/packages/aip/src/meters/operations.tsp`:
- Around line 98-109: Update the doc comment describing CSV columns so the
behavior is unambiguous: change the sentence about the three customer_* columns
(near the CSV columns list in the comment) to state that the three customer_*
columns are included whenever any result row has an associated customer and,
when included, they appear for all rows with blank values for rows without a
customer.
- Around line 122-128: Add a short doc comment to the queryCsv operation so
generated SDKs get a description; specifically, place a brief comment above the
queryCsv declaration that references the main query operation (e.g., mentions
CSV output and column layout and points to the query operation details /
operationId "query-meter" or symbol `query`) and optionally note that a `@summary`
is intentionally suppressed—this should be a one- or two-line description
linking back to `query` so codegen tools produce a non-empty docstring for
`queryCsv`.
In `@api/v3/handlers/meters/query_csv.go`:
- Around line 109-118: collectCustomerIDs currently appends every non-nil
CustomerID then calls lo.Uniq, which allocates proportional to row count; change
it to collect unique IDs in one pass by using a map[string]struct{} inside
collectCustomerIDs: iterate rows, skip nil CustomerID, set seen[*row.CustomerID]
= struct{}{}, then build and return a slice of keys from the map (this keeps
memory/time proportional to distinct IDs while preserving the function's
output).
- Around line 154-226: Records() currently builds a full [][]string in memory
(on top of queryMeterCSVResult.rows and customersByID) which can spike memory
for large CSV exports; change to a streaming API: add a method like WriteCSV(w
*csv.Writer) on queryMeterCSVResult that writes the header then iterates r.rows
and writes each record directly (format WindowStart/WindowEnd, subject, customer
id/key/name from r.customersByID, otherDimensions from r.GroupBy, and value) and
periodically calls w.Flush()/check w.Error(); update the CSV handler to call
queryMeterCSVResult.WriteCSV with the response writer or to use a streaming
variant on commonhttp.CSVResponse instead of calling Records(), so we never
materialize the entire [][]string.
- Around line 154-162: The subject vs customer presence detection in
queryMeterCSVResult.Records() is inconsistent: hasCustomerColumns is derived by
scanning r.rows for non-nil CustomerID but hasSubjectColumn is derived from
query.DimensionSubject being in groupBy; make them symmetrical by changing
hasSubjectColumn to also scan r.rows for non-nil Subject (i.e., iterate r.rows
and set hasSubjectColumn = true if a row's Subject != nil), keeping the rest of
the Records() logic the same and referencing the same symbols (Records(),
r.rows, Subject, CustomerID) so presence is determined the same way for both
columns.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 7fc8c1ad-b78b-4dc2-ac08-5bd85672528c
⛔ Files ignored due to path filters (1)
api/v3/openapi.yamlis excluded by!**/openapi.yaml
📒 Files selected for processing (5)
api/spec/packages/aip/src/meters/operations.tspapi/v3/api.gen.goapi/v3/handlers/meters/handler.goapi/v3/handlers/meters/query_csv.goapi/v3/server/routes.go
69b7c2f to
bf9aec4
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
api/spec/packages/aip/src/meters/operations.tsp (2)
137-142:⚠️ Potential issue | 🟡 MinorThe CSV example windows are still inconsistent.
Line 140 jumps to
2023-01-02, while the surrounding rows look like consecutive one-minute buckets. Since this lands in user-facing docs, it’s worth keeping the sample monotonic and easy to scan.Suggested example cleanup
from,to,customer_id,customer_key,customer_name,model,type,value 2023-01-01T00:00:00Z,2023-01-01T00:01:00Z,01G65Z755AFWAKHE12NY0CQ9FH,acme-inc,Acme Inc.,gpt-4-turbo,input,12 - 2023-01-01T00:01:00Z,2023-01-02T00:02:00Z,01G65Z755AFWAKHE12NY0CQ9FH,acme-inc,Acme Inc.,gpt-4-turbo,input,20 - 2023-01-01T00:02:00Z,2023-01-02T00:03:00Z,01G65Z755B3YZ1KRA9W8V7PS2D,globex,Globex Corp,gpt-4-turbo,output,4 + 2023-01-01T00:01:00Z,2023-01-01T00:02:00Z,01G65Z755AFWAKHE12NY0CQ9FH,acme-inc,Acme Inc.,gpt-4-turbo,input,20 + 2023-01-01T00:02:00Z,2023-01-01T00:03:00Z,01G65Z755B3YZ1KRA9W8V7PS2D,globex,Globex Corp,gpt-4-turbo,output,4🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/spec/packages/aip/src/meters/operations.tsp` around lines 137 - 142, The CSV example inside the `@example`(...) block in operations.tsp has an inconsistent timestamp (the second row uses 2023-01-02) — update the timestamps so all rows form monotonic, consecutive one-minute buckets (e.g., 2023-01-01T00:00:00Z, 00:01:00Z, 00:02:00Z, 00:03:00Z) to make the sample easy to scan; edit the CSV rows in the `@example` block accordingly so the from/to windows are consecutive and consistent.
129-133:⚠️ Potential issue | 🟠 MajorThe CSV operation still needs the query request body.
The Go handler parses
api.MeterQueryRequestfrom the body before querying, so generated clients for this TypeSpec operation won’t be able to pass filters/dimensions/window settings as currently declared.Suggested fix
queryCsv( `@path` meterId: Shared.ULID, - // Note: to avoid generating anyOf in the OpenAPI yaml, we omit the request body - // `@body` request: MeterQueryRequest + `@body` request: MeterQueryRequest, ): {As per coding guidelines, "The declared API should be accurate, in parity with the actual implementation, and easy to understand for the user."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/spec/packages/aip/src/meters/operations.tsp` around lines 129 - 133, The CSV operation signature removed the request body but the Go handler expects api.MeterQueryRequest from the request body; restore the body parameter in the queryCsv operation so generated clients can supply filters/dimensions/window settings (e.g. add back a body param like `@body` request: api.MeterQueryRequest or `@body` request: MeterQueryRequest depending on the local TypeSpec alias used) and ensure the body type matches the Go handler's api.MeterQueryRequest.api/v3/handlers/meters/query_csv.go (1)
216-216:⚠️ Potential issue | 🟡 MinorAvoid padding CSV values with six decimal places.
%fturns values like12into12.000000. For exports, the shortest round-trippable representation is usually friendlier.Suggested tweak
import ( "context" "fmt" "net/http" "slices" + "strconv" "time" @@ - record = append(record, fmt.Sprintf("%f", row.Value)) + record = append(record, strconv.FormatFloat(row.Value, 'f', -1, 64))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/v3/handlers/meters/query_csv.go` at line 216, Replace the fixed-six-decimal formatting used when appending numeric CSV fields (the line that appends fmt.Sprintf("%f", row.Value) for row.Value) with a shortest-roundtrip float formatter (e.g., use the 'g' formatter or strconv.FormatFloat with format 'g' and precision -1) so values like 12 are emitted as "12" not "12.000000"; update the import list to include strconv if you choose strconv.FormatFloat and apply this change wherever record = append(record, fmt.Sprintf("%f", row.Value)) occurs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@api/spec/packages/aip/src/meters/operations.tsp`:
- Around line 107-108: Update the operations.tsp documentation so it matches the
CSV export behavior: state that customer_id, customer_key and customer_name are
emitted only when customer_id is present in the grouped dimensions (matching the
logic in the CSV handler), or alternatively change the CSV handler's condition
in the query_csv.go export logic to emit the three columns whenever any result
row has an associated customer; reference the CSV handler's grouping check (the
condition around customer_id in api/v3/handlers/meters/query_csv.go) and the
customer_* column descriptions in operations.tsp and make them consistent.
---
Duplicate comments:
In `@api/spec/packages/aip/src/meters/operations.tsp`:
- Around line 137-142: The CSV example inside the `@example`(...) block in
operations.tsp has an inconsistent timestamp (the second row uses 2023-01-02) —
update the timestamps so all rows form monotonic, consecutive one-minute buckets
(e.g., 2023-01-01T00:00:00Z, 00:01:00Z, 00:02:00Z, 00:03:00Z) to make the sample
easy to scan; edit the CSV rows in the `@example` block accordingly so the from/to
windows are consecutive and consistent.
- Around line 129-133: The CSV operation signature removed the request body but
the Go handler expects api.MeterQueryRequest from the request body; restore the
body parameter in the queryCsv operation so generated clients can supply
filters/dimensions/window settings (e.g. add back a body param like `@body`
request: api.MeterQueryRequest or `@body` request: MeterQueryRequest depending on
the local TypeSpec alias used) and ensure the body type matches the Go handler's
api.MeterQueryRequest.
In `@api/v3/handlers/meters/query_csv.go`:
- Line 216: Replace the fixed-six-decimal formatting used when appending numeric
CSV fields (the line that appends fmt.Sprintf("%f", row.Value) for row.Value)
with a shortest-roundtrip float formatter (e.g., use the 'g' formatter or
strconv.FormatFloat with format 'g' and precision -1) so values like 12 are
emitted as "12" not "12.000000"; update the import list to include strconv if
you choose strconv.FormatFloat and apply this change wherever record =
append(record, fmt.Sprintf("%f", row.Value)) occurs.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 239242e1-8506-4cd3-80af-88af6bc7ffc9
⛔ Files ignored due to path filters (1)
api/v3/openapi.yamlis excluded by!**/openapi.yaml
📒 Files selected for processing (7)
api/spec/packages/aip/src/meters/operations.tspapi/v3/api.gen.goapi/v3/handlers/meters/handler.goapi/v3/handlers/meters/query_csv.goapi/v3/server/routes.goopenmeter/meter/httphandler/query_csv.gopkg/framework/commonhttp/encoder.go
✅ Files skipped from review due to trivial changes (1)
- api/v3/api.gen.go
🚧 Files skipped from review as they are similar to previous changes (2)
- api/v3/handlers/meters/handler.go
- api/v3/server/routes.go
bf9aec4 to
cfbe2a2
Compare
Summary by CodeRabbit
New Features
Bug Fixes