{"modulePath":"github.com/GoCodeAlone/workflow","version":"v0.87.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package billing\n\n## Constants\n\n```go\nconst (\n\tStatusActive   = \"active\"\n\tStatusPastDue  = \"past_due\"\n\tStatusCanceled = \"canceled\"\n\tStatusTrialing = \"trialing\"\n)\n```\nSubscriptionStatus constants for well-known Stripe subscription states.\n\n## Variables\n\n```go\nvar (\n\tPlanFree = Plan{\n\t\tID:                  \"free\",\n\t\tName:                \"Free\",\n\t\tPriceMonthly:        0,\n\t\tExecutionsPerMonth:  1000,\n\t\tMaxPipelines:        5,\n\t\tMaxStepsPerPipeline: 20,\n\t\tRetentionDays:       7,\n\t\tMaxWorkers:          2,\n\t}\n\n\tPlanStarter = Plan{\n\t\tID:                  \"starter\",\n\t\tName:                \"Starter\",\n\t\tPriceMonthly:        4900,\n\t\tExecutionsPerMonth:  50_000,\n\t\tMaxPipelines:        25,\n\t\tMaxStepsPerPipeline: 50,\n\t\tRetentionDays:       30,\n\t\tMaxWorkers:          8,\n\t\tFeatures:            []string{\"email-support\", \"custom-domains\"},\n\t}\n\n\tPlanProfessional = Plan{\n\t\tID:                  \"professional\",\n\t\tName:                \"Professional\",\n\t\tPriceMonthly:        19900,\n\t\tExecutionsPerMonth:  500_000,\n\t\tMaxPipelines:        0,\n\t\tMaxStepsPerPipeline: 0,\n\t\tRetentionDays:       90,\n\t\tMaxWorkers:          32,\n\t\tFeatures:            []string{\"email-support\", \"custom-domains\", \"priority-builds\", \"advanced-analytics\"},\n\t}\n\n\tPlanEnterprise = Plan{\n\t\tID:                  \"enterprise\",\n\t\tName:                \"Enterprise\",\n\t\tPriceMonthly:        0,\n\t\tExecutionsPerMonth:  0,\n\t\tMaxPipelines:        0,\n\t\tMaxStepsPerPipeline: 0,\n\t\tRetentionDays:       365,\n\t\tMaxWorkers:          0,\n\t\tFeatures: []string{\n\t\t\t\"sso\",\n\t\t\t\"multi-region\",\n\t\t\t\"dedicated-infrastructure\",\n\t\t\t\"sla-guarantee\",\n\t\t\t\"priority-support\",\n\t\t\t\"custom-domains\",\n\t\t\t\"advanced-analytics\",\n\t\t\t\"audit-log-export\",\n\t\t},\n\t}\n\n\t// AllPlans is the ordered list of available plans.\n\tAllPlans = []Plan{PlanFree, PlanStarter, PlanProfessional, PlanEnterprise}\n)\n```\nPredefined billing plans.\n\n```go\nvar ErrLimitExceeded = billingError(\"execution limit exceeded for current billing period\")\n```\nErrLimitExceeded is returned by CheckLimit when a tenant has exhausted their plan's execution quota for the current billing period.\n\n## Functions\n\n```go\nfunc CheckLimit(ctx context.Context, meter UsageMeter, tenantID string) error\n```\nCheckLimit is a convenience wrapper for non-HTTP enforcement paths (e.g. gRPC handlers or internal pipeline runners). It returns an error when the tenant has exceeded their plan limit.\n\n## Types\n\n```go\ntype BillingProvider interface {\n\t// CreateCustomer registers a new billing customer for the given tenant.\n\tCreateCustomer(ctx context.Context, tenantID, email string) (customerID string, err error)\n\t// CreateSubscription starts a subscription for the customer on the given plan.\n\tCreateSubscription(ctx context.Context, customerID, planID string) (subscriptionID string, err error)\n\t// CancelSubscription cancels an active subscription.\n\tCancelSubscription(ctx context.Context, subscriptionID string) error\n\t// ReportUsage reports metered usage for a subscription.\n\tReportUsage(ctx context.Context, subscriptionID string, quantity int64) error\n\t// HandleWebhook processes an incoming webhook payload from the payment provider.\n\tHandleWebhook(ctx context.Context, payload []byte, signature string) error\n}\n```\nBillingProvider abstracts payment and subscription management.\n\n```go\ntype EnforcementMiddleware struct {\n\t// contains filtered or unexported fields\n}\n```\nEnforcementMiddleware wraps an HTTP handler and rejects requests from tenants that have exceeded their plan's execution limit.\n\n```go\nfunc NewEnforcementMiddleware(meter UsageMeter, getTenantID TenantIDFunc) *EnforcementMiddleware\n```\nNewEnforcementMiddleware creates an EnforcementMiddleware. The meter is queried on every request; the getTenantID function is used to extract the current tenant from the request context or headers.\n\n```go\nfunc (m *EnforcementMiddleware) Wrap(next http.Handler) http.Handler\n```\nWrap returns an http.Handler that enforces the tenant's execution limit before delegating to next. Requests without a resolvable tenant ID pass through without enforcement.\n\n```go\ntype Handler struct {\n\t// contains filtered or unexported fields\n}\n```\nHandler exposes billing endpoints over HTTP.\n\n```go\nfunc NewHandler(meter UsageMeter, provider BillingProvider) *Handler\n```\nNewHandler creates a new billing HTTP handler.\n\n```go\nfunc (h *Handler) RegisterRoutes(mux *http.ServeMux)\n```\nRegisterRoutes registers billing endpoints on the given mux.\n\n```go\ntype InMemoryMeter struct {\n\t// contains filtered or unexported fields\n}\n```\nInMemoryMeter is a thread-safe in-memory UsageMeter suitable for tests.\n\n```go\nfunc NewInMemoryMeter() *InMemoryMeter\n```\nNewInMemoryMeter creates an InMemoryMeter.\n\n```go\nfunc (m *InMemoryMeter) CheckLimit(_ context.Context, tenantID string) (bool, int64, error)\n```\nCheckLimit checks whether the tenant may run another execution.\n\n```go\nfunc (m *InMemoryMeter) GetUsage(_ context.Context, tenantID string, period time.Time) (*UsageReport, error)\n```\nGetUsage returns the usage report for the given period.\n\n```go\nfunc (m *InMemoryMeter) RecordExecution(_ context.Context, tenantID, pipelineName string) error\n```\nRecordExecution records a single execution for the tenant.\n\n```go\nfunc (m *InMemoryMeter) SetPlan(tenantID, planID string)\n```\nSetPlan associates a tenant with a billing plan.\n\n```go\ntype MockBillingProvider struct {\n\n\t// Customers maps tenantID -\u003e customerID.\n\tCustomers map[string]string\n\t// Subscriptions maps subscriptionID -\u003e planID.\n\tSubscriptions map[string]string\n\t// UsageReports collects (subscriptionID, quantity) pairs.\n\tUsageReports []UsageEntry\n\t// WebhookPayloads collects raw webhook bodies.\n\tWebhookPayloads [][]byte\n\n\t// Error fields allow tests to inject failures.\n\tCreateCustomerErr     error\n\tCreateSubscriptionErr error\n\tCancelSubscriptionErr error\n\tReportUsageErr        error\n\tHandleWebhookErr      error\n\t// contains filtered or unexported fields\n}\n```\nMockBillingProvider is a test double that records calls and returns configurable results.\n\n```go\nfunc NewMockBillingProvider() *MockBillingProvider\n```\nNewMockBillingProvider creates a MockBillingProvider ready for use.\n\n```go\nfunc (m *MockBillingProvider) CancelSubscription(_ context.Context, subscriptionID string) error\n```\nCancelSubscription cancels a mock subscription.\n\n```go\nfunc (m *MockBillingProvider) CreateCustomer(_ context.Context, tenantID, _ string) (string, error)\n```\nCreateCustomer creates a mock customer.\n\n```go\nfunc (m *MockBillingProvider) CreateSubscription(_ context.Context, customerID, planID string) (string, error)\n```\nCreateSubscription creates a mock subscription.\n\n```go\nfunc (m *MockBillingProvider) HandleWebhook(_ context.Context, payload []byte, _ string) error\n```\nHandleWebhook records the webhook payload.\n\n```go\nfunc (m *MockBillingProvider) ReportUsage(_ context.Context, subscriptionID string, quantity int64) error\n```\nReportUsage records a usage report.\n\n```go\ntype Plan struct {\n\tID                  string   `json:\"id\"`\n\tName                string   `json:\"name\"`\n\tPriceMonthly        int      `json:\"price_monthly\"`          // cents\n\tExecutionsPerMonth  int64    `json:\"executions_per_month\"`   // 0 = unlimited\n\tMaxPipelines        int      `json:\"max_pipelines\"`          // 0 = unlimited\n\tMaxStepsPerPipeline int      `json:\"max_steps_per_pipeline\"` // 0 = unlimited\n\tRetentionDays       int      `json:\"retention_days\"`\n\tMaxWorkers          int      `json:\"max_workers\"`\n\tFeatures            []string `json:\"features,omitempty\"`\n}\n```\nPlan represents a billing plan with usage limits.\n\n```go\nfunc PlanByID(id string) *Plan\n```\nPlanByID looks up a plan by its identifier. Returns nil if not found.\n\n```go\nfunc (p Plan) IsUnlimited() bool\n```\nIsUnlimited reports whether the plan has no execution limit.\n\n```go\ntype SQLiteMeter struct {\n\t// contains filtered or unexported fields\n}\n```\nSQLiteMeter is a UsageMeter backed by a SQLite database.\n\n```go\nfunc NewSQLiteMeter(db *sql.DB) (*SQLiteMeter, error)\n```\nNewSQLiteMeter creates a new SQLiteMeter and initialises the schema.\n\n```go\nfunc (m *SQLiteMeter) CheckLimit(ctx context.Context, tenantID string) (bool, int64, error)\n```\nCheckLimit checks whether the tenant may run another execution.\n\n```go\nfunc (m *SQLiteMeter) GetUsage(ctx context.Context, tenantID string, period time.Time) (*UsageReport, error)\n```\nGetUsage returns the usage report for the given period from SQLite.\n\n```go\nfunc (m *SQLiteMeter) RecordExecution(ctx context.Context, tenantID, pipelineName string) error\n```\nRecordExecution records an execution in SQLite.\n\n```go\nfunc (m *SQLiteMeter) SetPlan(tenantID, planID string)\n```\nSetPlan associates a tenant with a billing plan.\n\n```go\ntype StripePlanIDs map[string]string\n```\nStripePlanIDs maps plan IDs to Stripe price IDs (monthly). These must be configured to match Stripe dashboard price objects.\n\n```go\ntype StripeProvider struct {\n\t// contains filtered or unexported fields\n}\n```\nStripeProvider implements BillingProvider using the Stripe API.\n\n```go\nfunc NewStripeProvider(apiKey, webhookSecret string, planPriceIDs StripePlanIDs) *StripeProvider\n```\nNewStripeProvider creates a StripeProvider with the given API key, webhook secret, and mapping from plan IDs to Stripe price IDs.\n\n```go\nfunc (p *StripeProvider) CancelSubscription(_ context.Context, subscriptionID string) error\n```\nCancelSubscription cancels a Stripe subscription at period end.\n\n```go\nfunc (p *StripeProvider) CreateCustomer(_ context.Context, tenantID, email string) (string, error)\n```\nCreateCustomer creates a new Stripe customer for the given tenant.\n\n```go\nfunc (p *StripeProvider) CreateSubscription(_ context.Context, customerID, planID string) (string, error)\n```\nCreateSubscription creates a new Stripe subscription for the customer on the given plan.\n\n```go\nfunc (p *StripeProvider) HandleWebhook(_ context.Context, payload []byte, signature string) error\n```\nHandleWebhook validates the Stripe webhook signature and dispatches known events.\n\n```go\nfunc (p *StripeProvider) ReportUsage(_ context.Context, _ string, _ int64) error\n```\nReportUsage is a no-op for Stripe fixed-price plans. For metered billing, override this to call the Stripe usage records API.\n\n```go\ntype Subscription struct {\n\tID                   string    `json:\"id\"`\n\tCustomerID           string    `json:\"customer_id\"`\n\tPlanID               string    `json:\"plan_id\"`\n\tStatus               string    `json:\"status\"` // active, past_due, canceled, trialing\n\tCurrentPeriodEnd     time.Time `json:\"current_period_end\"`\n\tStripeSubscriptionID string    `json:\"stripe_subscription_id,omitempty\"`\n}\n```\nSubscription represents an active or historical billing subscription for a tenant.\n\n```go\ntype TenantIDFunc func(r *http.Request) string\n```\nTenantIDFunc extracts a tenant ID from an incoming HTTP request. The caller provides this so that enforcement is not coupled to any specific authentication scheme.\n\n```go\ntype UsageEntry struct {\n\tSubscriptionID string\n\tQuantity       int64\n}\n```\nUsageEntry records a single usage report.\n\n```go\ntype UsageMeter interface {\n\t// RecordExecution records a single pipeline execution for the tenant.\n\tRecordExecution(ctx context.Context, tenantID, pipelineName string) error\n\t// GetUsage returns the usage report for the given billing period.\n\tGetUsage(ctx context.Context, tenantID string, period time.Time) (*UsageReport, error)\n\t// CheckLimit checks whether the tenant is allowed to run another execution\n\t// and returns the remaining executions in the current period.\n\tCheckLimit(ctx context.Context, tenantID string) (allowed bool, remaining int64, err error)\n}\n```\nUsageMeter tracks and queries resource consumption per tenant.\n\n```go\ntype UsageReport struct {\n\tTenantID       string    `json:\"tenant_id\"`\n\tPeriod         time.Time `json:\"period\"` // first day of billing period\n\tExecutionCount int64     `json:\"execution_count\"`\n\tPipelineCount  int       `json:\"pipeline_count\"`\n\tStepCount      int       `json:\"step_count\"`\n\tWorkerPeak     int       `json:\"worker_peak\"`\n}\n```\nUsageReport summarizes resource usage for a tenant during a billing period.\n\n","path":"github.com/GoCodeAlone/workflow/billing","name":"billing","synopsis":"","isRedistributable":true}
