ports

package
v3.1.1 Latest Latest
Warning

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

Go to latest
Published: May 21, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

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/v3/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 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

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 Clock

type Clock interface {
	Now() time.Time
}

Clock allows deterministic tests.

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)
}

DatabasePool defines the interface for database connection pooling.

type DatabasePoolSnapshot

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

func SnapshotDatabasePoolStats(pool DatabasePool) DatabasePoolSnapshot

SnapshotDatabasePoolStats copies pool stats into a value snapshot.

type DatabasePoolSnapshotProvider

type DatabasePoolSnapshotProvider interface {
	StatSnapshot() DatabasePoolSnapshot
}

DatabasePoolSnapshotProvider is an optional capability for pools that can expose plain-value pool statistics.

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 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

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

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

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 IdempotencyReservationReleaser

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/v3/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 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

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

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 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 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 ReservationReleasableIdempotencyStore

type ReservationReleasableIdempotencyStore interface {
	IdempotencyStore
	IdempotencyReservationReleaser
}

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

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.

Jump to

Keyboard shortcuts

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