metronome.go 12 KB

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