소스 검색

Get porter cloud subscription id from billing events (#4661)

Mauricio Araujo 2 년 전
부모
커밋
7cd7e37d7c
2개의 변경된 파일21개의 추가작업 그리고 14개의 파일을 삭제
  1. 10 14
      api/server/handlers/billing/ingest.go
  2. 11 0
      internal/billing/usage.go

+ 10 - 14
api/server/handlers/billing/ingest.go

@@ -5,7 +5,6 @@ import (
 	"bytes"
 	"context"
 	"encoding/json"
-	"fmt"
 	"net/http"
 
 	"github.com/porter-dev/porter/api/server/handlers"
@@ -64,25 +63,22 @@ func (c *IngestEventsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
 		telemetry.AttributeKV{Key: "usage-events-count", Value: len(ingestEventsRequest.Events)},
 	)
 
-	// For Porter Cloud events, we apend a prefix to avoid collisions before sending to Lago
-	if proj.EnableSandbox {
-		for i := range ingestEventsRequest.Events {
-			ingestEventsRequest.Events[i].CustomerID = fmt.Sprintf("porter-cloud-%s", ingestEventsRequest.Events[i].CustomerID)
+	var subscriptionID string
+	if !proj.EnableSandbox {
+		plan, err := c.Config().BillingManager.LagoClient.GetCustomerActivePlan(ctx, proj.ID, proj.EnableSandbox)
+		if err != nil {
+			err := telemetry.Error(ctx, span, err, "error getting active subscription")
+			c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
+			return
 		}
-	}
-
-	plan, err := c.Config().BillingManager.LagoClient.GetCustomerActivePlan(ctx, proj.ID, proj.EnableSandbox)
-	if err != nil {
-		err := telemetry.Error(ctx, span, err, "error getting active subscription")
-		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
-		return
+		subscriptionID = plan.ID
 	}
 
 	telemetry.WithAttributes(span,
-		telemetry.AttributeKV{Key: "subscription_id", Value: plan.ID},
+		telemetry.AttributeKV{Key: "subscription_id", Value: subscriptionID},
 	)
 
-	err = c.Config().BillingManager.LagoClient.IngestEvents(ctx, plan.ID, ingestEventsRequest.Events, proj.EnableSandbox)
+	err := c.Config().BillingManager.LagoClient.IngestEvents(ctx, subscriptionID, ingestEventsRequest.Events, proj.EnableSandbox)
 	if err != nil {
 		err := telemetry.Error(ctx, span, err, "error ingesting events")
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))

+ 11 - 0
internal/billing/usage.go

@@ -380,6 +380,17 @@ func (m LagoClient) IngestEvents(ctx context.Context, subscriptionID string, eve
 		batch := events[i:end]
 		var batchInput []lago.EventInput
 		for i := range batch {
+			projectID, err := strconv.ParseUint(batch[i].CustomerID, 10, 64)
+			if err != nil {
+				return telemetry.Error(ctx, span, err, "failed to parse project id")
+			}
+
+			if enableSandbox {
+				// For Porter Cloud, we can't infer the project ID from the request, so we
+				// instead use the one in the billing event
+				subscriptionID = m.generateLagoID(SubscriptionIDPrefix, uint(projectID), enableSandbox)
+			}
+
 			event := lago.EventInput{
 				TransactionID:          batch[i].TransactionID,
 				ExternalSubscriptionID: subscriptionID,