Documentation
¶
Overview ¶
Package plugin provides an extensible plugin system for Ledger. Plugins can hook into various lifecycle events to extend functionality.
Index ¶
- Constants
- type CouponValidator
- type InvoiceFormatter
- type OnEntitlementChecked
- type OnFeatureArchived
- type OnFeatureCreated
- type OnFeatureDeleted
- type OnFeatureUpdated
- type OnInit
- type OnInvoiceFailed
- type OnInvoiceFinalized
- type OnInvoiceGenerated
- type OnInvoicePaid
- type OnInvoicePastDue
- type OnInvoiceVoided
- type OnPlanArchived
- type OnPlanCreated
- type OnPlanUpdated
- type OnProviderSync
- type OnQuotaExceeded
- type OnShutdown
- type OnSoftLimitReached
- type OnSubscriptionCancelScheduled
- type OnSubscriptionCanceled
- type OnSubscriptionChanged
- type OnSubscriptionCreated
- type OnSubscriptionExpired
- type OnSubscriptionRenewed
- type OnSubscriptionTrialEnded
- type OnUsageFlushed
- type OnUsageIngested
- type OnWebhookReceived
- type PaymentProviderPlugin
- type Plugin
- type PricingStrategy
- type Registry
- func (r *Registry) Count() int
- func (r *Registry) EmitEntitlementChecked(ctx context.Context, result interface{})
- func (r *Registry) EmitFeatureArchived(ctx context.Context, featureID string)
- func (r *Registry) EmitFeatureCreated(ctx context.Context, feature interface{})
- func (r *Registry) EmitFeatureDeleted(ctx context.Context, featureID string)
- func (r *Registry) EmitFeatureUpdated(ctx context.Context, oldFeature, newFeature interface{})
- func (r *Registry) EmitInit(ctx context.Context, ledger interface{})
- func (r *Registry) EmitInvoiceFailed(ctx context.Context, inv interface{}, payErr error)
- func (r *Registry) EmitInvoiceFinalized(ctx context.Context, inv interface{})
- func (r *Registry) EmitInvoiceGenerated(ctx context.Context, inv interface{})
- func (r *Registry) EmitInvoicePaid(ctx context.Context, inv interface{})
- func (r *Registry) EmitInvoicePastDue(ctx context.Context, inv interface{})
- func (r *Registry) EmitInvoiceVoided(ctx context.Context, inv interface{}, reason string)
- func (r *Registry) EmitPlanArchived(ctx context.Context, planID string)
- func (r *Registry) EmitPlanCreated(ctx context.Context, plan interface{})
- func (r *Registry) EmitPlanUpdated(ctx context.Context, oldPlan, newPlan interface{})
- func (r *Registry) EmitProviderSync(ctx context.Context, providerName string, success bool, syncErr error)
- func (r *Registry) EmitQuotaExceeded(ctx context.Context, tenantID, featureKey string, used, limit int64)
- func (r *Registry) EmitShutdown(ctx context.Context)
- func (r *Registry) EmitSoftLimitReached(ctx context.Context, tenantID, featureKey string, used, limit int64)
- func (r *Registry) EmitSubscriptionCancelScheduled(ctx context.Context, sub interface{})
- func (r *Registry) EmitSubscriptionCanceled(ctx context.Context, sub interface{})
- func (r *Registry) EmitSubscriptionChanged(ctx context.Context, sub, oldPlan, newPlan interface{})
- func (r *Registry) EmitSubscriptionCreated(ctx context.Context, sub interface{})
- func (r *Registry) EmitSubscriptionExpired(ctx context.Context, sub interface{})
- func (r *Registry) EmitSubscriptionRenewed(ctx context.Context, renewal interface{})
- func (r *Registry) EmitSubscriptionTrialEnded(ctx context.Context, sub interface{})
- func (r *Registry) EmitUsageFlushed(ctx context.Context, count int, elapsed time.Duration)
- func (r *Registry) EmitUsageIngested(ctx context.Context, events []interface{})
- func (r *Registry) EmitWebhookReceived(ctx context.Context, providerName string, payload []byte)
- func (r *Registry) Get(name string) Plugin
- func (r *Registry) GetCouponValidators() []CouponValidator
- func (r *Registry) GetInvoiceFormatter(format string) InvoiceFormatter
- func (r *Registry) GetPaymentProvider(name string) PaymentProviderPlugin
- func (r *Registry) GetPaymentProviders() []PaymentProviderPlugin
- func (r *Registry) GetPricingStrategy(name string) PricingStrategy
- func (r *Registry) GetTaxCalculators() []TaxCalculator
- func (r *Registry) GetUsageAggregator(name string) UsageAggregator
- func (r *Registry) HasPaymentProviders() bool
- func (r *Registry) InvoiceFormats() []string
- func (r *Registry) List() []Plugin
- func (r *Registry) Register(p Plugin) error
- func (r *Registry) WithLogger(logger log.Logger) *Registry
- func (r *Registry) WithMetrics(m gometrics.Metrics) *Registry
- type TaxCalculator
- type UsageAggregator
Constants ¶
const HookFailuresMetric = "ledger_plugin_hook_failures_total"
HookFailuresMetric counts hook calls that failed, by hook and by reason. A Forge app scrapes it as forge_ledger_plugin_hook_failures_total.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CouponValidator ¶
type CouponValidator interface {
Plugin
ValidateCoupon(ctx context.Context, coupon interface{}, sub interface{}) error
}
CouponValidator provides custom coupon validation logic.
type InvoiceFormatter ¶
type InvoiceFormatter interface {
Plugin
Format() string // "pdf", "html", "csv", etc.
Render(ctx context.Context, inv interface{}, w interface{}) error // w is io.Writer
}
InvoiceFormatter formats invoices for export.
type OnEntitlementChecked ¶
type OnEntitlementChecked interface {
Plugin
OnEntitlementChecked(ctx context.Context, result interface{}) error
}
OnEntitlementChecked is called when an entitlement is checked.
type OnFeatureArchived ¶
type OnFeatureArchived interface {
Plugin
OnFeatureArchived(ctx context.Context, featureID string) error
}
OnFeatureArchived is called when a catalog feature is archived.
type OnFeatureCreated ¶
type OnFeatureCreated interface {
Plugin
OnFeatureCreated(ctx context.Context, feature interface{}) error
}
OnFeatureCreated is called when a new catalog feature is created.
type OnFeatureDeleted ¶
type OnFeatureDeleted interface {
Plugin
OnFeatureDeleted(ctx context.Context, featureID string) error
}
OnFeatureDeleted is called when a catalog feature is deleted.
type OnFeatureUpdated ¶
type OnFeatureUpdated interface {
Plugin
OnFeatureUpdated(ctx context.Context, oldFeature, newFeature interface{}) error
}
OnFeatureUpdated is called when a catalog feature is updated.
type OnInvoiceFailed ¶
type OnInvoiceFailed interface {
Plugin
OnInvoiceFailed(ctx context.Context, inv interface{}, err error) error
}
OnInvoiceFailed is called when an invoice payment fails.
type OnInvoiceFinalized ¶
type OnInvoiceFinalized interface {
Plugin
OnInvoiceFinalized(ctx context.Context, inv interface{}) error
}
OnInvoiceFinalized is called when an invoice is finalized.
type OnInvoiceGenerated ¶
type OnInvoiceGenerated interface {
Plugin
OnInvoiceGenerated(ctx context.Context, inv interface{}) error
}
OnInvoiceGenerated is called when an invoice is generated.
type OnInvoicePaid ¶
OnInvoicePaid is called when an invoice is paid.
type OnInvoicePastDue ¶
type OnInvoicePastDue interface {
Plugin
OnInvoicePastDue(ctx context.Context, inv interface{}) error
}
OnInvoicePastDue is called when the lifecycle clock marks a pending invoice past due. The subscription's status does not change.
type OnInvoiceVoided ¶
type OnInvoiceVoided interface {
Plugin
OnInvoiceVoided(ctx context.Context, inv interface{}, reason string) error
}
OnInvoiceVoided is called when an invoice is voided.
type OnPlanArchived ¶
OnPlanArchived is called when a plan is archived.
type OnPlanCreated ¶
OnPlanCreated is called when a new plan is created.
type OnPlanUpdated ¶
type OnPlanUpdated interface {
Plugin
OnPlanUpdated(ctx context.Context, oldPlan, newPlan interface{}) error
}
OnPlanUpdated is called when a plan is updated.
type OnProviderSync ¶
type OnProviderSync interface {
Plugin
OnProviderSync(ctx context.Context, provider string, success bool, err error) error
}
OnProviderSync is called when syncing with a payment provider.
type OnQuotaExceeded ¶
type OnQuotaExceeded interface {
Plugin
OnQuotaExceeded(ctx context.Context, tenantID, featureKey string, used, limit int64) error
}
OnQuotaExceeded is called when a quota is exceeded.
type OnShutdown ¶
OnShutdown is called when the plugin is shutting down.
type OnSoftLimitReached ¶
type OnSoftLimitReached interface {
Plugin
OnSoftLimitReached(ctx context.Context, tenantID, featureKey string, used, limit int64) error
}
OnSoftLimitReached is called when a soft limit is reached.
type OnSubscriptionCancelScheduled ¶
type OnSubscriptionCancelScheduled interface {
Plugin
OnSubscriptionCancelScheduled(ctx context.Context, sub interface{}) error
}
OnSubscriptionCancelScheduled is called when a cancellation is recorded for a later date. The subscription keeps running until then, and OnSubscriptionCanceled fires when the lifecycle clock ends it.
type OnSubscriptionCanceled ¶
type OnSubscriptionCanceled interface {
Plugin
OnSubscriptionCanceled(ctx context.Context, sub interface{}) error
}
OnSubscriptionCanceled is called when a subscription stops: an immediate cancel, or the lifecycle clock enacting a scheduled one. A cancel dated later fires OnSubscriptionCancelScheduled when it is recorded.
type OnSubscriptionChanged ¶
type OnSubscriptionChanged interface {
Plugin
OnSubscriptionChanged(ctx context.Context, sub interface{}, oldPlan, newPlan interface{}) error
}
OnSubscriptionChanged is called when a subscription changes plans.
type OnSubscriptionCreated ¶
type OnSubscriptionCreated interface {
Plugin
OnSubscriptionCreated(ctx context.Context, sub interface{}) error
}
OnSubscriptionCreated is called when a new subscription is created.
type OnSubscriptionExpired ¶
type OnSubscriptionExpired interface {
Plugin
OnSubscriptionExpired(ctx context.Context, sub interface{}) error
}
OnSubscriptionExpired is called when a subscription expires.
type OnSubscriptionRenewed ¶
type OnSubscriptionRenewed interface {
Plugin
OnSubscriptionRenewed(ctx context.Context, renewal interface{}) error
}
OnSubscriptionRenewed is called when the lifecycle clock moves a subscription into a new billing period. It fires once per move and receives a *subscription.Renewal: the subscription in its new period, and every period that ended in the move, oldest first, catch-up periods included. Ledger bills none of them; a plugin that invoices at rollover calls GenerateInvoice with ledger.ForPeriod for each. After a change to a plan's billing period the first rollover can list a period of the old cadence, which ForPeriod refuses. A paused subscription never rolls. A resume stretches its period by the length of the pause, and the stretched period is listed here, once, when its new end passes.
Like every hook the lifecycle clock fires (this one, OnSubscriptionCanceled from an enacted cancel, OnSubscriptionTrialEnded and OnInvoicePastDue), it is delivered at most once, in the process whose store write landed, after that write. ctx carries the run's values but not its deadline or its cancel, so a slow run or a Stop does not cut the call off. The registry stops waiting for a hook after its timeout, but the hook keeps running on that live context and may still finish; what is lost then is its error, which nobody sees. A crash between the write and the call, or a hook that fails, loses the announcement: no later run repeats it. To reconcile, list your subscriptions and, for each, walk back from its current period with ledger.ForPeriod, invoicing every ended period that has no invoice; ErrAlreadyExists marks the ones you already billed.
type OnSubscriptionTrialEnded ¶
type OnSubscriptionTrialEnded interface {
Plugin
OnSubscriptionTrialEnded(ctx context.Context, sub interface{}) error
}
OnSubscriptionTrialEnded is called when the lifecycle clock ends a trial and the subscription becomes active. A pause holds the trial: a resume moves its end on by the length of the pause, and this fires once that later end passes.
type OnUsageFlushed ¶
type OnUsageFlushed interface {
Plugin
OnUsageFlushed(ctx context.Context, count int, elapsed time.Duration) error
}
OnUsageFlushed is called when usage events are flushed to the store.
type OnUsageIngested ¶
type OnUsageIngested interface {
Plugin
OnUsageIngested(ctx context.Context, events []interface{}) error
}
OnUsageIngested is called when usage events are ingested.
type OnWebhookReceived ¶
type OnWebhookReceived interface {
Plugin
OnWebhookReceived(ctx context.Context, provider string, payload []byte) error
}
OnWebhookReceived is called when a webhook is received.
type PaymentProviderPlugin ¶
PaymentProviderPlugin provides a payment provider implementation.
type Plugin ¶
type Plugin interface {
Name() string
}
Plugin is the base interface that all plugins must implement.
type PricingStrategy ¶
type PricingStrategy interface {
Plugin
StrategyName() string
Compute(tiers []interface{}, usage, included int64, currency string) interface{} // Returns Money
}
PricingStrategy provides custom pricing calculation. A feature (or, failing that, its plan) selects a strategy by StrategyName under the metadata key "pricing_strategy". A name that is not registered falls back to the built-in tier pricing.
Compute is called only for usage above the feature's included allowance, and for any positive seat count, where the allowance is zero. It is never called for usage the allowance covers.
Each element of tiers is a plan.PriceTier (a value, not a pointer). The slice holds only the tiers belonging to the feature being priced, sorted into ladder order. usage is the total quantity for the period and included is the allowance. currency is the plan's currency, lowercased.
Compute must return a non-negative types.Money in that currency (compared case-insensitively). A zero Money is the legal "free" answer. Returning nil, any other type, another currency or a negative amount fails invoice generation with an error naming the strategy.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages all registered plugins and provides efficient dispatch. It uses type-cached discovery for O(1) dispatch performance.
func (*Registry) EmitEntitlementChecked ¶
EmitEntitlementChecked emits an entitlement checked event.
func (*Registry) EmitFeatureArchived ¶
EmitFeatureArchived emits a feature archived event.
func (*Registry) EmitFeatureCreated ¶
EmitFeatureCreated emits a feature created event.
func (*Registry) EmitFeatureDeleted ¶
EmitFeatureDeleted emits a feature deleted event.
func (*Registry) EmitFeatureUpdated ¶
EmitFeatureUpdated emits a feature updated event.
func (*Registry) EmitInvoiceFailed ¶
EmitInvoiceFailed emits an invoice payment failed event.
func (*Registry) EmitInvoiceFinalized ¶
EmitInvoiceFinalized emits an invoice finalized event.
func (*Registry) EmitInvoiceGenerated ¶
EmitInvoiceGenerated emits an invoice generated event.
func (*Registry) EmitInvoicePaid ¶
EmitInvoicePaid emits an invoice paid event.
func (*Registry) EmitInvoicePastDue ¶
EmitInvoicePastDue emits an invoice the lifecycle clock marked past due.
func (*Registry) EmitInvoiceVoided ¶
EmitInvoiceVoided emits an invoice voided event.
func (*Registry) EmitPlanArchived ¶
EmitPlanArchived emits a plan archived event.
func (*Registry) EmitPlanCreated ¶
EmitPlanCreated emits a plan created event.
func (*Registry) EmitPlanUpdated ¶
EmitPlanUpdated emits a plan updated event.
func (*Registry) EmitProviderSync ¶
func (r *Registry) EmitProviderSync(ctx context.Context, providerName string, success bool, syncErr error)
EmitProviderSync emits a provider sync event.
func (*Registry) EmitQuotaExceeded ¶
func (r *Registry) EmitQuotaExceeded(ctx context.Context, tenantID, featureKey string, used, limit int64)
EmitQuotaExceeded emits a quota exceeded event.
func (*Registry) EmitShutdown ¶
EmitShutdown calls OnShutdown for all plugins that implement it.
func (*Registry) EmitSoftLimitReached ¶
func (r *Registry) EmitSoftLimitReached(ctx context.Context, tenantID, featureKey string, used, limit int64)
EmitSoftLimitReached emits a soft limit reached event.
func (*Registry) EmitSubscriptionCancelScheduled ¶
EmitSubscriptionCancelScheduled emits a cancellation recorded for a later date.
func (*Registry) EmitSubscriptionCanceled ¶
EmitSubscriptionCanceled emits a subscription canceled event.
func (*Registry) EmitSubscriptionChanged ¶
EmitSubscriptionChanged emits a subscription changed event.
func (*Registry) EmitSubscriptionCreated ¶
EmitSubscriptionCreated emits a subscription created event.
func (*Registry) EmitSubscriptionExpired ¶
EmitSubscriptionExpired emits a subscription expired event.
func (*Registry) EmitSubscriptionRenewed ¶
EmitSubscriptionRenewed emits a subscription moved into a new period, as a *subscription.Renewal.
func (*Registry) EmitSubscriptionTrialEnded ¶
EmitSubscriptionTrialEnded emits a trial ended by the lifecycle clock.
func (*Registry) EmitUsageFlushed ¶
EmitUsageFlushed emits a usage flushed event.
func (*Registry) EmitUsageIngested ¶
EmitUsageIngested emits a usage ingested event.
func (*Registry) EmitWebhookReceived ¶
EmitWebhookReceived emits a webhook received event.
func (*Registry) GetCouponValidators ¶
func (r *Registry) GetCouponValidators() []CouponValidator
GetCouponValidators returns every registered coupon validator.
func (*Registry) GetInvoiceFormatter ¶
func (r *Registry) GetInvoiceFormatter(format string) InvoiceFormatter
GetInvoiceFormatter returns the formatter registered for format, or nil.
func (*Registry) GetPaymentProvider ¶
func (r *Registry) GetPaymentProvider(name string) PaymentProviderPlugin
GetPaymentProvider returns a payment provider plugin by provider name.
func (*Registry) GetPaymentProviders ¶
func (r *Registry) GetPaymentProviders() []PaymentProviderPlugin
GetPaymentProviders returns all registered payment provider plugins.
func (*Registry) GetPricingStrategy ¶
func (r *Registry) GetPricingStrategy(name string) PricingStrategy
GetPricingStrategy returns a pricing strategy by name.
func (*Registry) GetTaxCalculators ¶
func (r *Registry) GetTaxCalculators() []TaxCalculator
GetTaxCalculators returns all registered tax calculators.
func (*Registry) GetUsageAggregator ¶
func (r *Registry) GetUsageAggregator(name string) UsageAggregator
GetUsageAggregator returns the usage aggregator registered under name, or nil.
func (*Registry) HasPaymentProviders ¶
HasPaymentProviders returns true if any payment provider plugins are registered.
func (*Registry) InvoiceFormats ¶
InvoiceFormats returns every registered formatter's format, sorted.
func (*Registry) WithLogger ¶
WithLogger sets the logger for the registry.
func (*Registry) WithMetrics ¶
WithMetrics counts failed hook calls on m as HookFailuresMetric, labeled with the hook (its interface name, such as OnInvoicePaid) and the reason: error, timeout or canceled. A nil m records nothing. Call it before the registry dispatches anything; ledger.New does.
type TaxCalculator ¶
type TaxCalculator interface {
Plugin
CalculateTax(ctx context.Context, subtotal interface{}, tenantID string) (interface{}, error) // Returns Money
}
TaxCalculator calculates tax for invoices.
type UsageAggregator ¶
type UsageAggregator interface {
Plugin
AggregatorName() string
Aggregate(ctx context.Context, events []interface{}) (int64, error)
}
UsageAggregator provides custom usage aggregation logic. A metered feature selects an aggregator by AggregatorName under the metadata key "aggregator". A name that is not registered falls back to the store's own aggregation.
Aggregate is called at most once per metered feature that selects the aggregator, per invoice. It is not called for a metered feature whose Limit is negative (an unlimited allowance can never bill), and it is not called for any feature once an earlier failure has stopped generation, including a feature whose price tiers fail validation.
It receives the usage events for that tenant, app and feature that fall in the billed period, the half-open window [start, end): the period's own bounds once it has ended, and its start to now while it is still running. That is the same window the built-in sum reads, for the current period and for one named with ledger.ForPeriod alike. An event stamped exactly at the start is in the window, and one stamped exactly at the end belongs to the next period, so consecutive invoices never bill the same event twice or skip it.
Each element of events is a *meter.UsageEvent. It is a pointer: asserting the value type meter.UsageEvent fails, and an aggregator that ignores elements it cannot assert will total zero usage, so nothing is billed and nothing reports an error. Assert the pointer type and return an error for anything else.
The return value is the total usage quantity for the period, and it must be non-negative. An error or a negative total fails invoice generation with an error naming the aggregator.