TrackUsage increments cost for a user/project in hourly, weekly, and lifetime buckets. Uses upsert to create or update the usage records atomically. The success parameter indicates whether the request completed successfully. We will be charging only for successful requests, but we track failed reque
(ctx context.Context, userID bson.ObjectID, projectID string, cost float64, success bool)
| 116 | // The success parameter indicates whether the request completed successfully. |
| 117 | // We will be charging only for successful requests, but we track failed requests for monitoring. |
| 118 | func (s *UsageService) TrackUsage(ctx context.Context, userID bson.ObjectID, projectID string, cost float64, success bool) error { |
| 119 | if cost == 0 { |
| 120 | return nil |
| 121 | } |
| 122 | |
| 123 | now := time.Now() |
| 124 | |
| 125 | // Track hourly usage |
| 126 | if err := s.trackHourlyUsage(ctx, userID, projectID, cost, success, now); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | |
| 130 | // Track weekly usage |
| 131 | if err := s.trackWeeklyUsage(ctx, userID, projectID, cost, success, now); err != nil { |
| 132 | return err |
| 133 | } |
| 134 | |
| 135 | // Track lifetime usage |
| 136 | if err := s.trackLifetimeUsage(ctx, userID, projectID, cost, success, now); err != nil { |
| 137 | return err |
| 138 | } |
| 139 | |
| 140 | return nil |
| 141 | } |
| 142 | |
| 143 | func (s *UsageService) upsertUsage(ctx context.Context, collection *mongo.Collection, filter bson.M, cost float64, success bool, now time.Time) error { |
| 144 | costField := "failed_cost" |