ports

package
v2.1.0 Latest Latest
Warning

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

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

Documentation

Overview

Package ports provides toolkit-wide boundary contracts.

Optional HTTP handler behavior is exposed through exported, narrow capability interfaces such as DetailedHealthManager, CachedHealthManager, and DocsHTMLModeProvider so external implementations can discover the full public contract without depending on package-private handler details.

Most contracts in this package are intended to stay adapter-neutral. Compatibility-sensitive exceptions remain stable for v2 source compatibility only: the provider-shaped billing contracts in billing.go are deprecated in favor of github.com/aatuh/api-toolkit/v2/compat/billing, and the driver-shaped database stats contracts in database.go should be replaced in new code by DatabasePoolSnapshotProvider, SnapshotDatabasePoolStats, or adapter StatSnapshot methods. The legacy response writer package is similarly retained for v2 callers while new response code should use httpx. See docs/ports-surface.md and docs/v3-compatibility-roadmap.md for the containment and removal plan.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrLegacyInFlightReservationMissingToken = errors.New("idempotency reservation token is missing from legacy in-flight record")

ErrLegacyInFlightReservationMissingToken indicates a legacy in-flight idempotency reservation was recovered from mixed-version operation without a reservation token.

View Source
var ErrLegacyInFlightTokenMismatch = errors.New("idempotency reservation token mismatch")

ErrLegacyInFlightTokenMismatch indicates a legacy in-flight idempotency reservation was rejected due to token mismatch.

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 BillingPortalFlowAfterCompletion deprecated added in v2.1.0

type BillingPortalFlowAfterCompletion struct {
	Type              BillingPortalFlowAfterCompletionType
	RedirectReturnURL string
}

BillingPortalFlowAfterCompletion configures the post-flow behavior.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowAfterCompletion.

type BillingPortalFlowAfterCompletionType deprecated added in v2.1.0

type BillingPortalFlowAfterCompletionType string

BillingPortalFlowAfterCompletionType describes behavior once a deep-link flow completes.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowAfterCompletionType.

const (
	// BillingPortalFlowAfterCompletionTypeRedirect redirects customer to provided URL after completion.
	//
	// Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowAfterCompletionTypeRedirect.
	BillingPortalFlowAfterCompletionTypeRedirect BillingPortalFlowAfterCompletionType = "redirect"
)

type BillingPortalFlowData deprecated added in v2.1.0

type BillingPortalFlowData struct {
	Type                      BillingPortalFlowType
	AfterCompletion           *BillingPortalFlowAfterCompletion
	SubscriptionUpdateConfirm *BillingPortalFlowSubscriptionUpdateConfirm
}

BillingPortalFlowData configures a deep-link flow in billing portal session creation.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowData.

type BillingPortalFlowSubscriptionUpdateConfirm deprecated added in v2.1.0

type BillingPortalFlowSubscriptionUpdateConfirm struct {
	SubscriptionID string
	Items          []BillingPortalFlowSubscriptionUpdateConfirmItem
}

BillingPortalFlowSubscriptionUpdateConfirm configures a targeted subscription update confirmation.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowSubscriptionUpdateConfirm.

type BillingPortalFlowSubscriptionUpdateConfirmItem deprecated added in v2.1.0

type BillingPortalFlowSubscriptionUpdateConfirmItem struct {
	SubscriptionItemID string
	PriceID            string
	Quantity           int64
}

BillingPortalFlowSubscriptionUpdateConfirmItem describes one item update inside confirm flow.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowSubscriptionUpdateConfirmItem.

type BillingPortalFlowType deprecated added in v2.1.0

type BillingPortalFlowType string

BillingPortalFlowType describes customer portal deep-link flow types.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowType.

const (
	// BillingPortalFlowTypeSubscriptionUpdateConfirm opens a confirmation flow for a specific plan update.
	//
	// Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalFlowTypeSubscriptionUpdateConfirm.
	BillingPortalFlowTypeSubscriptionUpdateConfirm BillingPortalFlowType = "subscription_update_confirm"
)

type BillingPortalSession deprecated

type BillingPortalSession struct {
	ID  string
	URL string
}

BillingPortalSession represents a customer portal session.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalSession.

type BillingPortalSessionInput deprecated

type BillingPortalSessionInput struct {
	CustomerID string
	ReturnURL  string
	Locale     string
	Flow       *BillingPortalFlowData
}

BillingPortalSessionInput describes a customer portal session request.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingPortalSessionInput.

type BillingProvider deprecated

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.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.BillingProvider.

This is a compatibility-sensitive v2 surface. It is currently shaped around provider-specific customer, invoicing, and billing-portal workflows and is a candidate for extraction in v3.

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 CachedHealthManager added in v2.1.0

type CachedHealthManager interface {
	CachedHealth() (HealthResponse, bool)
}

CachedHealthManager is an optional capability for health managers that exposes a reusable health snapshot for middleware and other request-path callers that should avoid probing dependencies inline.

type CheckoutSession deprecated

type CheckoutSession struct {
	ID  string
	URL string
}

CheckoutSession represents a provider-created hosted checkout session.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.CheckoutSession.

type CheckoutSessionRequest deprecated

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.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.CheckoutSessionRequest.

This billing surface is compatibility-sensitive in v2 and currently models a Stripe-like hosted checkout flow rather than a provider-neutral abstraction.

type Clock

type Clock interface {
	Now() time.Time
}

Clock allows deterministic tests.

type Customer deprecated

type Customer struct {
	ID string
}

Customer represents a billing customer.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.Customer.

type CustomerAddress deprecated

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

CustomerAddress describes a customer's billing address.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.CustomerAddress.

type CustomerInput deprecated

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

CustomerInput describes a new billing customer.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.CustomerInput.

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.

The query, transaction, and lifecycle methods are intended to stay generic. Stat is retained as a v2 compatibility surface for adapters that already expose driver-shaped counters. New observability call sites that only need plain values should prefer the optional DatabasePoolSnapshotProvider capability with SnapshotDatabasePoolStats.

type DatabasePoolSnapshot added in v2.1.0

type DatabasePoolSnapshot struct {
	AcquireCount         int64
	AcquireDuration      time.Duration
	AcquiredConns        int32
	CanceledAcquireCount int64
	ConstructingConns    int32
	EmptyAcquireCount    int64
	IdleConns            int32
	MaxConns             int32
	NewConnsCount        int64
	TotalConns           int32
}

DatabasePoolSnapshot captures database pool stats as plain values.

func SnapshotDatabasePoolStats added in v2.1.0

func SnapshotDatabasePoolStats(pool DatabasePool) DatabasePoolSnapshot

SnapshotDatabasePoolStats copies pool stats into a value snapshot.

It prefers the optional DatabasePoolSnapshotProvider capability and falls back to the legacy DatabaseStats interface when necessary.

Example
pool := &snapshotOnlyDatabasePool{
	snapshot: DatabasePoolSnapshot{
		IdleConns:  3,
		TotalConns: 4,
	},
}

snapshot := SnapshotDatabasePoolStats(pool)
fmt.Println(snapshot.IdleConns, snapshot.TotalConns)
Output:
3 4

func SnapshotDatabaseStats added in v2.1.0

func SnapshotDatabaseStats(stats DatabaseStats) DatabasePoolSnapshot

SnapshotDatabaseStats copies database stats into a value snapshot.

type DatabasePoolSnapshotProvider added in v2.1.0

type DatabasePoolSnapshotProvider interface {
	StatSnapshot() DatabasePoolSnapshot
}

DatabasePoolSnapshotProvider is an optional capability for pools that can expose plain-value pool statistics without forcing callers to depend on the legacy DatabaseStats shape.

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 database pool statistics.

This interface mirrors pgxpool-style counters and remains in v2 as a compatibility-sensitive surface. New generic call sites should treat it as an adapter-compatibility shape and prefer DatabasePoolSnapshotProvider or SnapshotDatabasePoolStats instead.

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 DetailedHealthManager added in v2.1.0

type DetailedHealthManager interface {
	DetailedHealthEnabled() bool
}

DetailedHealthManager is an optional capability for health managers that allows HTTP handler packages to decide whether detailed health routes should be registered or served.

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"`
	HTMLMode    DocsHTMLMode `json:"html_mode,omitempty"`
}

DocsConfig defines configuration for documentation.

EnableHTML controls whether the HTML docs surface is served. EnableJSON and EnableYAML control which OpenAPI formats may be served through the configured OpenAPI path.

type DocsHTMLMode added in v2.1.0

type DocsHTMLMode string

DocsHTMLMode controls the HTML presentation mode for the docs surface.

const (
	// DocsHTMLModeSwaggerUI renders the Swagger UI convenience page.
	DocsHTMLModeSwaggerUI DocsHTMLMode = "swagger-ui"
	// DocsHTMLModeStatic renders a first-party static landing page without third-party assets.
	DocsHTMLModeStatic DocsHTMLMode = "static"
)

type DocsHTMLModeProvider added in v2.1.0

type DocsHTMLModeProvider interface {
	HTMLMode() DocsHTMLMode
}

DocsHTMLModeProvider is an optional capability for docs managers that exposes the configured HTML rendering mode to HTTP handler packages.

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.

Implementations should treat disabled or missing docs surfaces as not found rather than silently fabricating placeholder content. HTTP handler packages may also inspect the exported DocsHTMLModeProvider capability instead of relying on package-private knowledge about concrete managers.

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.

Contract:

  • Timeout bounds a single liveness, readiness, or detailed health pass.
  • CacheDuration controls how long individual checker results may be reused when EnableCaching is true.
  • EnableDetailed controls whether HTTP packages should expose detailed health output that includes per-check dependency information.
  • LivenessChecks and ReadinessChecks should name at least one checker each; empty probe lists are invalid configuration and should not be reported as healthy.

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.

HTTP handler packages may opt into additional health behavior through the exported DetailedHealthManager and CachedHealthManager capability interfaces instead of relying on package-private knowledge about concrete managers.

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
	ReservationToken string
}

IdempotencyRecord captures request/response material for idempotent retries.

type IdempotencyReleaser added in v2.1.0

type IdempotencyReleaser interface {
	Release(ctx context.Context, key string) error
}

IdempotencyReleaser removes an in-flight reservation or stale record.

Release keeps the v2-compatible source contract. It should be a no-op when the key is missing, expired, completed, or ambiguous, and may remove an in-flight record by key without checking ReservationToken. New stores should also implement IdempotencyReservationReleaser so middleware can use token-aware cleanup for current in-flight reservations.

The idempotency middleware requires release semantics so non-stored outcomes can reopen a key safely for later retries without deleting completed replay records or ambiguous safety records.

type IdempotencyReservationReleaser added in v2.1.0

type IdempotencyReservationReleaser interface {
	ReleaseReservation(ctx context.Context, key string, token string) error
}

IdempotencyReservationReleaser removes an in-flight reservation using the reservation token recorded by the middleware.

ReleaseReservation must be a no-op when the key is missing, expired, completed, or ambiguous. It must delete only the current in-flight record when token matches ReservationToken. Distributed stores must make the compare-and-delete operation atomic so a stale releaser cannot delete a newer reservation that replaced an expired or otherwise interleaved record. It must preserve tokened in-flight records when token does not match and return ErrLegacyInFlightTokenMismatch. Legacy tokenless in-flight records may be deleted only when callers also pass an empty token; implementations should return ErrLegacyInFlightReservationMissingToken after deleting that legacy record so mixed-version recovery paths can emit compatibility telemetry. Passing a non-empty token for a legacy tokenless record must preserve the record and return ErrLegacyInFlightTokenMismatch. Malformed records should be preserved and reported as decode errors.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/aatuh/api-toolkit/v2/ports"
)

type exampleTokenAwareStore struct{}

func (exampleTokenAwareStore) Get(context.Context, string) (ports.IdempotencyRecord, bool, error) {
	return ports.IdempotencyRecord{}, false, nil
}

func (exampleTokenAwareStore) TryBegin(context.Context, string, ports.IdempotencyRecord, time.Duration) (bool, error) {
	return true, nil
}

func (exampleTokenAwareStore) Save(context.Context, string, ports.IdempotencyRecord, time.Duration) error {
	return nil
}

func (exampleTokenAwareStore) Release(context.Context, string) error {
	return nil
}

func (exampleTokenAwareStore) ReleaseReservation(_ context.Context, _ string, token string) error {
	if token == "" {
		return ports.ErrLegacyInFlightReservationMissingToken
	}
	return nil
}

func main() {
	var store ports.ReservationReleasableIdempotencyStore = exampleTokenAwareStore{}

	record := ports.IdempotencyRecord{
		State:            ports.IdempotencyStateInFlight,
		Status:           http.StatusAccepted,
		ReservationToken: "reservation-token",
	}
	ok, _ := store.TryBegin(context.Background(), "orders:create:1", record, 30*time.Second)
	_ = store.ReleaseReservation(context.Background(), "orders:create:1", record.ReservationToken)

	fmt.Println(ok)
}
Output:
true

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
	// IdempotencyStateAmbiguous indicates a request may have completed, but its
	// replay-safe response state could not be persisted.
	IdempotencyStateAmbiguous
)

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 deprecated

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.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.Invoice.

type InvoiceInput deprecated

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.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.InvoiceInput.

type InvoiceItem deprecated

type InvoiceItem struct {
	ID        string
	InvoiceID string
}

InvoiceItem represents a created invoice item.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.InvoiceItem.

type InvoiceItemInput deprecated

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.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.InvoiceItemInput.

type InvoiceItemUpdate deprecated

type InvoiceItemUpdate struct {
	TaxBehavior string
}

InvoiceItemUpdate describes a patch for an invoice item.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.InvoiceItemUpdate.

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 MethodRouteRegistrar added in v2.1.0

type MethodRouteRegistrar interface {
	Get(pattern string, h http.HandlerFunc)
}

MethodRouteRegistrar defines the minimal route registration surface used by GET-only handlers.

type Middleware

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

Middleware defines the interface for middlewares.

type MiddlewareChain added in v2.1.0

type MiddlewareChain interface {
	Use(middlewares ...func(http.Handler) http.Handler)
}

MiddlewareChain defines the minimal middleware registration surface used by composed profiles.

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 deprecated

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

PaymentMethod describes a stored payment method.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.PaymentMethod.

type PaymentProvider deprecated

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.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.PaymentProvider.

This is a compatibility-sensitive v2 surface. It intentionally reflects the current hosted-checkout provider model and should not be presented as a universal billing abstraction.

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 deprecated

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.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.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 ReleasableIdempotencyStore added in v2.1.0

type ReleasableIdempotencyStore interface {
	IdempotencyStore
	IdempotencyReleaser
}

ReleasableIdempotencyStore combines persistence and release semantics for idempotent request processing.

type ReservationReleasableIdempotencyStore added in v2.1.0

type ReservationReleasableIdempotencyStore interface {
	ReleasableIdempotencyStore
	IdempotencyReservationReleaser
}

ReservationReleasableIdempotencyStore combines persistence, legacy release, and token-aware release semantics for idempotent request processing.

type SetupIntent deprecated

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

SetupIntent represents a setup intent response.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.SetupIntent.

type SetupIntentInput deprecated

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

SetupIntentInput describes a payment method setup intent request.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.SetupIntentInput.

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 validates a value using adapter-defined semantics.
	Validate(ctx context.Context, value interface{}) error
	// ValidateStruct validates a struct or pointer to struct.
	ValidateStruct(ctx context.Context, obj interface{}) error
	// ValidateField validates a single field on a struct or pointer to struct.
	ValidateField(ctx context.Context, obj interface{}, field string) error
}

Validator defines the interface for input validation.

Implementations are expected to:

  • validate structs or pointers to structs
  • return an error for unsupported target shapes instead of succeeding silently
  • accept either Go field names or documented external field names for ValidateField when supported by the adapter

type VersionInfo

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

VersionInfo describes application build information.

type WebhookEvent deprecated

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

WebhookEvent is a generic payment provider webhook payload wrapper.

Deprecated: use github.com/aatuh/api-toolkit/v2/compat/billing.WebhookEvent.

Jump to

Keyboard shortcuts

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