usage.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. package billing
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/getlago/lago-go-client"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/telemetry"
  13. )
  14. const (
  15. defaultStarterCreditsCents = 500
  16. defaultRewardAmountCents = 1000
  17. maxReferralRewards = 10
  18. defaultMaxRetries = 10
  19. maxIngestEventLimit = 100
  20. // porterStandardTrialDays is the number of days for the trial
  21. porterStandardTrialDays = 15
  22. // These prefixes are used to build the customer and subscription IDs
  23. // in Lago. This way we can reuse the project IDs instead of storing
  24. // the Lago IDs in the database.
  25. // TrialIDPrefix is the prefix for the trial ID
  26. TrialIDPrefix = "trial"
  27. // SubscriptionIDPrefix is the prefix for the subscription ID
  28. SubscriptionIDPrefix = "sub"
  29. // CustomerIDPrefix is the prefix for the customer ID
  30. CustomerIDPrefix = "cus"
  31. )
  32. // LagoClient is the client used to call the Lago API
  33. type LagoClient struct {
  34. client lago.Client
  35. lagoApiKey string
  36. PorterCloudPlanCode string
  37. PorterStandardPlanCode string
  38. PorterTrialCode string
  39. // DefaultRewardAmountCents is the default amount in USD cents rewarded to users
  40. // who successfully refer a new user
  41. DefaultRewardAmountCents int64
  42. // MaxReferralRewards is the maximum number of referral rewards a user can receive
  43. MaxReferralRewards int64
  44. }
  45. // NewLagoClient returns a new Lago client
  46. func NewLagoClient(lagoApiKey string, porterCloudPlanCode string, porterStandardPlanCode string, porterTrialCode string) (client LagoClient, err error) {
  47. lagoClient := lago.New().SetApiKey(lagoApiKey)
  48. if lagoClient == nil {
  49. return client, fmt.Errorf("failed to create lago client")
  50. }
  51. // lagoClient.Debug = true
  52. return LagoClient{
  53. lagoApiKey: lagoApiKey,
  54. client: *lagoClient,
  55. PorterCloudPlanCode: porterCloudPlanCode,
  56. PorterStandardPlanCode: porterStandardPlanCode,
  57. PorterTrialCode: porterTrialCode,
  58. DefaultRewardAmountCents: defaultRewardAmountCents,
  59. MaxReferralRewards: maxReferralRewards,
  60. }, nil
  61. }
  62. // CreateCustomerWithPlan will create the customer in Lago and immediately add it to the plan
  63. func (m LagoClient) CreateCustomerWithPlan(ctx context.Context, userEmail string, projectName string, projectID uint, billingID string, sandboxEnabled bool) (err error) {
  64. ctx, span := telemetry.NewSpan(ctx, "add-lago-customer-plan")
  65. defer span.End()
  66. if projectID == 0 {
  67. return telemetry.Error(ctx, span, err, "project id empty")
  68. }
  69. customerID, err := m.createCustomer(ctx, userEmail, projectName, projectID, billingID, sandboxEnabled)
  70. if err != nil {
  71. return telemetry.Error(ctx, span, err, "error while creating customer")
  72. }
  73. trialID := m.generateLagoID(TrialIDPrefix, projectID, sandboxEnabled)
  74. subscriptionID := m.generateLagoID(SubscriptionIDPrefix, projectID, sandboxEnabled)
  75. // The dates need to be at midnight UTC
  76. now := time.Now().UTC()
  77. now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
  78. trialEndTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).Add(time.Hour * 24 * porterStandardTrialDays).UTC()
  79. if sandboxEnabled {
  80. err = m.addCustomerPlan(ctx, customerID, m.PorterCloudPlanCode, subscriptionID, &now, nil)
  81. if err != nil {
  82. return telemetry.Error(ctx, span, err, fmt.Sprintf("error while adding customer to plan %s", m.PorterCloudPlanCode))
  83. }
  84. starterWalletName := "Free Starter Credits"
  85. expiresAt := time.Now().UTC().AddDate(0, 1, 0).Truncate(24 * time.Hour)
  86. err = m.CreateCreditsGrant(ctx, projectID, starterWalletName, defaultStarterCreditsCents, &expiresAt, sandboxEnabled)
  87. return nil
  88. }
  89. // First, start the new customer on the trial
  90. err = m.addCustomerPlan(ctx, customerID, m.PorterTrialCode, trialID, &now, &trialEndTime)
  91. if err != nil {
  92. return telemetry.Error(ctx, span, err, fmt.Sprintf("error while starting customer trial %s", m.PorterTrialCode))
  93. }
  94. // Then, add the customer to the actual plan. The date of the subscription will be the end of the trial
  95. err = m.addCustomerPlan(ctx, customerID, m.PorterStandardPlanCode, subscriptionID, &trialEndTime, nil)
  96. if err != nil {
  97. return telemetry.Error(ctx, span, err, fmt.Sprintf("error while adding customer to plan %s", m.PorterStandardPlanCode))
  98. }
  99. return err
  100. }
  101. func (m LagoClient) CheckIfCustomerExists(ctx context.Context, projectID uint, enableSandbox bool) (exists bool, err error) {
  102. ctx, span := telemetry.NewSpan(ctx, "check-lago-customer-exists")
  103. defer span.End()
  104. if projectID == 0 {
  105. return exists, telemetry.Error(ctx, span, err, "project id empty")
  106. }
  107. customerID := m.generateLagoID(CustomerIDPrefix, projectID, enableSandbox)
  108. _, lagoErr := m.client.Customer().Get(ctx, customerID)
  109. if lagoErr != nil {
  110. return exists, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to get customer")
  111. }
  112. return true, nil
  113. }
  114. func (m LagoClient) GetCustomeActivePlan(ctx context.Context, projectID uint, sandboxEnabled bool) (plan types.Plan, err error) {
  115. ctx, span := telemetry.NewSpan(ctx, "get-active-subscription")
  116. defer span.End()
  117. if projectID == 0 {
  118. return plan, telemetry.Error(ctx, span, err, "project id empty")
  119. }
  120. if sandboxEnabled {
  121. subscriptionID := m.generateLagoID(SubscriptionIDPrefix, projectID, sandboxEnabled)
  122. return types.Plan{ID: subscriptionID}, nil
  123. }
  124. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  125. subscriptionListInput := lago.SubscriptionListInput{
  126. ExternalCustomerID: customerID,
  127. }
  128. activeSubscriptions, lagoErr := m.client.Subscription().GetList(ctx, subscriptionListInput)
  129. if lagoErr != nil {
  130. return plan, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to get active subscription")
  131. }
  132. if activeSubscriptions == nil {
  133. return plan, telemetry.Error(ctx, span, err, "no active subscriptions found")
  134. }
  135. for _, subscription := range activeSubscriptions.Subscriptions {
  136. if subscription.Status != lago.SubscriptionStatusActive {
  137. continue
  138. }
  139. plan.ID = subscription.ExternalID
  140. plan.CustomerID = subscription.ExternalCustomerID
  141. plan.StartingOn = subscription.SubscriptionAt.Format(time.RFC3339)
  142. plan.EndingBefore = subscription.EndingAt.Format(time.RFC3339)
  143. if strings.Contains(subscription.ExternalID, TrialIDPrefix) {
  144. plan.TrialInfo.EndingBefore = subscription.EndingAt.Format(time.RFC3339)
  145. }
  146. break
  147. }
  148. return plan, nil
  149. }
  150. // EndCustomerPlan will immediately end the plan for the given customer
  151. func (m LagoClient) EndCustomerPlan(ctx context.Context, projectID uint) (err error) {
  152. ctx, span := telemetry.NewSpan(ctx, "end-lago-customer-plan")
  153. defer span.End()
  154. if projectID == 0 {
  155. return telemetry.Error(ctx, span, err, "subscription id empty")
  156. }
  157. subscriptionID := m.generateLagoID(SubscriptionIDPrefix, projectID, false)
  158. subscriptionTerminateInput := lago.SubscriptionTerminateInput{
  159. ExternalID: subscriptionID,
  160. }
  161. _, lagoErr := m.client.Subscription().Terminate(ctx, subscriptionTerminateInput)
  162. if lagoErr != nil {
  163. return telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to terminate subscription")
  164. }
  165. return nil
  166. }
  167. // ListCustomerCredits will return the total number of credits for the customer
  168. func (m LagoClient) ListCustomerCredits(ctx context.Context, projectID uint, sandboxEnabled bool) (credits types.ListCreditGrantsResponse, err error) {
  169. ctx, span := telemetry.NewSpan(ctx, "list-customer-credits")
  170. defer span.End()
  171. if projectID == 0 {
  172. return credits, telemetry.Error(ctx, span, err, "project id empty")
  173. }
  174. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  175. // We manually do the request in this function because the Lago client has an issue
  176. // with types for this specific request
  177. lagoBaseURL := "https://api.getlago.com"
  178. url := fmt.Sprintf("%s/api/v1/wallets?external_customer_id=%s", lagoBaseURL, customerID)
  179. req, err := http.NewRequest("GET", url, nil)
  180. if err != nil {
  181. return credits, telemetry.Error(ctx, span, err, "failed to create wallets request")
  182. }
  183. req.Header.Set("Authorization", "Bearer "+m.lagoApiKey)
  184. client := &http.Client{}
  185. resp, err := client.Do(req)
  186. if err != nil {
  187. return credits, telemetry.Error(ctx, span, err, "failed to get customer credits")
  188. }
  189. defer resp.Body.Close()
  190. type ListWalletsResponse struct {
  191. Wallets []types.Wallet `json:"wallets"`
  192. }
  193. var walletList ListWalletsResponse
  194. err = json.NewDecoder(resp.Body).Decode(&walletList)
  195. if err != nil {
  196. return credits, telemetry.Error(ctx, span, err, "failed to decode wallet list response")
  197. }
  198. var response types.ListCreditGrantsResponse
  199. for _, wallet := range walletList.Wallets {
  200. if wallet.Status != string(lago.Active) {
  201. continue
  202. }
  203. response.GrantedBalanceCents += wallet.BalanceCents
  204. response.RemainingBalanceCents += wallet.OngoingBalanceCents
  205. }
  206. return response, nil
  207. }
  208. // CreateCreditsGrant will create a new credit grant for the customer with the specified amount
  209. func (m LagoClient) CreateCreditsGrant(ctx context.Context, projectID uint, name string, grantAmount int64, expiresAt *time.Time, sandboxEnabled bool) (err error) {
  210. ctx, span := telemetry.NewSpan(ctx, "create-credits-grant")
  211. defer span.End()
  212. if projectID == 0 {
  213. return telemetry.Error(ctx, span, err, "project id empty")
  214. }
  215. customerID := m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  216. walletInput := &lago.WalletInput{
  217. ExternalCustomerID: customerID,
  218. Name: name,
  219. Currency: lago.USD,
  220. GrantedCredits: strconv.FormatInt(grantAmount, 10),
  221. // Rate is 1 credit = 1 cent
  222. RateAmount: "0.01",
  223. ExpirationAt: expiresAt,
  224. }
  225. _, lagoErr := m.client.Wallet().Create(ctx, walletInput)
  226. if lagoErr != nil {
  227. return telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to create credits grant")
  228. }
  229. return nil
  230. }
  231. // ListCustomerUsage will return the aggregated usage for a customer
  232. func (m LagoClient) ListCustomerUsage(ctx context.Context, customerID string, subscriptionID string, currentPeriod bool) (usage types.Usage, err error) {
  233. ctx, span := telemetry.NewSpan(ctx, "list-customer-usage")
  234. defer span.End()
  235. if subscriptionID == "" {
  236. return usage, telemetry.Error(ctx, span, err, "subscription id empty")
  237. }
  238. if currentPeriod {
  239. customerUsageInput := &lago.CustomerUsageInput{
  240. ExternalSubscriptionID: subscriptionID,
  241. }
  242. currentUsage, lagoErr := m.client.Customer().CurrentUsage(ctx, customerID, customerUsageInput)
  243. if lagoErr != nil {
  244. return usage, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to get customer usage")
  245. }
  246. usage.FromDatetime = currentUsage.FromDatetime.Format(time.RFC3339)
  247. usage.ToDatetime = currentUsage.ToDatetime.Format(time.RFC3339)
  248. usage.TotalAmountCents = int64(currentUsage.TotalAmountCents)
  249. usage.ChargesUsage = make([]types.ChargeUsage, len(currentUsage.ChargesUsage))
  250. for i, charge := range currentUsage.ChargesUsage {
  251. usage.ChargesUsage[i] = types.ChargeUsage{
  252. Units: charge.Units,
  253. AmountCents: int64(charge.AmountCents),
  254. AmountCurrency: string(charge.AmountCurrency),
  255. BillableMetric: types.BillableMetric{
  256. Name: charge.BillableMetric.Name,
  257. },
  258. }
  259. }
  260. }
  261. return usage, nil
  262. }
  263. // IngestEvents sends a list of billing events to Lago's ingest endpoint
  264. func (m LagoClient) IngestEvents(ctx context.Context, subscriptionID string, events []types.BillingEvent, enableSandbox bool) (err error) {
  265. ctx, span := telemetry.NewSpan(ctx, "ingets-billing-events")
  266. defer span.End()
  267. if len(events) == 0 {
  268. return nil
  269. }
  270. for i := 0; i < len(events); i += maxIngestEventLimit {
  271. end := i + maxIngestEventLimit
  272. if end > len(events) {
  273. end = len(events)
  274. }
  275. batch := events[i:end]
  276. batchInput := make([]lago.EventInput, len(batch))
  277. for i := range batch {
  278. externalSubscriptionID := subscriptionID
  279. if enableSandbox {
  280. // This hack has to be done because we can't infer the project id from the
  281. // context in Porter Cloud
  282. customerID, err := strconv.ParseUint(batch[i].CustomerID, 10, 64)
  283. if err != nil {
  284. return telemetry.Error(ctx, span, err, "failed to parse customer ID")
  285. }
  286. externalSubscriptionID = m.generateLagoID(SubscriptionIDPrefix, uint(customerID), enableSandbox)
  287. }
  288. event := lago.EventInput{
  289. TransactionID: batch[i].TransactionID,
  290. ExternalSubscriptionID: externalSubscriptionID,
  291. Code: batch[i].EventType,
  292. Timestamp: batch[i].Timestamp,
  293. Properties: batch[i].Properties,
  294. }
  295. batchInput = append(batchInput, event)
  296. }
  297. // Retry each batch to make sure all events are ingested
  298. var currentAttempts int
  299. for currentAttempts < defaultMaxRetries {
  300. m.client.Event().Batch(ctx, &batchInput)
  301. currentAttempts++
  302. }
  303. if currentAttempts == defaultMaxRetries {
  304. return telemetry.Error(ctx, span, err, "max number of retry attempts reached with no success")
  305. }
  306. }
  307. return nil
  308. }
  309. // ListCustomerFinalizedInvoices will return all finalized invoices for the customer
  310. func (m LagoClient) ListCustomerFinalizedInvoices(ctx context.Context, projectID uint, enableSandbox bool) (invoiceList []types.Invoice, err error) {
  311. ctx, span := telemetry.NewSpan(ctx, "list-customer-invoices")
  312. defer span.End()
  313. if projectID == 0 {
  314. return invoiceList, telemetry.Error(ctx, span, err, "project id cannot be empty")
  315. }
  316. customerID := m.generateLagoID(CustomerIDPrefix, projectID, enableSandbox)
  317. invoiceListInput := &lago.InvoiceListInput{
  318. ExternalCustomerID: customerID,
  319. Status: lago.InvoiceStatusFinalized,
  320. }
  321. invoices, lagoErr := m.client.Invoice().GetList(ctx, invoiceListInput)
  322. if lagoErr != nil {
  323. return invoiceList, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to list invoices")
  324. }
  325. for _, invoice := range invoices.Invoices {
  326. invoiceReq, lagoErr := m.client.Invoice().Download(ctx, invoice.LagoID.String())
  327. if lagoErr != nil {
  328. return invoiceList, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to download invoice")
  329. }
  330. var fileURL string
  331. if invoiceReq == nil {
  332. fileURL = invoice.FileURL
  333. } else {
  334. fileURL = invoiceReq.FileURL
  335. }
  336. invoiceList = append(invoiceList, types.Invoice{
  337. HostedInvoiceURL: fileURL,
  338. Status: string(invoice.Status),
  339. Created: invoice.IssuingDate,
  340. })
  341. }
  342. return invoiceList, nil
  343. }
  344. // createCustomer will create the customer in Lago
  345. func (m LagoClient) createCustomer(ctx context.Context, userEmail string, projectName string, projectID uint, billingID string, sandboxEnabled bool) (customerID string, err error) {
  346. ctx, span := telemetry.NewSpan(ctx, "create-lago-customer")
  347. defer span.End()
  348. customerID = m.generateLagoID(CustomerIDPrefix, projectID, sandboxEnabled)
  349. customerInput := &lago.CustomerInput{
  350. ExternalID: customerID,
  351. Name: projectName,
  352. Email: userEmail,
  353. BillingConfiguration: lago.CustomerBillingConfigurationInput{
  354. PaymentProvider: lago.PaymentProviderStripe,
  355. ProviderCustomerID: billingID,
  356. Sync: false,
  357. SyncWithProvider: false,
  358. },
  359. }
  360. _, lagoErr := m.client.Customer().Create(ctx, customerInput)
  361. if lagoErr != nil {
  362. return customerID, telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to create lago customer")
  363. }
  364. return customerID, nil
  365. }
  366. // addCustomerPlan will create a plan subscription for the customer
  367. func (m LagoClient) addCustomerPlan(ctx context.Context, customerID string, planID string, subscriptionID string, startingAt *time.Time, endingAt *time.Time) (err error) {
  368. ctx, span := telemetry.NewSpan(ctx, "add-lago-customer-plan")
  369. defer span.End()
  370. if customerID == "" || planID == "" {
  371. return telemetry.Error(ctx, span, err, "project and plan id are required")
  372. }
  373. subscriptionInput := &lago.SubscriptionInput{
  374. ExternalCustomerID: customerID,
  375. ExternalID: subscriptionID,
  376. PlanCode: planID,
  377. SubscriptionAt: startingAt,
  378. EndingAt: endingAt,
  379. BillingTime: lago.Calendar,
  380. }
  381. _, lagoErr := m.client.Subscription().Create(ctx, subscriptionInput)
  382. if lagoErr != nil {
  383. return telemetry.Error(ctx, span, fmt.Errorf(lagoErr.ErrorCode), "failed to create subscription")
  384. }
  385. return nil
  386. }
  387. func (m LagoClient) generateLagoID(prefix string, projectID uint, sandboxEnabled bool) string {
  388. if sandboxEnabled {
  389. return fmt.Sprintf("cloud_%s_%d", prefix, projectID)
  390. }
  391. return fmt.Sprintf("%s_%d", prefix, projectID)
  392. }