ports

package
v2.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 2, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package ports provides ports utilities.

Index

Constants

This section is empty.

Variables

View Source
var ErrResourceMissing = errors.New("resource missing")

ErrResourceMissing signals that a requested external resource was not found.

Functions

This section is empty.

Types

type Authorizer

type Authorizer interface {
	Can(ctx context.Context, subject any, action string, resource any) error
}

Authorizer checks whether a subject can perform an action on a resource.

type AuthorizerFunc

type AuthorizerFunc func(ctx context.Context, subject any, action string, resource any) error

AuthorizerFunc adapts a function to the Authorizer interface.

func (AuthorizerFunc) Can

func (f AuthorizerFunc) Can(ctx context.Context, subject any, action string, resource any) error

Can executes the authorization function.

type BillingPortalSession

type BillingPortalSession struct {
	ID  string
	URL string
}

BillingPortalSession represents a customer portal session.

type BillingPortalSessionInput

type BillingPortalSessionInput struct {
	CustomerID string
	ReturnURL  string
	Locale     string
}

BillingPortalSessionInput describes a customer portal session request.

type BillingProvider

type BillingProvider interface {
	CreateCustomer(ctx context.Context, in CustomerInput) (Customer, error)
	UpdateCustomer(ctx context.Context, customerID string, in CustomerInput) error
	CreateSetupIntent(ctx context.Context, in SetupIntentInput) (SetupIntent, error)
	SetCustomerDefaultPaymentMethod(ctx context.Context, customerID, paymentMethodID string) error
	RetrievePaymentMethod(ctx context.Context, paymentMethodID string) (PaymentMethod, error)
	CreateInvoiceItem(ctx context.Context, in InvoiceItemInput) (InvoiceItem, error)
	RetrieveInvoiceItem(ctx context.Context, invoiceItemID string) (InvoiceItem, error)
	UpdateInvoiceItem(ctx context.Context, invoiceItemID string, in InvoiceItemUpdate) (InvoiceItem, error)
	CreateInvoice(ctx context.Context, in InvoiceInput) (Invoice, error)
	FinalizeInvoice(ctx context.Context, invoiceID string) (Invoice, error)
	PayInvoice(ctx context.Context, invoiceID string) (Invoice, error)
	RetrieveInvoice(ctx context.Context, invoiceID string) (Invoice, error)
	CreateBillingPortalSession(ctx context.Context, in BillingPortalSessionInput) (BillingPortalSession, error)
}

BillingProvider defines billing-related operations for hosted invoicing.

type CORSHandler

type CORSHandler interface {
	Handler(opts CORSOptions) func(http.Handler) http.Handler
}

CORSHandler defines the interface for CORS handling.

type CORSOptions

type CORSOptions struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	AllowCredentials bool
	MaxAge           int
}

CORSOptions defines CORS configuration.

type CheckoutSession

type CheckoutSession struct {
	ID  string
	URL string
}

CheckoutSession represents a provider-created hosted checkout session.

type CheckoutSessionRequest

type CheckoutSessionRequest struct {
	Amount               int64             // Minor units (cents)
	Currency             string            // ISO currency, e.g. "eur"
	PriceID              string            // Provider-specific price ID (preferred)
	SuccessURL           string            // Where to redirect on success
	CancelURL            string            // Where to redirect on cancellation
	Metadata             map[string]string // Arbitrary key/value for reconciliation
	Mode                 string            // "payment" | "subscription"
	Locale               string            // Optional locale code, provider-specific
	CustomerID           string            // Optional provider customer ID
	CustomerEmail        string            // Optional customer email address
	ClientReferenceID    string            // Optional client-side correlation ID
	SubscriptionMetadata map[string]string // Metadata for subscription objects
}

CheckoutSessionRequest describes a hosted checkout request (e.g. Stripe Checkout).

type Clock

type Clock interface {
	Now() time.Time
}

Clock allows deterministic tests.

type Customer

type Customer struct {
	ID string
}

Customer represents a billing customer.

type CustomerAddress

type CustomerAddress struct {
	Line1      string
	Line2      string
	City       string
	State      string
	PostalCode string
	Country    string
}

CustomerAddress describes a customer's billing address.

type CustomerInput

type CustomerInput struct {
	Name     string
	Email    string
	Phone    string
	Address  *CustomerAddress
	Metadata map[string]string
}

CustomerInput describes a new billing customer.

type DatabaseConnection

type DatabaseConnection interface {
	Query(ctx context.Context, sql string, args ...any) (DatabaseRows, error)
	QueryRow(ctx context.Context, sql string, args ...any) DatabaseRow
	Exec(ctx context.Context, sql string, args ...any) (DatabaseResult, error)
	Begin(ctx context.Context) (DatabaseTransaction, error)
	Release()
}

DatabaseConnection defines the interface for individual database connections.

type DatabasePool

type DatabasePool interface {
	Ping(ctx context.Context) error
	Close()
	Acquire(ctx context.Context) (DatabaseConnection, error)
	Stat() DatabaseStats
}

DatabasePool defines the interface for database connection pooling.

type DatabaseResult

type DatabaseResult interface {
	RowsAffected() int64
}

DatabaseResult defines the interface for query execution results.

type DatabaseRow

type DatabaseRow interface {
	Scan(dest ...any) error
}

DatabaseRow defines the interface for a single query result row.

type DatabaseRows

type DatabaseRows interface {
	Next() bool
	Scan(dest ...any) error
	Close()
	Err() error
}

DatabaseRows defines the interface for query result rows.

type DatabaseStats

type DatabaseStats interface {
	AcquireCount() int64
	AcquireDuration() time.Duration
	AcquiredConns() int32
	CanceledAcquireCount() int64
	ConstructingConns() int32
	EmptyAcquireCount() int64
	IdleConns() int32
	MaxConns() int32
	NewConnsCount() int64
	TotalConns() int32
}

DatabaseStats defines the interface for database pool statistics.

type DatabaseTransaction

type DatabaseTransaction interface {
	Query(ctx context.Context, sql string, args ...any) (DatabaseRows, error)
	QueryRow(ctx context.Context, sql string, args ...any) DatabaseRow
	Exec(ctx context.Context, sql string, args ...any) (DatabaseResult, error)
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

DatabaseTransaction defines the interface for database transactions.

type DetailedHealthResponse

type DetailedHealthResponse struct {
	Status    HealthStatus            `json:"status"`
	Timestamp time.Time               `json:"timestamp"`
	Checks    map[string]HealthResult `json:"checks"`
	Summary   HealthSummary           `json:"summary"`
}

DetailedHealthResponse represents a detailed health response with individual checks.

type DocsConfig

type DocsConfig struct {
	Title       string    `json:"title"`
	Description string    `json:"description"`
	Version     string    `json:"version"`
	Contact     string    `json:"contact,omitempty"`
	License     string    `json:"license,omitempty"`
	Paths       DocsPaths `json:"paths"`
	EnableHTML  bool      `json:"enable_html"`
	EnableJSON  bool      `json:"enable_json"`
	EnableYAML  bool      `json:"enable_yaml"`
}

DocsConfig defines configuration for documentation.

type DocsInfo

type DocsInfo struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Version     string `json:"version"`
	Contact     string `json:"contact,omitempty"`
	License     string `json:"license,omitempty"`
}

DocsInfo provides information about the API documentation.

type DocsManager

type DocsManager interface {
	RegisterProvider(provider DocsProvider)
	GetHTML() (string, error)
	GetOpenAPI() ([]byte, error)
	GetVersion() (string, error)
	GetInfo() DocsInfo
	ServeHTML(w http.ResponseWriter, r *http.Request)
	ServeOpenAPI(w http.ResponseWriter, r *http.Request)
	ServeVersion(w http.ResponseWriter, r *http.Request)
	ServeInfo(w http.ResponseWriter, r *http.Request)
}

DocsManager defines the interface for managing documentation.

type DocsPaths

type DocsPaths struct {
	HTML    string `json:"html"`
	OpenAPI string `json:"openapi"`
	Version string `json:"version"`
	Info    string `json:"info"`
}

DocsPaths defines the paths for documentation endpoints.

func DefaultDocsPaths

func DefaultDocsPaths() DocsPaths

DefaultDocsPaths returns the default documentation endpoint paths.

type DocsProvider

type DocsProvider interface {
	GetHTML() (string, error)
	GetOpenAPI() ([]byte, error)
	GetVersion() (string, error)
	GetInfo() DocsInfo
}

DocsProvider defines the interface for providing documentation content.

type EnvVar

type EnvVar interface {
	// LoadEnvFiles loads environment variables from specific files.
	LoadEnvFiles(paths []string) error
	// Get returns the value and if it exists.
	Get(key string) (string, bool)
	// GetOr returns the value or default if not present.
	GetOr(key, def string) string
	// MustGet returns the value or panics if not present.
	MustGet(key string) string
	// GetBoolOr returns the value as boolean or default if not present.
	GetBoolOr(key string, def bool) bool
	// MustGetBool returns the value as a boolean or panics if not present.
	MustGetBool(key string) bool
	// GetIntOr returns the value as an integer or default if not present.
	GetIntOr(key string, def int) int
	// MustGetInt returns the value as an integer or panics if not present.
	MustGetInt(key string) int
	// GetInt64Or returns the value as an int64 or default if not present.
	GetInt64Or(key string, def int64) int64
	// MustGetInt64 returns the value as an int64 or panics if not present.
	MustGetInt64(key string) int64
	// GetUintOr returns the value as a uint or default if not present.
	GetUintOr(key string, def uint) uint
	// MustGetUint returns the value as a uint or panics if not present.
	MustGetUint(key string) uint
	// GetUint64Or returns the value as a uint64 or default if not present.
	GetUint64Or(key string, def uint64) uint64
	// MustGetUint64 returns the value as a uint64 or panics if not present.
	MustGetUint64(key string) uint64
	// GetFloat64Or returns the value as a float64 or default if not present.
	GetFloat64Or(key string, def float64) float64
	// MustGetFloat64 returns the value as a float64 or panics if not present.
	MustGetFloat64(key string) float64
	// MustGetDuration returns the value as a duration or panics if not present.
	MustGetDuration(key string) time.Duration
	// GetDurationOr returns the value as a duration or default if not present.
	GetDurationOr(key string, def time.Duration) time.Duration
	// Bind populates a struct from environment variables.
	Bind(dst any) error
	// MustBind panics on binding errors.
	MustBind(dst any)
	// BindWithPrefix binds with a prefix.
	BindWithPrefix(dst any, prefix string) error
	// MustBindWithPrefix panics on binding errors with prefix.
	MustBindWithPrefix(dst any, prefix string)
	// DumpRedacted returns environment with secrets redacted.
	DumpRedacted() map[string]string
}

EnvVar manages environment variables with typed getters.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient describes an outbound HTTP client.

type HTTPMiddleware

type HTTPMiddleware interface {
	RequestID() func(http.Handler) http.Handler
	RealIP() func(http.Handler) http.Handler
	Recoverer() func(http.Handler) http.Handler
}

HTTPMiddleware defines the interface for HTTP middleware.

type HTTPRouter

type HTTPRouter interface {
	http.Handler
	Get(pattern string, h http.HandlerFunc)
	Post(pattern string, h http.HandlerFunc)
	Put(pattern string, h http.HandlerFunc)
	Delete(pattern string, h http.HandlerFunc)
	Mount(pattern string, h http.Handler)
	Use(middlewares ...func(http.Handler) http.Handler)
}

HTTPRouter defines the interface for HTTP routing.

type HealthCheckConfig

type HealthCheckConfig struct {
	Timeout         time.Duration `json:"timeout"`
	CacheDuration   time.Duration `json:"cache_duration"`
	EnableCaching   bool          `json:"enable_caching"`
	EnableDetailed  bool          `json:"enable_detailed"`
	LivenessChecks  []string      `json:"liveness_checks"`
	ReadinessChecks []string      `json:"readiness_checks"`
}

HealthCheckConfig defines configuration for health checks.

type HealthCheckRegistry

type HealthCheckRegistry interface {
	Register(name string, checker HealthChecker)
	Unregister(name string)
	GetChecker(name string) (HealthChecker, bool)
	ListCheckers() []string
}

HealthCheckRegistry defines the interface for registering health checks.

type HealthChecker

type HealthChecker interface {
	Name() string
	Check(ctx context.Context) HealthResult
}

HealthChecker defines the interface for individual health checks.

type HealthManager

type HealthManager interface {
	RegisterChecker(checker HealthChecker)
	RegisterCheckers(checkers ...HealthChecker)
	GetLiveness(ctx context.Context) HealthResult
	GetReadiness(ctx context.Context) HealthResult
	GetHealth(ctx context.Context) HealthResponse
	GetDetailedHealth(ctx context.Context) DetailedHealthResponse
}

HealthManager defines the interface for managing health checks.

type HealthResponse

type HealthResponse struct {
	Status    HealthStatus `json:"status"`
	Timestamp time.Time    `json:"timestamp"`
	Message   string       `json:"message,omitempty"`
}

HealthResponse represents the overall health response.

type HealthResult

type HealthResult struct {
	Status    HealthStatus  `json:"status"`
	Message   string        `json:"message,omitempty"`
	Details   interface{}   `json:"details,omitempty"`
	Timestamp time.Time     `json:"timestamp"`
	Duration  time.Duration `json:"duration,omitempty"`
}

HealthResult represents the result of a health check.

type HealthStatus

type HealthStatus string

HealthStatus represents the status of a health check.

const (
	// HealthStatusHealthy indicates all checks are passing.
	HealthStatusHealthy HealthStatus = "healthy"
	// HealthStatusUnhealthy indicates one or more checks failed.
	HealthStatusUnhealthy HealthStatus = "unhealthy"
	// HealthStatusDegraded indicates partial degradation.
	HealthStatusDegraded HealthStatus = "degraded"
	// HealthStatusUnknown indicates indeterminate health.
	HealthStatusUnknown HealthStatus = "unknown"
)

type HealthSummary

type HealthSummary struct {
	Total     int `json:"total"`
	Healthy   int `json:"healthy"`
	Unhealthy int `json:"unhealthy"`
	Degraded  int `json:"degraded"`
	Unknown   int `json:"unknown"`
}

HealthSummary provides a summary of all health checks.

type IDGen

type IDGen interface {
	New() string
}

IDGen generates unique IDs.

type IdempotencyRecord

type IdempotencyRecord struct {
	State       IdempotencyState
	RequestHash string
	Status      int
	Header      http.Header
	Body        []byte
	CreatedAt   time.Time
}

IdempotencyRecord captures request/response material for idempotent retries.

type IdempotencyState

type IdempotencyState int

IdempotencyState describes the lifecycle of a stored idempotency record.

const (
	// IdempotencyStateUnknown indicates no stored state.
	IdempotencyStateUnknown IdempotencyState = iota
	// IdempotencyStateInFlight indicates a request is being processed.
	IdempotencyStateInFlight
	// IdempotencyStateCompleted indicates a request has a stored response.
	IdempotencyStateCompleted
)

type IdempotencyStore

type IdempotencyStore interface {
	Get(ctx context.Context, key string) (IdempotencyRecord, bool, error)
	TryBegin(ctx context.Context, key string, record IdempotencyRecord, ttl time.Duration) (bool, error)
	Save(ctx context.Context, key string, record IdempotencyRecord, ttl time.Duration) error
}

IdempotencyStore persists idempotency records (Redis/DB/etc).

type Invoice

type Invoice struct {
	ID               string
	Status           string
	Currency         string
	AmountDue        int64
	AmountPaid       int64
	HostedInvoiceURL string
	CreatedAt        time.Time
	DueDate          *time.Time
	FinalizedAt      *time.Time
	PaidAt           *time.Time
}

Invoice represents a billing invoice.

type InvoiceInput

type InvoiceInput struct {
	CustomerID                  string
	AutoAdvance                 bool
	AutomaticTax                bool
	CollectionMethod            string
	DueDays                     *int
	PendingInvoiceItemsBehavior string
	Metadata                    map[string]string
	IdempotencyKey              string
}

InvoiceInput describes a draft invoice creation request.

type InvoiceItem

type InvoiceItem struct {
	ID        string
	InvoiceID string
}

InvoiceItem represents a created invoice item.

type InvoiceItemInput

type InvoiceItemInput struct {
	CustomerID     string
	Amount         int64
	Currency       string
	Description    string
	TaxBehavior    string
	Metadata       map[string]string
	IdempotencyKey string
}

InvoiceItemInput describes a pending invoice item.

type InvoiceItemUpdate

type InvoiceItemUpdate struct {
	TaxBehavior string
}

InvoiceItemUpdate describes a patch for an invoice item.

type Logger

type Logger interface {
	Debug(msg string, kv ...any)
	Info(msg string, kv ...any)
	Warn(msg string, kv ...any)
	Error(msg string, kv ...any)
}

Logger is a tiny façade to avoid vendor lock-in.

type Middleware

type Middleware interface {
	Middleware() func(http.Handler) http.Handler
}

Middleware defines the interface for middlewares.

type Migrator

type Migrator interface {
	Up(ctx context.Context, dir string) error
	Down(ctx context.Context, dir string) error
	Status(ctx context.Context, dir string) (string, error)
	Close() error
}

Migrator defines an interface for database migrations.

type NopLogger

type NopLogger struct{}

NopLogger is a no-op logger for safe defaults.

func (NopLogger) Debug

func (NopLogger) Debug(string, ...any)

Debug implements Logger.

func (NopLogger) Error

func (NopLogger) Error(string, ...any)

Error implements Logger.

func (NopLogger) Info

func (NopLogger) Info(string, ...any)

Info implements Logger.

func (NopLogger) Warn

func (NopLogger) Warn(string, ...any)

Warn implements Logger.

type PaymentMethod

type PaymentMethod struct {
	ID       string
	Brand    string
	Last4    string
	ExpMonth int
	ExpYear  int
}

PaymentMethod describes a stored payment method.

type PaymentProvider

type PaymentProvider interface {
	CreateCheckoutSession(ctx context.Context, req CheckoutSessionRequest) (CheckoutSession, error)
	ParseWebhook(ctx context.Context, payload []byte, sigHeader string) (WebhookEvent, error)
	ListPrices(ctx context.Context) ([]Price, error)
}

PaymentProvider defines a hosted checkout + webhook contract.

type PolicyDecision

type PolicyDecision struct {
	Allow  bool
	Reason string
	Data   any
}

PolicyDecision represents the outcome of a policy evaluation. Data may contain adapter-specific details for diagnostics.

type PolicyEngine

type PolicyEngine interface {
	Evaluate(ctx context.Context, req PolicyRequest) (PolicyDecision, error)
}

PolicyEngine evaluates policy requests.

type PolicyRequest

type PolicyRequest struct {
	Subject  any
	Action   string
	Resource any
	Context  any
}

PolicyRequest captures inputs for policy engine evaluation. Context carries request-scoped attributes in a format understood by the adapter.

type Price

type Price struct {
	ID         string
	ProductID  string
	Currency   string
	UnitAmount int64
	Nickname   string
	Metadata   map[string]string
	Active     bool
}

Price represents a payment provider price.

type RateLimiter

type RateLimiter interface {
	Allow(ctx context.Context, key string) (allowed bool, retryAfter time.Duration, err error)
}

RateLimiter defines a distributed rate limiter contract.

type SetupIntent

type SetupIntent struct {
	ID              string
	ClientSecret    string
	CustomerID      string
	PaymentMethodID string
}

SetupIntent represents a setup intent response.

type SetupIntentInput

type SetupIntentInput struct {
	CustomerID string
	Usage      string
	Metadata   map[string]string
}

SetupIntentInput describes a payment method setup intent request.

type SystemClock

type SystemClock struct{}

SystemClock implements Clock using time.Now.

func (SystemClock) Now

func (SystemClock) Now() time.Time

Now returns the current time.

type TxManager

type TxManager interface {
	WithinTx(ctx context.Context, fn func(ctx context.Context) error) error
}

TxManager runs a function within a transaction boundary.

type URLParamExtractor

type URLParamExtractor interface {
	URLParam(r *http.Request, key string) string
}

URLParamExtractor defines the interface for extracting URL parameters.

type Validator

type Validator interface {
	Validate(ctx context.Context, value interface{}) error
	ValidateStruct(ctx context.Context, obj interface{}) error
	ValidateField(ctx context.Context, obj interface{}, field string) error
}

Validator defines the interface for input validation.

type VersionInfo

type VersionInfo struct {
	Version string `json:"version"`
	Commit  string `json:"commit"`
	Date    string `json:"date"`
}

VersionInfo describes application build information.

type WebhookEvent

type WebhookEvent struct {
	ID        string
	Type      string
	CreatedAt time.Time
	Payload   json.RawMessage
}

WebhookEvent is a generic payment provider webhook payload wrapper.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL