metronome.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package billing
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "time"
  11. "github.com/google/uuid"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/internal/telemetry"
  14. )
  15. const (
  16. metronomeBaseUrl = "https://api.metronome.com/v1/"
  17. defaultCollectionMethod = "charge_automatically"
  18. defaultMaxRetries = 10
  19. )
  20. // MetronomeClient is the client used to call the Metronome API
  21. type MetronomeClient struct {
  22. ApiKey string
  23. billableMetrics []types.BillableMetric
  24. PorterCloudPlanID uuid.UUID
  25. PorterStandardPlanID uuid.UUID
  26. }
  27. // NewMetronomeClient returns a new Metronome client
  28. func NewMetronomeClient(metronomeApiKey string, porterCloudPlanID string, porterStandardPlanID string) (client MetronomeClient, err error) {
  29. porterCloudPlanUUID, err := uuid.Parse(porterCloudPlanID)
  30. if err != nil {
  31. return client, err
  32. }
  33. porterStandardPlanUUID, err := uuid.Parse(porterStandardPlanID)
  34. if err != nil {
  35. return client, err
  36. }
  37. return MetronomeClient{
  38. ApiKey: metronomeApiKey,
  39. PorterCloudPlanID: porterCloudPlanUUID,
  40. PorterStandardPlanID: porterStandardPlanUUID,
  41. }, nil
  42. }
  43. // CreateCustomerWithPlan will create the customer in Metronome and immediately add it to the plan
  44. func (m MetronomeClient) CreateCustomerWithPlan(ctx context.Context, userEmail string, projectName string, projectID uint, billingID string, sandboxEnabled bool) (customerID uuid.UUID, customerPlanID uuid.UUID, err error) {
  45. ctx, span := telemetry.NewSpan(ctx, "add-metronome-customer-plan")
  46. defer span.End()
  47. planID := m.PorterStandardPlanID
  48. projID := strconv.FormatUint(uint64(projectID), 10)
  49. if sandboxEnabled {
  50. planID = m.PorterCloudPlanID
  51. // This is necessary to avoid conflicts with Porter standard projects
  52. projID = fmt.Sprintf("porter-cloud-%s", projID)
  53. }
  54. customerID, err = m.createCustomer(ctx, userEmail, projectName, projID, billingID)
  55. if err != nil {
  56. return customerID, customerPlanID, telemetry.Error(ctx, span, err, fmt.Sprintf("error while creating customer with plan %s", planID))
  57. }
  58. customerPlanID, err = m.addCustomerPlan(ctx, customerID, planID)
  59. return customerID, customerPlanID, err
  60. }
  61. // createCustomer will create the customer in Metronome
  62. func (m MetronomeClient) createCustomer(ctx context.Context, userEmail string, projectName string, projectID string, billingID string) (customerID uuid.UUID, err error) {
  63. ctx, span := telemetry.NewSpan(ctx, "create-metronome-customer")
  64. defer span.End()
  65. path := "customers"
  66. customer := types.Customer{
  67. Name: projectName,
  68. Aliases: []string{
  69. projectID,
  70. },
  71. BillingConfig: types.BillingConfig{
  72. BillingProviderType: "stripe",
  73. BillingProviderCustomerID: billingID,
  74. StripeCollectionMethod: defaultCollectionMethod,
  75. },
  76. CustomFields: map[string]string{
  77. "project_id": projectID,
  78. "user_email": userEmail,
  79. },
  80. }
  81. var result struct {
  82. Data types.Customer `json:"data"`
  83. }
  84. _, err = m.do(http.MethodPost, path, customer, &result)
  85. if err != nil {
  86. return customerID, telemetry.Error(ctx, span, err, "error creating customer")
  87. }
  88. return result.Data.ID, nil
  89. }
  90. // addCustomerPlan will start the customer on the given plan
  91. func (m MetronomeClient) addCustomerPlan(ctx context.Context, customerID uuid.UUID, planID uuid.UUID) (customerPlanID uuid.UUID, err error) {
  92. ctx, span := telemetry.NewSpan(ctx, "add-metronome-customer-plan")
  93. defer span.End()
  94. if customerID == uuid.Nil || planID == uuid.Nil {
  95. return customerPlanID, telemetry.Error(ctx, span, err, "customer or plan id empty")
  96. }
  97. path := fmt.Sprintf("/customers/%s/plans/add", customerID)
  98. // Plan start time must be midnight UTC, formatted as RFC3339 timestamp
  99. now := time.Now()
  100. midnightUTC := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  101. startOn := midnightUTC.Format(time.RFC3339)
  102. req := types.AddCustomerPlanRequest{
  103. PlanID: planID,
  104. StartingOnUTC: startOn,
  105. }
  106. var result struct {
  107. Data struct {
  108. CustomerPlanID uuid.UUID `json:"id"`
  109. } `json:"data"`
  110. }
  111. _, err = m.do(http.MethodPost, path, req, &result)
  112. if err != nil {
  113. return customerPlanID, telemetry.Error(ctx, span, err, "failed to add customer to plan")
  114. }
  115. return result.Data.CustomerPlanID, nil
  116. }
  117. // ListCustomerPlan will return the current active plan to which the user is subscribed
  118. func (m MetronomeClient) ListCustomerPlan(ctx context.Context, customerID uuid.UUID) (plan types.Plan, err error) {
  119. ctx, span := telemetry.NewSpan(ctx, "list-customer-plans")
  120. defer span.End()
  121. if customerID == uuid.Nil {
  122. return plan, telemetry.Error(ctx, span, err, "customer id empty")
  123. }
  124. path := fmt.Sprintf("/customers/%s/plans", customerID)
  125. var result struct {
  126. Data []types.Plan `json:"data"`
  127. }
  128. _, err = m.do(http.MethodGet, path, nil, &result)
  129. if err != nil {
  130. return plan, telemetry.Error(ctx, span, err, "failed to list customer plans")
  131. }
  132. if len(result.Data) > 0 {
  133. plan = result.Data[0]
  134. }
  135. return plan, nil
  136. }
  137. // EndCustomerPlan will immediately end the plan for the given customer
  138. func (m MetronomeClient) EndCustomerPlan(ctx context.Context, customerID uuid.UUID, customerPlanID uuid.UUID) (err error) {
  139. ctx, span := telemetry.NewSpan(ctx, "end-metronome-customer-plan")
  140. defer span.End()
  141. if customerID == uuid.Nil || customerPlanID == uuid.Nil {
  142. return telemetry.Error(ctx, span, err, "customer or customer plan id empty")
  143. }
  144. path := fmt.Sprintf("/customers/%s/plans/%s/end", customerID, customerPlanID)
  145. // Plan start time must be midnight UTC, formatted as RFC3339 timestamp
  146. now := time.Now()
  147. midnightUTC := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  148. endBefore := midnightUTC.Format(time.RFC3339)
  149. req := types.EndCustomerPlanRequest{
  150. EndingBeforeUTC: endBefore,
  151. }
  152. _, err = m.do(http.MethodPost, path, req, nil)
  153. if err != nil {
  154. return telemetry.Error(ctx, span, err, "failed to end customer plan")
  155. }
  156. return nil
  157. }
  158. // ListCustomerCredits will return the total number of credits for the customer
  159. func (m MetronomeClient) ListCustomerCredits(ctx context.Context, customerID uuid.UUID) (credits types.ListCreditGrantsResponse, err error) {
  160. ctx, span := telemetry.NewSpan(ctx, "list-customer-credits")
  161. defer span.End()
  162. if customerID == uuid.Nil {
  163. return credits, telemetry.Error(ctx, span, err, "customer id empty")
  164. }
  165. path := "credits/listGrants"
  166. req := types.ListCreditGrantsRequest{
  167. CustomerIDs: []uuid.UUID{
  168. customerID,
  169. },
  170. }
  171. var result struct {
  172. Data []types.CreditGrant `json:"data"`
  173. }
  174. _, err = m.do(http.MethodPost, path, req, &result)
  175. if err != nil {
  176. return credits, telemetry.Error(ctx, span, err, "failed to list customer credits")
  177. }
  178. var response types.ListCreditGrantsResponse
  179. for _, grant := range result.Data {
  180. response.GrantedCredits += grant.GrantAmount.Amount
  181. response.RemainingCredits += grant.Balance.IncludingPending
  182. }
  183. return response, nil
  184. }
  185. // ListCustomerUsage will return the aggregated usage for a customer
  186. func (m MetronomeClient) ListCustomerUsage(ctx context.Context, customerID uuid.UUID, startingOn string, endingBefore string, windowsSize string, currentPeriod bool) (usage []types.Usage, err error) {
  187. ctx, span := telemetry.NewSpan(ctx, "list-customer-usage")
  188. defer span.End()
  189. if customerID == uuid.Nil {
  190. return usage, telemetry.Error(ctx, span, err, "customer id empty")
  191. }
  192. if len(m.billableMetrics) == 0 {
  193. billableMetrics, err := m.listBillableMetricIDs(ctx, customerID)
  194. if err != nil {
  195. return nil, telemetry.Error(ctx, span, err, "failed to list billable metrics")
  196. }
  197. telemetry.WithAttributes(span,
  198. telemetry.AttributeKV{Key: "billable-metric-count", Value: len(billableMetrics)},
  199. )
  200. // Cache billable metric ids for future calls
  201. m.billableMetrics = append(m.billableMetrics, billableMetrics...)
  202. }
  203. path := "usage/groups"
  204. baseReq := types.ListCustomerUsageRequest{
  205. CustomerID: customerID,
  206. WindowSize: windowsSize,
  207. StartingOn: startingOn,
  208. EndingBefore: endingBefore,
  209. CurrentPeriod: currentPeriod,
  210. }
  211. for _, billableMetric := range m.billableMetrics {
  212. telemetry.WithAttributes(span,
  213. telemetry.AttributeKV{Key: "billable-metric-id", Value: billableMetric.ID},
  214. )
  215. var result struct {
  216. Data []types.CustomerUsageMetric `json:"data"`
  217. }
  218. baseReq.BillableMetricID = billableMetric.ID
  219. _, err = m.do(http.MethodPost, path, baseReq, &result)
  220. if err != nil {
  221. return usage, telemetry.Error(ctx, span, err, "failed to get customer usage")
  222. }
  223. usage = append(usage, types.Usage{
  224. MetricName: billableMetric.Name,
  225. UsageMetrics: result.Data,
  226. })
  227. }
  228. return usage, nil
  229. }
  230. // IngestEvents sends a list of billing events to Metronome's ingest endpoint
  231. func (m MetronomeClient) IngestEvents(ctx context.Context, events []types.BillingEvent) (err error) {
  232. ctx, span := telemetry.NewSpan(ctx, "ingets-billing-events")
  233. defer span.End()
  234. if len(events) == 0 {
  235. return nil
  236. }
  237. path := "ingest"
  238. var currentAttempts int
  239. for currentAttempts < defaultMaxRetries {
  240. statusCode, err := m.do(http.MethodPost, path, events, nil)
  241. // Check errors that are not from error http codes
  242. if statusCode == 0 && err != nil {
  243. return telemetry.Error(ctx, span, err, "failed to ingest billing events")
  244. }
  245. if statusCode == http.StatusForbidden || statusCode == http.StatusUnauthorized {
  246. return telemetry.Error(ctx, span, err, "unauthorized")
  247. }
  248. // 400 responses should not be retried
  249. if statusCode == http.StatusBadRequest {
  250. return telemetry.Error(ctx, span, err, "malformed billing events")
  251. }
  252. // Any other status code can be safely retried
  253. if statusCode == 200 {
  254. return nil
  255. }
  256. currentAttempts++
  257. }
  258. return telemetry.Error(ctx, span, err, "max number of retry attempts reached with no success")
  259. }
  260. func (m MetronomeClient) listBillableMetricIDs(ctx context.Context, customerID uuid.UUID) (billableMetrics []types.BillableMetric, err error) {
  261. ctx, span := telemetry.NewSpan(ctx, "list-billable-metrics")
  262. defer span.End()
  263. if customerID == uuid.Nil {
  264. return billableMetrics, telemetry.Error(ctx, span, err, "customer id empty")
  265. }
  266. path := fmt.Sprintf("/customers/%s/billable-metrics", customerID)
  267. var result struct {
  268. Data []types.BillableMetric `json:"data"`
  269. }
  270. _, err = m.do(http.MethodGet, path, nil, &result)
  271. if err != nil {
  272. return billableMetrics, telemetry.Error(ctx, span, err, "failed to retrieve billable metrics from metronome")
  273. }
  274. return result.Data, nil
  275. }
  276. func (m MetronomeClient) do(method string, path string, body interface{}, data interface{}) (statusCode int, err error) {
  277. client := http.Client{}
  278. endpoint, err := url.JoinPath(metronomeBaseUrl, path)
  279. if err != nil {
  280. return statusCode, err
  281. }
  282. var bodyJson []byte
  283. if body != nil {
  284. bodyJson, err = json.Marshal(body)
  285. if err != nil {
  286. return statusCode, err
  287. }
  288. }
  289. req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(bodyJson))
  290. if err != nil {
  291. return statusCode, err
  292. }
  293. bearer := "Bearer " + m.ApiKey
  294. req.Header.Set("Authorization", bearer)
  295. req.Header.Set("Content-Type", "application/json")
  296. resp, err := client.Do(req)
  297. if err != nil {
  298. return statusCode, err
  299. }
  300. statusCode = resp.StatusCode
  301. if resp.StatusCode != http.StatusOK {
  302. // If there is an error, try to decode the message
  303. var message map[string]string
  304. err = json.NewDecoder(resp.Body).Decode(&message)
  305. if err != nil {
  306. return statusCode, fmt.Errorf("status code %d received, couldn't process response message", resp.StatusCode)
  307. }
  308. _ = resp.Body.Close()
  309. return statusCode, fmt.Errorf("status code %d received, response message: %v", resp.StatusCode, message)
  310. }
  311. if data != nil {
  312. err = json.NewDecoder(resp.Body).Decode(data)
  313. if err != nil {
  314. return statusCode, err
  315. }
  316. }
  317. _ = resp.Body.Close()
  318. return statusCode, nil
  319. }