metronome.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. porterStandardTrialDays = 15
  20. defaultRewardAmountCents = 1000
  21. defaultPaidAmountCents = 0
  22. maxReferralRewards = 10
  23. )
  24. // MetronomeClient is the client used to call the Metronome API
  25. type MetronomeClient struct {
  26. ApiKey string
  27. billableMetrics []types.BillableMetric
  28. PorterCloudPlanID uuid.UUID
  29. PorterStandardPlanID uuid.UUID
  30. // DefaultRewardAmountCents is the default amount in USD cents rewarded to users
  31. // who successfully refer a new user
  32. DefaultRewardAmountCents float64
  33. // DefaultPaidAmountCents is the amount paid by the user to get the credits
  34. // grant, if set to 0 it means they are free
  35. DefaultPaidAmountCents float64
  36. // MaxReferralRewards is the maximum number of referral rewards a user can receive
  37. MaxReferralRewards int64
  38. }
  39. // NewMetronomeClient returns a new Metronome client
  40. func NewMetronomeClient(metronomeApiKey string, porterCloudPlanID string, porterStandardPlanID string) (client MetronomeClient, err error) {
  41. porterCloudPlanUUID, err := uuid.Parse(porterCloudPlanID)
  42. if err != nil {
  43. return client, err
  44. }
  45. porterStandardPlanUUID, err := uuid.Parse(porterStandardPlanID)
  46. if err != nil {
  47. return client, err
  48. }
  49. return MetronomeClient{
  50. ApiKey: metronomeApiKey,
  51. PorterCloudPlanID: porterCloudPlanUUID,
  52. PorterStandardPlanID: porterStandardPlanUUID,
  53. DefaultRewardAmountCents: defaultRewardAmountCents,
  54. DefaultPaidAmountCents: defaultPaidAmountCents,
  55. MaxReferralRewards: maxReferralRewards,
  56. }, nil
  57. }
  58. // CreateCustomerWithPlan will create the customer in Metronome and immediately add it to the plan
  59. 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) {
  60. ctx, span := telemetry.NewSpan(ctx, "add-metronome-customer-plan")
  61. defer span.End()
  62. var trialDays uint
  63. planID := m.PorterStandardPlanID
  64. projID := strconv.FormatUint(uint64(projectID), 10)
  65. if sandboxEnabled {
  66. planID = m.PorterCloudPlanID
  67. // This is necessary to avoid conflicts with Porter standard projects
  68. projID = fmt.Sprintf("porter-cloud-%s", projID)
  69. } else {
  70. trialDays = porterStandardTrialDays
  71. }
  72. customerID, err = m.createCustomer(ctx, userEmail, projectName, projID, billingID)
  73. if err != nil {
  74. return customerID, customerPlanID, telemetry.Error(ctx, span, err, fmt.Sprintf("error while creating customer with plan %s", planID))
  75. }
  76. customerPlanID, err = m.addCustomerPlan(ctx, customerID, planID, trialDays)
  77. return customerID, customerPlanID, err
  78. }
  79. // createCustomer will create the customer in Metronome
  80. func (m MetronomeClient) createCustomer(ctx context.Context, userEmail string, projectName string, projectID string, billingID string) (customerID uuid.UUID, err error) {
  81. ctx, span := telemetry.NewSpan(ctx, "create-metronome-customer")
  82. defer span.End()
  83. path := "customers"
  84. customer := types.Customer{
  85. Name: projectName,
  86. Aliases: []string{
  87. projectID,
  88. },
  89. BillingConfig: types.BillingConfig{
  90. BillingProviderType: "stripe",
  91. BillingProviderCustomerID: billingID,
  92. StripeCollectionMethod: defaultCollectionMethod,
  93. },
  94. CustomFields: map[string]string{
  95. "project_id": projectID,
  96. "user_email": userEmail,
  97. },
  98. }
  99. var result struct {
  100. Data types.Customer `json:"data"`
  101. }
  102. _, err = m.do(http.MethodPost, path, "", customer, &result)
  103. if err != nil {
  104. return customerID, telemetry.Error(ctx, span, err, "error creating customer")
  105. }
  106. return result.Data.ID, nil
  107. }
  108. // addCustomerPlan will start the customer on the given plan
  109. func (m MetronomeClient) addCustomerPlan(ctx context.Context, customerID uuid.UUID, planID uuid.UUID, trialDays uint) (customerPlanID uuid.UUID, err error) {
  110. ctx, span := telemetry.NewSpan(ctx, "add-metronome-customer-plan")
  111. defer span.End()
  112. if customerID == uuid.Nil || planID == uuid.Nil {
  113. return customerPlanID, telemetry.Error(ctx, span, err, "customer or plan id empty")
  114. }
  115. path := fmt.Sprintf("/customers/%s/plans/add", customerID)
  116. // Plan start time must be midnight UTC, formatted as RFC3339 timestamp
  117. now := time.Now()
  118. midnightUTC := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  119. startOn := midnightUTC.Format(time.RFC3339)
  120. req := types.AddCustomerPlanRequest{
  121. PlanID: planID,
  122. StartingOnUTC: startOn,
  123. }
  124. if trialDays != 0 {
  125. req.Trial = &types.TrialSpec{
  126. LengthInDays: int64(trialDays),
  127. }
  128. }
  129. var result struct {
  130. Data struct {
  131. CustomerPlanID uuid.UUID `json:"id"`
  132. } `json:"data"`
  133. }
  134. _, err = m.do(http.MethodPost, path, "", req, &result)
  135. if err != nil {
  136. return customerPlanID, telemetry.Error(ctx, span, err, "failed to add customer to plan")
  137. }
  138. return result.Data.CustomerPlanID, nil
  139. }
  140. // ListCustomerPlan will return the current active plan to which the user is subscribed
  141. func (m MetronomeClient) ListCustomerPlan(ctx context.Context, customerID uuid.UUID) (plan types.Plan, err error) {
  142. ctx, span := telemetry.NewSpan(ctx, "list-customer-plans")
  143. defer span.End()
  144. if customerID == uuid.Nil {
  145. return plan, telemetry.Error(ctx, span, err, "customer id empty")
  146. }
  147. path := fmt.Sprintf("/customers/%s/plans", customerID)
  148. var result struct {
  149. Data []types.Plan `json:"data"`
  150. }
  151. _, err = m.do(http.MethodGet, path, "", nil, &result)
  152. if err != nil {
  153. return plan, telemetry.Error(ctx, span, err, "failed to list customer plans")
  154. }
  155. if len(result.Data) > 0 {
  156. plan = result.Data[0]
  157. }
  158. return plan, nil
  159. }
  160. // EndCustomerPlan will immediately end the plan for the given customer
  161. func (m MetronomeClient) EndCustomerPlan(ctx context.Context, customerID uuid.UUID, customerPlanID uuid.UUID) (err error) {
  162. ctx, span := telemetry.NewSpan(ctx, "end-metronome-customer-plan")
  163. defer span.End()
  164. if customerID == uuid.Nil || customerPlanID == uuid.Nil {
  165. return telemetry.Error(ctx, span, err, "customer or customer plan id empty")
  166. }
  167. path := fmt.Sprintf("/customers/%s/plans/%s/end", customerID, customerPlanID)
  168. // Plan start time must be midnight UTC, formatted as RFC3339 timestamp
  169. now := time.Now()
  170. midnightUTC := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  171. endBefore := midnightUTC.Format(time.RFC3339)
  172. req := types.EndCustomerPlanRequest{
  173. EndingBeforeUTC: endBefore,
  174. }
  175. _, err = m.do(http.MethodPost, path, "", req, nil)
  176. if err != nil {
  177. return telemetry.Error(ctx, span, err, "failed to end customer plan")
  178. }
  179. return nil
  180. }
  181. // ListCustomerCredits will return the total number of credits for the customer
  182. func (m MetronomeClient) ListCustomerCredits(ctx context.Context, customerID uuid.UUID) (credits types.ListCreditGrantsResponse, err error) {
  183. ctx, span := telemetry.NewSpan(ctx, "list-customer-credits")
  184. defer span.End()
  185. if customerID == uuid.Nil {
  186. return credits, telemetry.Error(ctx, span, err, "customer id empty")
  187. }
  188. path := "credits/listGrants"
  189. req := types.ListCreditGrantsRequest{
  190. CustomerIDs: []uuid.UUID{
  191. customerID,
  192. },
  193. }
  194. var result struct {
  195. Data []types.CreditGrant `json:"data"`
  196. }
  197. _, err = m.do(http.MethodPost, path, "", req, &result)
  198. if err != nil {
  199. return credits, telemetry.Error(ctx, span, err, "failed to list customer credits")
  200. }
  201. var response types.ListCreditGrantsResponse
  202. for _, grant := range result.Data {
  203. response.GrantedCredits += grant.GrantAmount.Amount
  204. response.RemainingCredits += grant.Balance.IncludingPending
  205. }
  206. return response, nil
  207. }
  208. // CreateCreditsGrant will create a new credit grant for the customer with the specified amount
  209. func (m MetronomeClient) CreateCreditsGrant(ctx context.Context, customerID uuid.UUID, reason string, grantAmount float64, paidAmount float64, expiresAt string) (err error) {
  210. ctx, span := telemetry.NewSpan(ctx, "create-credits-grant")
  211. defer span.End()
  212. if customerID == uuid.Nil {
  213. return telemetry.Error(ctx, span, err, "customer id empty")
  214. }
  215. path := "credits/createGrant"
  216. creditTypeID, err := m.getCreditTypeID(ctx, "USD (cents)")
  217. if err != nil {
  218. return telemetry.Error(ctx, span, err, "failed to get credit type id")
  219. }
  220. req := types.CreateCreditsGrantRequest{
  221. CustomerID: customerID,
  222. UniquenessKey: uuid.NewString(),
  223. GrantAmount: types.GrantAmountID{
  224. Amount: grantAmount,
  225. CreditTypeID: creditTypeID,
  226. },
  227. PaidAmount: types.PaidAmount{
  228. Amount: paidAmount,
  229. CreditTypeID: creditTypeID,
  230. },
  231. Name: "Porter Credits",
  232. Reason: reason,
  233. ExpiresAt: expiresAt,
  234. Priority: 1,
  235. }
  236. statusCode, err := m.do(http.MethodPost, path, "", req, nil)
  237. if err != nil && statusCode != http.StatusConflict {
  238. // a conflict response indicates the grant already exists
  239. return telemetry.Error(ctx, span, err, "failed to create credits grant")
  240. }
  241. return nil
  242. }
  243. // ListCustomerUsage will return the aggregated usage for a customer
  244. func (m MetronomeClient) ListCustomerUsage(ctx context.Context, customerID uuid.UUID, startingOn string, endingBefore string, windowsSize string, currentPeriod bool) (usage []types.Usage, err error) {
  245. ctx, span := telemetry.NewSpan(ctx, "list-customer-usage")
  246. defer span.End()
  247. if customerID == uuid.Nil {
  248. return usage, telemetry.Error(ctx, span, err, "customer id empty")
  249. }
  250. if len(m.billableMetrics) == 0 {
  251. billableMetrics, err := m.listBillableMetricIDs(ctx, customerID)
  252. if err != nil {
  253. return nil, telemetry.Error(ctx, span, err, "failed to list billable metrics")
  254. }
  255. telemetry.WithAttributes(span,
  256. telemetry.AttributeKV{Key: "billable-metric-count", Value: len(billableMetrics)},
  257. )
  258. // Cache billable metric ids for future calls
  259. m.billableMetrics = append(m.billableMetrics, billableMetrics...)
  260. }
  261. path := "usage/groups"
  262. baseReq := types.ListCustomerUsageRequest{
  263. CustomerID: customerID,
  264. WindowSize: windowsSize,
  265. StartingOn: startingOn,
  266. EndingBefore: endingBefore,
  267. CurrentPeriod: currentPeriod,
  268. }
  269. for _, billableMetric := range m.billableMetrics {
  270. telemetry.WithAttributes(span,
  271. telemetry.AttributeKV{Key: "billable-metric-id", Value: billableMetric.ID},
  272. )
  273. var result struct {
  274. Data []types.CustomerUsageMetric `json:"data"`
  275. }
  276. baseReq.BillableMetricID = billableMetric.ID
  277. _, err = m.do(http.MethodPost, path, "", baseReq, &result)
  278. if err != nil {
  279. return usage, telemetry.Error(ctx, span, err, "failed to get customer usage")
  280. }
  281. usage = append(usage, types.Usage{
  282. MetricName: billableMetric.Name,
  283. UsageMetrics: result.Data,
  284. })
  285. }
  286. return usage, nil
  287. }
  288. // ListCustomerCosts will return the costs for a customer over a time period
  289. func (m MetronomeClient) ListCustomerCosts(ctx context.Context, customerID uuid.UUID, startingOn string, endingBefore string, limit int) (costs []types.FormattedCost, err error) {
  290. ctx, span := telemetry.NewSpan(ctx, "list-customer-costs")
  291. defer span.End()
  292. if customerID == uuid.Nil {
  293. return costs, telemetry.Error(ctx, span, err, "customer id empty")
  294. }
  295. path := fmt.Sprintf("customers/%s/costs", customerID)
  296. var result struct {
  297. Data []types.Cost `json:"data"`
  298. }
  299. queryParams := fmt.Sprintf("starting_on=%s&ending_before=%s&limit=%d", startingOn, endingBefore, limit)
  300. _, err = m.do(http.MethodGet, path, queryParams, nil, &result)
  301. if err != nil {
  302. return costs, telemetry.Error(ctx, span, err, "failed to create credits grant")
  303. }
  304. for _, customerCost := range result.Data {
  305. formattedCost := types.FormattedCost{
  306. StartTimestamp: customerCost.StartTimestamp,
  307. EndTimestamp: customerCost.EndTimestamp,
  308. }
  309. for _, creditType := range customerCost.CreditTypes {
  310. formattedCost.Cost += creditType.Cost
  311. }
  312. costs = append(costs, formattedCost)
  313. }
  314. return costs, nil
  315. }
  316. // IngestEvents sends a list of billing events to Metronome's ingest endpoint
  317. func (m MetronomeClient) IngestEvents(ctx context.Context, events []types.BillingEvent) (err error) {
  318. ctx, span := telemetry.NewSpan(ctx, "ingets-billing-events")
  319. defer span.End()
  320. if len(events) == 0 {
  321. return nil
  322. }
  323. path := "ingest"
  324. var currentAttempts int
  325. for currentAttempts < defaultMaxRetries {
  326. statusCode, err := m.do(http.MethodPost, path, "", events, nil)
  327. // Check errors that are not from error http codes
  328. if statusCode == 0 && err != nil {
  329. return telemetry.Error(ctx, span, err, "failed to ingest billing events")
  330. }
  331. if statusCode == http.StatusForbidden || statusCode == http.StatusUnauthorized {
  332. return telemetry.Error(ctx, span, err, "unauthorized")
  333. }
  334. // 400 responses should not be retried
  335. if statusCode == http.StatusBadRequest {
  336. return telemetry.Error(ctx, span, err, "malformed billing events")
  337. }
  338. // Any other status code can be safely retried
  339. if statusCode == 200 {
  340. return nil
  341. }
  342. currentAttempts++
  343. }
  344. return telemetry.Error(ctx, span, err, "max number of retry attempts reached with no success")
  345. }
  346. func (m MetronomeClient) listBillableMetricIDs(ctx context.Context, customerID uuid.UUID) (billableMetrics []types.BillableMetric, err error) {
  347. ctx, span := telemetry.NewSpan(ctx, "list-billable-metrics")
  348. defer span.End()
  349. if customerID == uuid.Nil {
  350. return billableMetrics, telemetry.Error(ctx, span, err, "customer id empty")
  351. }
  352. path := fmt.Sprintf("/customers/%s/billable-metrics", customerID)
  353. var result struct {
  354. Data []types.BillableMetric `json:"data"`
  355. }
  356. _, err = m.do(http.MethodGet, path, "", nil, &result)
  357. if err != nil {
  358. return billableMetrics, telemetry.Error(ctx, span, err, "failed to retrieve billable metrics from metronome")
  359. }
  360. return result.Data, nil
  361. }
  362. func (m MetronomeClient) getCreditTypeID(ctx context.Context, currencyCode string) (creditTypeID uuid.UUID, err error) {
  363. ctx, span := telemetry.NewSpan(ctx, "get-credit-type-id")
  364. defer span.End()
  365. path := "/credit-types/list"
  366. var result struct {
  367. Data []types.PricingUnit `json:"data"`
  368. }
  369. _, err = m.do(http.MethodGet, path, "", nil, &result)
  370. if err != nil {
  371. return creditTypeID, telemetry.Error(ctx, span, err, "failed to retrieve billable metrics from metronome")
  372. }
  373. for _, pricingUnit := range result.Data {
  374. if pricingUnit.Name == currencyCode {
  375. return pricingUnit.ID, nil
  376. }
  377. }
  378. return creditTypeID, telemetry.Error(ctx, span, fmt.Errorf("credit type not found for currency code %s", currencyCode), "failed to find credit type")
  379. }
  380. func (m MetronomeClient) do(method string, path string, queryParams string, body interface{}, data interface{}) (statusCode int, err error) {
  381. client := http.Client{}
  382. endpoint, err := url.JoinPath(metronomeBaseUrl, path)
  383. if err != nil {
  384. return statusCode, err
  385. }
  386. var bodyJson []byte
  387. if body != nil {
  388. bodyJson, err = json.Marshal(body)
  389. if err != nil {
  390. return statusCode, err
  391. }
  392. }
  393. // Add raw query parameters to the endpoint
  394. if queryParams != "" {
  395. endpoint += "?" + queryParams
  396. }
  397. req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(bodyJson))
  398. if err != nil {
  399. return statusCode, err
  400. }
  401. bearer := "Bearer " + m.ApiKey
  402. req.Header.Set("Authorization", bearer)
  403. req.Header.Set("Content-Type", "application/json")
  404. resp, err := client.Do(req)
  405. if err != nil {
  406. return statusCode, err
  407. }
  408. statusCode = resp.StatusCode
  409. if resp.StatusCode != http.StatusOK {
  410. // If there is an error, try to decode the message
  411. var message map[string]string
  412. err = json.NewDecoder(resp.Body).Decode(&message)
  413. if err != nil {
  414. return statusCode, fmt.Errorf("status code %d received, couldn't process response message", resp.StatusCode)
  415. }
  416. _ = resp.Body.Close()
  417. return statusCode, fmt.Errorf("status code %d received, response message: %v", resp.StatusCode, message)
  418. }
  419. if data != nil {
  420. err = json.NewDecoder(resp.Body).Decode(data)
  421. if err != nil {
  422. return statusCode, err
  423. }
  424. }
  425. _ = resp.Body.Close()
  426. return statusCode, nil
  427. }