Repository navigation
Expand file tree
/
Copy pathledger.go
More file actions
1545 lines (1341 loc) · 50.3 KB
/
Copy pathledger.go
File metadata and controls
1545 lines (1341 loc) · 50.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ledger
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
log "github.com/xraph/go-utils/log"
"github.com/xraph/ledger/coupon"
"github.com/xraph/ledger/entitlement"
"github.com/xraph/ledger/feature"
"github.com/xraph/ledger/id"
"github.com/xraph/ledger/invoice"
"github.com/xraph/ledger/meter"
"github.com/xraph/ledger/plan"
"github.com/xraph/ledger/plugin"
"github.com/xraph/ledger/provider"
"github.com/xraph/ledger/store"
"github.com/xraph/ledger/subscription"
"github.com/xraph/ledger/types"
)
// Ledger is the main billing engine.
type Ledger struct {
store store.Store
plugins *plugin.Registry
logger log.Logger
// Background workers
meterBuffer chan *meter.UsageEvent
stopChan chan struct{}
wg sync.WaitGroup
// importMu serialises the four provider imports from their duplicate check
// through their store write, so one process never stores a second row for
// a repeated import. It does not reach across replicas: with more than one,
// two imports of the same record can still race, and the dashboard's
// disabled button while a request is pending is what keeps that rare.
importMu sync.Mutex
// Configuration
meterBatchSize int
meterFlushInterval time.Duration
entitlementCacheTTL time.Duration
lifecycleInterval time.Duration
clock func() time.Time
skipMigrate bool
}
// New creates a new Ledger instance.
func New(s store.Store, opts ...Option) *Ledger {
l := &Ledger{
store: s,
plugins: plugin.NewRegistry(),
logger: log.NewNoopLogger(),
meterBuffer: make(chan *meter.UsageEvent, 10000),
stopChan: make(chan struct{}),
meterBatchSize: 100,
meterFlushInterval: 5 * time.Second,
entitlementCacheTTL: 30 * time.Second,
lifecycleInterval: time.Minute,
clock: time.Now,
}
for _, opt := range opts {
opt(l)
}
return l
}
// Option configures a Ledger instance.
type Option func(*Ledger)
// WithLogger sets the logger.
func WithLogger(logger log.Logger) Option {
return func(l *Ledger) {
l.logger = logger
l.plugins.WithLogger(logger)
}
}
// WithPlugin registers a plugin.
func WithPlugin(p plugin.Plugin) Option {
return func(l *Ledger) {
_ = l.plugins.Register(p) //nolint:errcheck // best-effort plugin registration during init
}
}
// WithMeterConfig configures metering parameters.
func WithMeterConfig(batchSize int, flushInterval time.Duration) Option {
return func(l *Ledger) {
l.meterBatchSize = batchSize
l.meterFlushInterval = flushInterval
}
}
// WithEntitlementCacheTTL sets the entitlement cache TTL.
func WithEntitlementCacheTTL(ttl time.Duration) Option {
return func(l *Ledger) {
l.entitlementCacheTTL = ttl
}
}
// WithLifecycleInterval sets how often the lifecycle clock runs Advance in the
// background (default: one minute). Zero or less turns the clock off, for a
// deployment that calls Advance from its own scheduler.
func WithLifecycleInterval(d time.Duration) Option {
return func(l *Ledger) {
l.lifecycleInterval = max(d, 0)
}
}
// WithClock sets where the engine reads the time for its decisions. Tests use
// it. A nil clock keeps time.Now.
//
// These follow the clock: the lifecycle worker's Advance, a new
// subscription's creation time, first period and trial, the periods
// GenerateInvoice will bill, coupon validity, and an invoice's due date.
//
// These stay on the wall clock: UpdatedAt and other change stamps, the
// timestamp on a metered usage event, the moment an immediate cancel or a
// void is recorded, the store's own usage windows, and the expiry of the
// entitlement cache.
func WithClock(now func() time.Time) Option {
return func(l *Ledger) {
if now != nil {
l.clock = now
}
}
}
// LifecycleInterval reports how often the lifecycle clock runs. Zero means it
// is off.
func (l *Ledger) LifecycleInterval() time.Duration { return l.lifecycleInterval }
// now is the engine's current time, in UTC, from the configured clock.
func (l *Ledger) now() time.Time { return l.clock().UTC() }
// stamp is now cut to the millisecond, for a time the engine stores and hands
// back to the caller: a subscription's creation and first period, a pause, a
// resume. Mongo keeps milliseconds and postgres microseconds, so a nanosecond
// value would come back from the store different from the one the caller
// holds, and a period named from the caller's copy would not match.
func (l *Ledger) stamp() time.Time { return l.now().Truncate(time.Millisecond) }
// WithoutMigrate makes Start skip the store migration and start only the
// background workers, for a deployment that migrates its schema separately.
func WithoutMigrate() Option {
return func(l *Ledger) {
l.skipMigrate = true
}
}
// Store returns the underlying ledger store.
func (l *Ledger) Store() store.Store { return l.store }
// Start begins background workers.
func (l *Ledger) Start(ctx context.Context) error {
// Migrate database, unless the deployment migrates it separately
if !l.skipMigrate {
if err := l.store.Migrate(ctx); err != nil {
return err
}
}
// Initialize plugins
l.plugins.EmitInit(ctx, l)
// Start meter flush worker
l.wg.Add(1)
go l.meterFlushWorker(ctx)
// Start the lifecycle clock
if l.lifecycleInterval > 0 {
l.wg.Add(1)
go l.lifecycleWorker(ctx)
}
l.logger.Info("ledger started",
log.Int("batch_size", l.meterBatchSize),
log.Duration("flush_interval", l.meterFlushInterval),
log.Duration("cache_ttl", l.entitlementCacheTTL),
log.Duration("lifecycle_interval", l.lifecycleInterval),
)
return nil
}
// Health checks the health of the Ledger by pinging its store.
func (l *Ledger) Health(ctx context.Context) error {
return l.store.Ping(ctx)
}
// Stop shuts down the Ledger.
func (l *Ledger) Stop() error {
close(l.stopChan)
l.wg.Wait()
ctx := context.Background()
l.plugins.EmitShutdown(ctx)
return l.store.Close()
}
// ──────────────────────────────────────────────────
// Plan Management
// ──────────────────────────────────────────────────
// CreatePlan validates and stores a new billing plan. It normalises the plan
// first (see normalisePlan), and refuses a slug the app already uses with
// ErrAlreadyExists.
func (l *Ledger) CreatePlan(ctx context.Context, p *plan.Plan) error {
if p.ID == (id.PlanID{}) {
p.ID = id.NewPlanID()
}
normalisePlan(p)
if err := validatePlan(p); err != nil {
return err
}
taken, err := l.slugTaken(ctx, p.Slug, p.AppID, p.ID)
if err != nil {
return err
}
if taken {
return fmt.Errorf("%w: slug %q is already used in this app", ErrAlreadyExists, p.Slug)
}
p.Entity = types.NewEntity()
if err := l.store.CreatePlan(ctx, p); err != nil {
return err
}
l.plugins.EmitPlanCreated(ctx, p)
return nil
}
// GetPlan retrieves a plan by ID.
func (l *Ledger) GetPlan(ctx context.Context, planID id.PlanID) (*plan.Plan, error) {
return l.store.GetPlan(ctx, planID)
}
// GetPlanBySlug retrieves a plan by slug.
func (l *Ledger) GetPlanBySlug(ctx context.Context, slug, appID string) (*plan.Plan, error) {
return l.store.GetPlanBySlug(ctx, slug, appID)
}
// ──────────────────────────────────────────────────
// Feature Catalog Management
// ──────────────────────────────────────────────────
// CreateFeature creates a new catalog feature.
func (l *Ledger) CreateFeature(ctx context.Context, f *feature.Feature) error {
if f.ID == (id.FeatureID{}) {
f.ID = id.NewFeatureID()
}
f.Entity = types.NewEntity()
if err := l.store.CreateFeature(ctx, f); err != nil {
return err
}
l.plugins.EmitFeatureCreated(ctx, f)
return nil
}
// GetFeature retrieves a catalog feature by ID.
func (l *Ledger) GetFeature(ctx context.Context, featureID id.FeatureID) (*feature.Feature, error) {
return l.store.GetFeature(ctx, featureID)
}
// GetFeatureByKey retrieves a catalog feature by key and app scope.
func (l *Ledger) GetFeatureByKey(ctx context.Context, key, appID string) (*feature.Feature, error) {
return l.store.GetFeatureByKey(ctx, key, appID)
}
// ListFeatures lists catalog features for an app.
func (l *Ledger) ListFeatures(ctx context.Context, appID string, opts feature.ListOpts) ([]*feature.Feature, error) {
return l.store.ListFeatures(ctx, appID, opts)
}
// ListGlobalFeatures lists catalog features with no app scope.
func (l *Ledger) ListGlobalFeatures(ctx context.Context, opts feature.ListOpts) ([]*feature.Feature, error) {
return l.store.ListGlobalFeatures(ctx, opts)
}
// UpdateFeature updates a catalog feature.
func (l *Ledger) UpdateFeature(ctx context.Context, f *feature.Feature) error {
old, err := l.store.GetFeature(ctx, f.ID)
if err != nil {
return err
}
if err := l.store.UpdateFeature(ctx, f); err != nil {
return err
}
l.plugins.EmitFeatureUpdated(ctx, old, f)
return nil
}
// DeleteFeature deletes a catalog feature.
func (l *Ledger) DeleteFeature(ctx context.Context, featureID id.FeatureID) error {
if err := l.store.DeleteFeature(ctx, featureID); err != nil {
return err
}
l.plugins.EmitFeatureDeleted(ctx, featureID.String())
return nil
}
// ArchiveFeature archives a catalog feature.
func (l *Ledger) ArchiveFeature(ctx context.Context, featureID id.FeatureID) error {
if err := l.store.ArchiveFeature(ctx, featureID); err != nil {
return err
}
l.plugins.EmitFeatureArchived(ctx, featureID.String())
return nil
}
// ──────────────────────────────────────────────────
// Subscription Management
// ──────────────────────────────────────────────────
// CreateSubscription creates a new subscription.
//
// A subscription must name its tenant. Every store reads an empty tenant id
// as "every tenant", so one without a tenant would later be billed for other
// customers' usage. It is refused with an error wrapping ErrInvalidInput and
// nothing is written. The app id may stay empty: deployments that never set
// one still bill their base fee.
func (l *Ledger) CreateSubscription(ctx context.Context, sub *subscription.Subscription) error {
if sub.TenantID == "" {
return fmt.Errorf("%w: subscription has no tenant id", ErrInvalidInput)
}
p, err := l.subscribablePlan(ctx, sub.PlanID, sub.AppID)
if err != nil {
return err
}
if err := validateQuantity(p, sub.Quantity); err != nil {
return err
}
if sub.ID == (id.SubscriptionID{}) {
sub.ID = id.NewSubscriptionID()
}
// Stamped from the engine's clock, so a subscription created under
// WithClock has its first period and its trial on that clock's dates,
// and cut to the millisecond, so the struct the caller keeps matches the
// row on every backend.
created := l.stamp()
sub.Entity = types.Entity{CreatedAt: created, UpdatedAt: created}
// Set the first period from the plan's billing period (see
// billingPeriod). Stored times are UTC, so every backend holds the same
// representation. time.Now() carries the host's zone and a monotonic
// reading, neither of which a store can round-trip.
switch {
case sub.CurrentPeriodStart.IsZero():
// From CreatedAt, not a second clock reading: on a nanosecond clock a
// start later than created_at would let ForPeriod accept the period
// before the first, which ends just after created_at.
sub.CurrentPeriodStart = sub.CreatedAt.UTC()
sub.CurrentPeriodEnd = firstPeriodEnd(sub.CurrentPeriodStart, billingPeriod(p))
case sub.CurrentPeriodEnd.IsZero():
sub.CurrentPeriodStart = sub.CurrentPeriodStart.UTC()
sub.CurrentPeriodEnd = firstPeriodEnd(sub.CurrentPeriodStart, billingPeriod(p))
}
if sub.Status == "" {
if p.TrialDays > 0 {
trialStart := sub.CurrentPeriodStart
trialEnd := trialStart.AddDate(0, 0, p.TrialDays)
sub.Status = subscription.StatusTrialing
sub.TrialStart = &trialStart
sub.TrialEnd = &trialEnd
} else {
sub.Status = subscription.StatusActive
}
}
if err := l.store.CreateSubscription(ctx, sub); err != nil {
return err
}
// Invalidate entitlement cache for tenant
_ = l.store.Invalidate(ctx, sub.TenantID, sub.AppID) //nolint:errcheck // best-effort cache invalidation
l.plugins.EmitSubscriptionCreated(ctx, sub)
return nil
}
// GetSubscription retrieves a subscription by ID.
func (l *Ledger) GetSubscription(ctx context.Context, subID id.SubscriptionID) (*subscription.Subscription, error) {
return l.store.GetSubscription(ctx, subID)
}
// GetActiveSubscription retrieves the active subscription for a tenant.
func (l *Ledger) GetActiveSubscription(ctx context.Context, tenantID, appID string) (*subscription.Subscription, error) {
return l.store.GetActiveSubscription(ctx, tenantID, appID)
}
// CancelSubscription cancels a subscription, now or at the end of its current
// period. A subscription that is already canceled or expired is refused, so a
// cancel on it can neither move its cancel_at nor announce the cancellation
// again. One that is still running can be canceled again while a scheduled
// cancel waits: a scheduled cancel sets cancel_at to the current period end
// once more, and an immediate one stops it now.
//
// OnSubscriptionCanceled fires only when the subscription stopped now. A
// cancel dated later fires OnSubscriptionCancelScheduled, and the lifecycle
// clock fires OnSubscriptionCanceled when it enacts it. That holds even when
// the period it ends is already over: the subscription keeps running until
// the clock's next run cancels it as of that period's end.
func (l *Ledger) CancelSubscription(ctx context.Context, subID id.SubscriptionID, immediately bool) error {
sub, err := l.store.GetSubscription(ctx, subID)
if err != nil {
return err
}
switch sub.Status {
case subscription.StatusCanceled:
return ErrSubscriptionCanceled
case subscription.StatusExpired:
return ErrSubscriptionExpired
}
// The store picks the date: now, or for a scheduled cancel the period end
// current when its write lands, which is later than the one read above
// if the lifecycle clock advanced the period in between.
cancelAt, err := l.store.CancelSubscription(ctx, subID, immediately)
if err != nil {
return err
}
// The hooks get the row as stored, which carries the store's updated_at
// and anything written beside the cancel, such as a period the clock
// advanced. The row read above stands in only if the read fails.
sub = l.storedOr(ctx, sub, func(x *subscription.Subscription) {
x.CancelAt = &cancelAt
if immediately {
canceledAt := cancelAt
x.Status = subscription.StatusCanceled
x.CanceledAt = &canceledAt
}
})
// Invalidate entitlement cache
_ = l.store.Invalidate(ctx, sub.TenantID, sub.AppID) //nolint:errcheck // best-effort cache invalidation
// Only an immediate cancel changes the status; a scheduled one never
// does, whatever date the store copied into cancel_at.
if immediately {
l.plugins.EmitSubscriptionCanceled(ctx, sub)
} else {
l.plugins.EmitSubscriptionCancelScheduled(ctx, sub)
}
return nil
}
// ──────────────────────────────────────────────────
// Usage Metering
// ──────────────────────────────────────────────────
// Meter records a usage event (non-blocking).
func (l *Ledger) Meter(ctx context.Context, featureKey string, quantity int64) error {
// Extract tenant and app from context
tenantID := extractTenantID(ctx)
appID := extractAppID(ctx)
if tenantID == "" || appID == "" {
return ErrInvalidInput
}
event := &meter.UsageEvent{
ID: id.NewUsageEventID(),
TenantID: tenantID,
AppID: appID,
FeatureKey: featureKey,
Quantity: quantity,
Timestamp: time.Now().UTC(),
}
select {
case l.meterBuffer <- event:
return nil
default:
return ErrMeterBufferFull
}
}
// meterFlushWorker flushes usage events to the store.
func (l *Ledger) meterFlushWorker(ctx context.Context) {
defer l.wg.Done()
batch := make([]*meter.UsageEvent, 0, l.meterBatchSize)
ticker := time.NewTicker(l.meterFlushInterval)
defer ticker.Stop()
for {
select {
case <-l.stopChan:
// Final flush
if len(batch) > 0 {
l.flushMeterBatch(ctx, batch)
}
return
case event := <-l.meterBuffer:
batch = append(batch, event)
if len(batch) >= l.meterBatchSize {
l.flushMeterBatch(ctx, batch)
batch = make([]*meter.UsageEvent, 0, l.meterBatchSize)
}
case <-ticker.C:
if len(batch) > 0 {
l.flushMeterBatch(ctx, batch)
batch = make([]*meter.UsageEvent, 0, l.meterBatchSize)
}
}
}
}
func (l *Ledger) flushMeterBatch(ctx context.Context, batch []*meter.UsageEvent) {
start := time.Now()
if err := l.store.IngestBatch(ctx, batch); err != nil {
l.logger.Error("failed to flush meter batch",
log.Error(err),
log.Int("batch_size", len(batch)),
)
return
}
elapsed := time.Since(start)
l.plugins.EmitUsageFlushed(ctx, len(batch), elapsed)
l.logger.Debug("flushed meter batch",
log.Int("batch_size", len(batch)),
log.Int64("elapsed_ms", elapsed.Milliseconds()),
)
}
// ──────────────────────────────────────────────────
// Entitlements
// ──────────────────────────────────────────────────
// Entitled checks if the current tenant can use a feature.
func (l *Ledger) Entitled(ctx context.Context, featureKey string) (*entitlement.Result, error) {
tenantID := extractTenantID(ctx)
appID := extractAppID(ctx)
if tenantID == "" || appID == "" {
return &entitlement.Result{
Allowed: false,
Feature: featureKey,
Reason: "missing tenant or app context",
}, nil
}
// Check cache first
if cached, err := l.store.GetCached(ctx, tenantID, appID, featureKey); err == nil {
return cached, nil
}
result, kind, err := l.computeEntitlement(ctx, tenantID, appID, featureKey)
if err != nil {
return nil, err
}
switch kind {
case entitlementBoolean:
_ = l.store.SetCached(ctx, tenantID, appID, featureKey, result, l.entitlementCacheTTL) //nolint:errcheck // best-effort cache set
case entitlementMetered:
if result.Reason == "quota exceeded" {
l.plugins.EmitQuotaExceeded(ctx, tenantID, featureKey, result.Used, result.Limit)
}
_ = l.store.SetCached(ctx, tenantID, appID, featureKey, result, l.entitlementCacheTTL) //nolint:errcheck // best-effort cache set
l.plugins.EmitEntitlementChecked(ctx, result)
case entitlementNoAccess:
// Nothing is cached and no event fires when there is no access to report.
}
return result, nil
}
type entitlementKind int
const (
entitlementNoAccess entitlementKind = iota // no subscription, no plan, or feature not in plan
entitlementBoolean
entitlementMetered
)
// computeEntitlement answers an entitlement question from the store alone. It
// reads no cache, writes no cache and fires no plugin events; callers decide.
func (l *Ledger) computeEntitlement(ctx context.Context, tenantID, appID, featureKey string) (*entitlement.Result, entitlementKind, error) {
// Get active subscription
sub, err := l.store.GetActiveSubscription(ctx, tenantID, appID)
if err != nil {
return &entitlement.Result{
Allowed: false,
Feature: featureKey,
Reason: "no active subscription",
}, entitlementNoAccess, nil
}
// Get plan
p, err := l.store.GetPlan(ctx, sub.PlanID)
if err != nil {
return &entitlement.Result{
Allowed: false,
Feature: featureKey,
Reason: "plan not found",
}, entitlementNoAccess, nil
}
// Find feature in plan
feat := p.FindFeature(featureKey)
if feat == nil {
return &entitlement.Result{
Allowed: false,
Feature: featureKey,
Reason: "feature not in plan",
}, entitlementNoAccess, nil
}
// Boolean feature
if feat.Type == plan.FeatureBoolean {
result := &entitlement.Result{
Allowed: feat.Limit > 0,
Feature: featureKey,
Limit: feat.Limit,
}
return result, entitlementBoolean, nil
}
// Metered/seat feature
used, err := l.store.Aggregate(ctx, tenantID, appID, featureKey, feat.Period)
if err != nil {
return nil, entitlementMetered, err
}
result := &entitlement.Result{
Feature: featureKey,
Used: used,
Limit: feat.Limit,
Remaining: max(0, feat.Limit-used),
SoftLimit: feat.SoftLimit,
}
switch {
case feat.Limit == -1:
result.Allowed = true
result.Remaining = -1
case used < feat.Limit:
result.Allowed = true
case feat.SoftLimit:
result.Allowed = true
result.Reason = "over soft limit"
default:
result.Allowed = false
result.Reason = "quota exceeded"
}
return result, entitlementMetered, nil
}
// Remaining returns the remaining quota for a feature.
func (l *Ledger) Remaining(ctx context.Context, featureKey string) (int64, error) {
result, err := l.Entitled(ctx, featureKey)
if err != nil {
return 0, err
}
return result.Remaining, nil
}
// ──────────────────────────────────────────────────
// Invoice Generation
// ──────────────────────────────────────────────────
// aggregateUsage totals a feature's usage for billing over window, the part of
// the billed period an invoice counts (see usageWindow). A feature naming a
// registered aggregator under metadata key "aggregator" is aggregated by the
// plugin over that window; anything else is summed from the same events
// (usageInPeriod). An unregistered name falls back to the sum rather than
// failing: a plan referring to a plugin that is not installed should still
// bill.
//
// GenerateInvoice has already refused an empty tenant id. The plugin path
// also refuses an empty app id, because it reads events through QueryUsage,
// which drops the app filter when the app id is empty. The summing path
// skips events from another app itself.
func (l *Ledger) aggregateUsage(ctx context.Context, sub *subscription.Subscription, pf plan.Feature, window subscription.Period) (int64, error) {
name := pf.Metadata["aggregator"]
if name == "" {
return l.usageInPeriod(ctx, sub, pf, window)
}
agg := l.plugins.GetUsageAggregator(name)
if agg == nil {
l.logger.Warn("ledger: feature names an unregistered usage aggregator; summing its events",
log.String("aggregator", name),
log.String("feature", pf.Key),
)
return l.usageInPeriod(ctx, sub, pf, window)
}
if sub.AppID == "" {
return 0, fmt.Errorf("%w: usage aggregator %q needs an app id to scope its events, and subscription %s has none",
ErrInvalidInput, name, sub.ID)
}
events, err := l.store.QueryUsage(ctx, sub.TenantID, sub.AppID, meter.QueryOpts{
FeatureKey: pf.Key,
Start: window.Start,
End: window.End,
})
if err != nil {
return 0, fmt.Errorf("query usage for aggregator %q: %w", name, err)
}
boxed := make([]interface{}, len(events))
for i := range events {
boxed[i] = events[i]
}
total, err := agg.Aggregate(ctx, boxed)
if err != nil {
return 0, fmt.Errorf("usage aggregator %q: %w", name, err)
}
// A negative total would reduce billable usage below what the store
// recorded, and could turn an overage into a silent zero. Refuse it the
// way a negative tax amount or strategy result is refused.
if total < 0 {
return 0, fmt.Errorf("usage aggregator %q returned a negative total %d", name, total)
}
return total, nil
}
// priceFeature prices one feature's billable usage in currency, which must
// be the plan's already-lowercased currency as GenerateInvoice normalised it.
// featureTiers must already have passed invoice.ValidateTiers.
//
// A feature naming a registered pricing strategy under metadata key
// "pricing_strategy", or failing that a plan naming one, is priced by the
// plugin. Everything else uses the built-in tier models. The plugin is never
// asked to price usage the allowance covers, and its answer must be a
// non-negative Money in the plan's currency.
func (l *Ledger) priceFeature(p *plan.Plan, pf plan.Feature, featureTiers []plan.PriceTier, currency string, usage, included int64) (types.Money, error) {
// The feature's own strategy wins over the plan's.
namedBy := "feature"
name := pf.Metadata["pricing_strategy"]
if name == "" {
namedBy = "plan"
name = p.Metadata["pricing_strategy"]
}
if name == "" {
return invoice.ComputeOverage(featureTiers, usage, included, currency)
}
strategy := l.plugins.GetPricingStrategy(name)
if strategy == nil {
l.logger.Warn(fmt.Sprintf("ledger: %s names an unregistered pricing strategy; using the built-in tiers", namedBy),
log.String("strategy", name),
log.String("feature", pf.Key),
)
return invoice.ComputeOverage(featureTiers, usage, included, currency)
}
// Defence in depth: both callers already guarantee this (the metered
// loop skips a Limit of -1 and any usage at or under the allowance, and
// the seat loop skips a seat count of zero against an allowance of
// zero), so today it never fires.
if included < 0 || usage <= included {
return types.Zero(currency), nil
}
// Hand the strategy a ladder in order, as invoice.ComputeOverage sees it.
sorted := invoice.SortTiers(featureTiers)
boxed := make([]interface{}, len(sorted))
for i := range sorted {
boxed[i] = sorted[i]
}
raw := strategy.Compute(boxed, usage, included, currency)
amount, ok := raw.(types.Money)
if !ok {
return types.Money{}, fmt.Errorf("pricing strategy %q returned %T, want types.Money", name, raw)
}
if amount.Currency != "" && !strings.EqualFold(amount.Currency, currency) {
return types.Money{}, fmt.Errorf("pricing strategy %q returned %s, want %s", name, amount.Currency, currency)
}
if amount.IsNegative() {
return types.Money{}, fmt.Errorf("pricing strategy %q returned a negative amount %v", name, amount)
}
return types.Money{Amount: amount.Amount, Currency: currency}, nil
}
// addChecked adds b to a, refusing an overflowing sum. The error names the
// stage that was being built and wraps types.ErrOverflow, so a caller can
// match it with errors.Is.
func addChecked(stage string, a, b types.Money) (types.Money, error) {
sum, err := a.CheckedAdd(b)
if err != nil {
return types.Money{}, fmt.Errorf("%s: %w", stage, err)
}
return sum, nil
}
// GenerateInvoice generates an invoice for a subscription period.
//
// It assembles line items in a fixed order: the base fee, then metered
// usage overage per feature in plan order, then seat charges per seat
// feature in plan order, then one discount line per applied coupon, then
// one tax line. Every Money the function builds is normalised to one
// lowercased currency taken from the plan, so two values built from
// different casings of the same currency (e.g. "USD" and "usd") never trip
// Money.Add/Subtract's case-sensitive mismatch panic. Tax is computed on
// the net amount (subtotal less discounts, clamped at zero), not the
// gross subtotal, so a discounted invoice is never taxed on money the
// customer was never charged.
//
// Every sum it builds (subtotal, discount, net, tax and total) is checked.
// An amount that overflows an int64 fails generation with an error wrapping
// types.ErrOverflow that names the stage, and nothing is stored: a wrapped
// figure must never become an invoice.
//
// A subscription with an empty tenant id is refused with an error wrapping
// ErrInvalidInput before anything else is read for it. Every store reads an
// empty tenant as "every tenant", so billing one would total other
// customers' usage. An empty app id is allowed and still bills the base
// fee; only a feature totalled by a plugin aggregator refuses it (see
// aggregateUsage).
//
// Usage is always the billed period's own: the events from its start to its
// end, or to now while it is still running (see usageWindow). That holds for
// the current period and for one named with ForPeriod, so two invoices for
// consecutive periods never count the same event. A feature's reset period
// (plan.Feature.Period) plays no part in billing; it shapes quota checks
// alone.
//
// With ForPeriod it bills a period the subscription has already had instead
// of its current one. Only usage is historical: the plan, its prices, the
// seat counts and the coupons are all read as they are now, because Ledger
// keeps no history of them and ChangePlan leaves the period alone.
func (l *Ledger) GenerateInvoice(ctx context.Context, subID id.SubscriptionID, opts ...InvoiceOption) (*invoice.Invoice, error) {
sub, err := l.store.GetSubscription(ctx, subID)
if err != nil {
return nil, err
}
if sub.TenantID == "" {
return nil, fmt.Errorf("%w: subscription %s has no tenant id", ErrInvalidInput, sub.ID)
}
p, err := l.store.GetPlan(ctx, sub.PlanID)
if err != nil {
return nil, err
}
// A named past period (ForPeriod) is billed on a copy of the subscription
// carrying that period, so the duplicate check, the invoice's dates and a
// plugin aggregator's window all read it from one place.
now := l.now()
named, err := namedPeriod(sub, p, opts, now)
if err != nil {
return nil, err
}
// A resume moves the end of a paused subscription's period on by the
// length of the pause, so that period is not finished: billing it now
// would bill a period whose end later moves. Ended periods named with
// ForPeriod are finished and stay billable.
if named == nil && sub.Status == subscription.StatusPaused {
return nil, fmt.Errorf("%w: subscription %s is paused; its period is billed when it ends", ErrInvalidInput, sub.ID)
}
if named != nil {
billed := *sub
billed.CurrentPeriodStart, billed.CurrentPeriodEnd = named.Start, named.End
sub = &billed
}
existing, err := l.liveInvoiceForPeriod(ctx, sub)
if err != nil {
return nil, err
}
if existing != nil {
return nil, fmt.Errorf("%w: invoice %s already covers this billing period", ErrAlreadyExists, existing.ID)
}
window := usageWindow(subscription.Period{Start: sub.CurrentPeriodStart, End: sub.CurrentPeriodEnd}, now)
currency := strings.ToLower(p.Currency)
inv := &invoice.Invoice{
Entity: types.NewEntity(),
ID: id.NewInvoiceID(),
TenantID: sub.TenantID,
SubscriptionID: sub.ID,
Status: invoice.StatusDraft,
Currency: currency,
Subtotal: types.Zero(currency),
TaxAmount: types.Zero(currency),
DiscountAmount: types.Zero(currency),
Total: types.Zero(currency),
PeriodStart: sub.CurrentPeriodStart,
PeriodEnd: sub.CurrentPeriodEnd,
AppID: sub.AppID,
LineItems: []invoice.LineItem{},
}
// 1. Base subscription fee. A base price stored in a currency other
// than the plan's is a catalogue error, not something to panic over:
// reject it before it ever reaches Money.Add. A negative base price is a
// catalogue error too, and is refused rather than skipped: skipping it
// would invoice the plan as though it had no base fee at all.
if p.Pricing != nil && p.Pricing.BaseAmount.IsNegative() {
return nil, fmt.Errorf("%w: plan %s base price %v is negative",
ErrInvalidPricing, p.ID, p.Pricing.BaseAmount)
}
if p.Pricing != nil && p.Pricing.BaseAmount.IsPositive() {
if p.Pricing.BaseAmount.Currency != "" && !strings.EqualFold(p.Pricing.BaseAmount.Currency, currency) {
return nil, fmt.Errorf("%w: plan %s base price is in %q, plan bills in %q",
ErrInvalidPricing, p.ID, p.Pricing.BaseAmount.Currency, p.Currency)
}
base := types.Money{Amount: p.Pricing.BaseAmount.Amount, Currency: currency}
inv.LineItems = append(inv.LineItems, invoice.LineItem{
ID: id.NewLineItemID(),
InvoiceID: inv.ID,
Description: "Base subscription fee",
Quantity: 1,
UnitAmount: base,
Amount: base,
Type: invoice.LineItemBase,
})
subtotal, addErr := addChecked("subtotal: adding the base fee", inv.Subtotal, base)
if addErr != nil {
return nil, addErr
}
inv.Subtotal = subtotal
}
// 2. Metered usage overage, priced from the plan's tiers.
var tiers []plan.PriceTier
if p.Pricing != nil {
tiers = p.Pricing.Tiers
}
for _, pf := range p.Features {
if pf.Type != plan.FeatureMetered {
continue
}
// An unlimited allowance can never bill, so this feature is
// skipped entirely, including ladder validation: a catalogue
// mistake on a feature nobody can ever be charged for should not
// fail every invoice on the plan.
if pf.Limit < 0 {
continue
}
featureTiers := tiersFor(tiers, pf.Key)
if vErr := invoice.ValidateTiers(featureTiers, currency); vErr != nil {
return nil, fmt.Errorf("plan %s feature %q: %w", p.ID, pf.Key, vErr)
}
used, aggErr := l.aggregateUsage(ctx, sub, pf, window)
if aggErr != nil {
return nil, fmt.Errorf("aggregate usage for feature %q: %w", pf.Key, aggErr)
}
billable := used - pf.Limit
if billable <= 0 {
continue
}
amount, priceErr := l.priceFeature(p, pf, featureTiers, currency, used, pf.Limit)
if priceErr != nil {
return nil, fmt.Errorf("price feature %q: %w", pf.Key, priceErr)
}
if amount.IsZero() {
continue
}
inv.LineItems = append(inv.LineItems, invoice.LineItem{
ID: id.NewLineItemID(),
InvoiceID: inv.ID,
FeatureKey: pf.Key,
Description: pf.Name + " overage",
Quantity: billable,