|
| 1 | +package meters |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "slices" |
| 8 | + "strconv" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/samber/lo" |
| 12 | + |
| 13 | + api "github.com/openmeterio/openmeter/api/v3" |
| 14 | + "github.com/openmeterio/openmeter/api/v3/apierrors" |
| 15 | + "github.com/openmeterio/openmeter/api/v3/handlers/meters/query" |
| 16 | + "github.com/openmeterio/openmeter/api/v3/request" |
| 17 | + "github.com/openmeterio/openmeter/openmeter/customer" |
| 18 | + "github.com/openmeterio/openmeter/openmeter/meter" |
| 19 | + "github.com/openmeterio/openmeter/pkg/framework/commonhttp" |
| 20 | + "github.com/openmeterio/openmeter/pkg/framework/transport/httptransport" |
| 21 | + "github.com/openmeterio/openmeter/pkg/models" |
| 22 | +) |
| 23 | + |
| 24 | +type ( |
| 25 | + QueryMeterCSVRequest = QueryMeterRequest |
| 26 | + QueryMeterCSVResponse = commonhttp.CSVResponse |
| 27 | + QueryMeterCSVParams = QueryMeterParams |
| 28 | + QueryMeterCSVHandler httptransport.HandlerWithArgs[QueryMeterCSVRequest, QueryMeterCSVResponse, QueryMeterCSVParams] |
| 29 | +) |
| 30 | + |
| 31 | +const ( |
| 32 | + csvColumnFrom = "from" |
| 33 | + csvColumnTo = "to" |
| 34 | + csvColumnValue = "value" |
| 35 | + csvColumnCustomerID = "customer_id" |
| 36 | + csvColumnCustomerKey = "customer_key" |
| 37 | + csvColumnCustomerName = "customer_name" |
| 38 | +) |
| 39 | + |
| 40 | +func (h *handler) QueryMeterCSV() QueryMeterCSVHandler { |
| 41 | + return httptransport.NewHandlerWithArgs( |
| 42 | + func(ctx context.Context, r *http.Request, meterID QueryMeterCSVParams) (QueryMeterCSVRequest, error) { |
| 43 | + ns, err := h.resolveNamespace(ctx) |
| 44 | + if err != nil { |
| 45 | + return QueryMeterCSVRequest{}, err |
| 46 | + } |
| 47 | + |
| 48 | + var body api.MeterQueryRequest |
| 49 | + if err := request.ParseBody(r, &body); err != nil { |
| 50 | + return QueryMeterCSVRequest{}, err |
| 51 | + } |
| 52 | + |
| 53 | + return QueryMeterCSVRequest{ |
| 54 | + NamespacedID: models.NamespacedID{ |
| 55 | + Namespace: ns, |
| 56 | + ID: meterID, |
| 57 | + }, |
| 58 | + Body: body, |
| 59 | + }, nil |
| 60 | + }, |
| 61 | + func(ctx context.Context, req QueryMeterCSVRequest) (QueryMeterCSVResponse, error) { |
| 62 | + m, err := h.service.GetMeterByIDOrSlug(ctx, meter.GetMeterInput{ |
| 63 | + Namespace: req.Namespace, |
| 64 | + IDOrSlug: req.ID, |
| 65 | + }) |
| 66 | + if err != nil { |
| 67 | + return nil, err |
| 68 | + } |
| 69 | + |
| 70 | + params, err := query.BuildQueryParams(ctx, m, req.Body, query.NewCustomerResolver(h.customerService)) |
| 71 | + if err != nil { |
| 72 | + return nil, err |
| 73 | + } |
| 74 | + |
| 75 | + rows, err := h.streaming.QueryMeter(ctx, req.Namespace, m, params) |
| 76 | + if err != nil { |
| 77 | + return nil, err |
| 78 | + } |
| 79 | + |
| 80 | + // Enrich with customer metadata (key, name) when any row has a CustomerID. |
| 81 | + customerIDs := collectCustomerIDs(rows) |
| 82 | + |
| 83 | + var customersByID map[string]customer.Customer |
| 84 | + if len(customerIDs) > 0 { |
| 85 | + result, err := h.customerService.ListCustomers(ctx, customer.ListCustomersInput{ |
| 86 | + Namespace: req.Namespace, |
| 87 | + CustomerIDs: customerIDs, |
| 88 | + }) |
| 89 | + if err != nil { |
| 90 | + return nil, fmt.Errorf("failed to list customers for csv enrichment: %w", err) |
| 91 | + } |
| 92 | + |
| 93 | + customersByID = lo.KeyBy(result.Items, func(c customer.Customer) string { |
| 94 | + return c.ID |
| 95 | + }) |
| 96 | + } |
| 97 | + |
| 98 | + return newQueryMeterCSVResult(m.Key, params.GroupBy, rows, customersByID), nil |
| 99 | + }, |
| 100 | + commonhttp.CSVResponseEncoder[QueryMeterCSVResponse], |
| 101 | + httptransport.AppendOptions( |
| 102 | + h.options, |
| 103 | + httptransport.WithOperationName("query-meter-csv"), |
| 104 | + httptransport.WithErrorEncoder(apierrors.GenericErrorEncoder()), |
| 105 | + )..., |
| 106 | + ) |
| 107 | +} |
| 108 | + |
| 109 | +// collectCustomerIDs returns the distinct non-nil customer IDs referenced by the rows. |
| 110 | +func collectCustomerIDs(rows []meter.MeterQueryRow) []string { |
| 111 | + ids := make([]string, 0) |
| 112 | + for _, row := range rows { |
| 113 | + if row.CustomerID == nil { |
| 114 | + continue |
| 115 | + } |
| 116 | + ids = append(ids, *row.CustomerID) |
| 117 | + } |
| 118 | + return lo.Uniq(ids) |
| 119 | +} |
| 120 | + |
| 121 | +// Column order: |
| 122 | +// |
| 123 | +// from, to, |
| 124 | +// [subject,] |
| 125 | +// [customer_id, customer_key, customer_name,] |
| 126 | +// <other dimensions...>, |
| 127 | +// value |
| 128 | +type queryMeterCSVResult struct { |
| 129 | + meterSlug string |
| 130 | + groupBy []string |
| 131 | + rows []meter.MeterQueryRow |
| 132 | + customersByID map[string]customer.Customer |
| 133 | +} |
| 134 | + |
| 135 | +var _ commonhttp.CSVResponse = &queryMeterCSVResult{} |
| 136 | + |
| 137 | +func newQueryMeterCSVResult( |
| 138 | + meterSlug string, |
| 139 | + groupBy []string, |
| 140 | + rows []meter.MeterQueryRow, |
| 141 | + customersByID map[string]customer.Customer, |
| 142 | +) *queryMeterCSVResult { |
| 143 | + return &queryMeterCSVResult{ |
| 144 | + meterSlug: meterSlug, |
| 145 | + groupBy: groupBy, |
| 146 | + rows: rows, |
| 147 | + customersByID: customersByID, |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +func (r *queryMeterCSVResult) FileName() string { |
| 152 | + return r.meterSlug |
| 153 | +} |
| 154 | + |
| 155 | +func (r *queryMeterCSVResult) Records() [][]string { |
| 156 | + hasSubjectColumn := slices.Contains(r.groupBy, query.DimensionSubject) |
| 157 | + hasCustomerColumns := slices.Contains(r.groupBy, query.DimensionCustomerID) |
| 158 | + |
| 159 | + otherDimensions := make([]string, 0, len(r.groupBy)) |
| 160 | + for _, k := range r.groupBy { |
| 161 | + switch k { |
| 162 | + case query.DimensionSubject, query.DimensionCustomerID: |
| 163 | + // Handled as reserved columns. |
| 164 | + default: |
| 165 | + otherDimensions = append(otherDimensions, k) |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + headers := []string{csvColumnFrom, csvColumnTo} |
| 170 | + if hasSubjectColumn { |
| 171 | + headers = append(headers, query.DimensionSubject) |
| 172 | + } |
| 173 | + if hasCustomerColumns { |
| 174 | + headers = append(headers, csvColumnCustomerID, csvColumnCustomerKey, csvColumnCustomerName) |
| 175 | + } |
| 176 | + headers = append(headers, otherDimensions...) |
| 177 | + headers = append(headers, csvColumnValue) |
| 178 | + |
| 179 | + records := make([][]string, 0, len(r.rows)+1) |
| 180 | + records = append(records, headers) |
| 181 | + |
| 182 | + for _, row := range r.rows { |
| 183 | + record := make([]string, 0, len(headers)) |
| 184 | + record = append(record, |
| 185 | + row.WindowStart.Format(time.RFC3339), |
| 186 | + row.WindowEnd.Format(time.RFC3339), |
| 187 | + ) |
| 188 | + |
| 189 | + if hasSubjectColumn { |
| 190 | + record = append(record, lo.FromPtrOr(row.Subject, "")) |
| 191 | + } |
| 192 | + |
| 193 | + if hasCustomerColumns { |
| 194 | + var id, key, name string |
| 195 | + if row.CustomerID != nil { |
| 196 | + id = *row.CustomerID |
| 197 | + if c, ok := r.customersByID[id]; ok { |
| 198 | + key = lo.FromPtrOr(c.Key, "") |
| 199 | + name = c.Name |
| 200 | + } |
| 201 | + } |
| 202 | + record = append(record, |
| 203 | + id, |
| 204 | + key, |
| 205 | + name, |
| 206 | + ) |
| 207 | + } |
| 208 | + |
| 209 | + for _, k := range otherDimensions { |
| 210 | + var v string |
| 211 | + if ptr, ok := row.GroupBy[k]; ok && ptr != nil { |
| 212 | + v = *ptr |
| 213 | + } |
| 214 | + record = append(record, v) |
| 215 | + } |
| 216 | + |
| 217 | + record = append(record, strconv.FormatFloat(row.Value, 'f', -1, 64)) |
| 218 | + records = append(records, record) |
| 219 | + } |
| 220 | + |
| 221 | + return records |
| 222 | +} |
0 commit comments