runtime

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: Apache-2.0 Imports: 80 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TargetAuto   = "auto"
	TargetVercel = "vercel"
	TargetDocker = "docker"
	TargetKube   = "kube"
	TargetBare   = "bare-metal"
)
View Source
const NodeType = redis.NodeType

Variables

View Source
var ErrNotFound = db.ErrNotFound

ErrNotFound is returned when a database record is not found.

Functions

func BuildDirectTarget added in v0.11.0

func BuildDirectTarget(endpoints []string) string

func BuildEtcdTarget added in v0.11.0

func BuildEtcdTarget(endpoints []string, key string) string

func BuildOpenAPI

func BuildOpenAPI(cfg *ServiceConfig, models map[string]*db.TableInfo) (*openapi3.T, error)

BuildOpenAPI generates an OpenAPI 3.0.3 spec from the service config and registered models.

func BulkheadGet added in v0.11.0

func BulkheadGet(name string) *syncx.Limit

func BulkheadRegister added in v0.11.0

func BulkheadRegister(name string, limit int)

func CachedCRUD added in v0.4.0

func CachedCRUD[T any](svc *Service, name, poolName, tableName string,
	kvName string, keyPrefix string, l2TTL time.Duration, l1TTL time.Duration,
)

CachedCRUD registers a CRUD provider with automatic L1 (memory) + L2 (Redis/Dragonfly) cache-aside. Cache is populated on miss using the DB primary key lookup. List/Create/Update/Delete return 405. The redisConf points to Dragonfly or Redis (NodeType or ClusterType). If l1TTL > 0, an in-process L1 cache (collection.Cache) is added in front of L2 for sub-μs reads.

func CheckVercelWarnings added in v0.5.0

func CheckVercelWarnings(cfg *ServiceConfig)

CheckVercelWarnings logs non-blocking warnings for Vercel deployment.

func GenerateProto added in v0.15.0

func GenerateProto(info *db.TableInfo, modelName, svcName, pkg string) string

func GenerateShortCode added in v0.13.0

func GenerateShortCode(n int) string

GenerateShortCode generates a random alphanumeric string of given length. Uses crypto/rand for security-sensitive contexts (URL shorteners, tokens).

func GetTable added in v0.6.0

func GetTable[T any](s *Service, name string) *db.Table[T]

GetTable returns a typed *db.Table[T] for a model registered via MustRegister.

func GrpcCall added in v0.15.0

func GrpcCall[T any](ctx context.Context, gc *GrpcClient, fn func(conn ClientConnInterface) (T, error)) (T, error)

GrpcCall makes a typed gRPC call on the given client connection. Returns an error if the client is nil (not configured).

func InsertOutbox added in v0.13.0

func InsertOutbox(ctx context.Context, pool *pgxpool.Pool, subject string, payload []byte) error

InsertOutbox adds an event to the outbox table for transactional publishing. Called from within a DB transaction alongside the business logic write.

func InsertOutboxJSON added in v0.13.0

func InsertOutboxJSON(ctx context.Context, pool *pgxpool.Pool, subject string, data any) error

InsertOutboxJSON is a convenience wrapper for JSON payloads.

func MongoMustRegister added in v0.4.0

func MongoMustRegister(svc *Service, name, poolName, database, collection, lookupField string)

MongoMustRegister registers a CRUD provider for MongoDB backend. The model is lazily initialized on the first HTTP request. lookupField is the document field used for Get (e.g. "_id" or "short_code").

func MustGetGrpcServer added in v0.15.0

func MustGetGrpcServer(svc *Service) *grpc.Server

MustGetGrpcServer returns the gRPC server, or panics if gRPC is not available (server.mode must be "micro" with grpc_server.listen_on set).

func MustRegister added in v0.4.0

func MustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])

MustRegister auto-creates the table and registers a CRUDProvider for the model. The pool, table, and hooks are lazily initialized on the first HTTP request.

func MySQLCachedCRUD added in v0.4.0

func MySQLCachedCRUD[T any](svc *Service, name, poolName, tableName string,
	kvName string, keyPrefix string, l2TTL time.Duration, l1TTL time.Duration,
)

MySQLCachedCRUD registers a CRUD provider with L1+L2 cache using MySQL as DB backend. Identical to CachedCRUD but uses *sql.DB and db.NewMySQLTable internally.

func MySQLMustRegister added in v0.4.0

func MySQLMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])

MySQLMustRegister is like MustRegister but uses MySQL (*sql.DB) instead of PostgreSQL.

func Pool

func Pool(pools map[string]any, name string) any

Pool returns a pool by name. Returns nil if not found or not the expected type.

func PoolPG

func PoolPG(pools map[string]any, name string) *pgxpool.Pool

PoolPG returns a *pgxpool.Pool by name.

func PoolPGRead added in v0.14.0

func PoolPGRead(pools map[string]any, name string) *pgxpool.Pool

PoolPGRead returns a read replica pool if available, falling back to write pool.

func PoolSQL

func PoolSQL(pools map[string]any, name string) *sql.DB

PoolSQL returns a *sql.DB by name (for Turso or MySQL).

func PresignTTL added in v0.13.0

func PresignTTL(store any) time.Duration

PresignTTL extracts the presign TTL duration from a StorageBackend. Returns 0 if the backend does not support presigned URLs.

func RegisterEntries

func RegisterEntries(app *fiber.App, cfg *ServiceConfig, handlers *EntryHandlers, prefix string, brokers map[string]events.EventBroker, models map[string]*db.TableInfo, jwtCfg *middleware.JWTConfig, authValidator func(context.Context, *middleware.AuthContext, []string, []string) error, apiKeyValidator func(ctx context.Context, key string) (*middleware.AuthContext, error), fgaClient openfga.Checker, oryClient *ory.Client, zitadelClient *zitadel.Client, rlRdb ...*redis.Redis) error

func SLOEvent added in v0.14.0

func SLOEvent(name string, isError bool)

SLOEvent records a request outcome for SLO tracking.

func SanitizeFilename added in v0.1.0

func SanitizeFilename(name string) string

func SetRateLimitMaxFunc added in v0.9.0

func SetRateLimitMaxFunc(fn func(c fiber.Ctx) int)

func TableFor

func TableFor[T any](pools map[string]any, poolName, tableName string) (*db.Table[T], error)

TableFor creates a db.Table[T] for the given pool name and table name.

func TursoMustRegister added in v0.4.0

func TursoMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])

TursoMustRegister registers a CRUD provider for Turso/SQLite backend.

func ValidateProjectStructure added in v0.5.0

func ValidateProjectStructure(yamlPath string, target string) error

ValidateProjectStructure checks that the project at yamlPath is structurally compatible with a given deploy target. Used by CLI commands. yamlPath is the path to service.yaml; the project root is derived from it.

func VerifyCallbackSignature added in v0.12.0

func VerifyCallbackSignature(payload []byte, secret string, signature string) bool

VerifyCallbackSignature verifies an HMAC-SHA256 signature for an async callback payload.

func WrapTransformHandler

func WrapTransformHandler[T any](handler func(fiber.Ctx) error, hooks EntryHooks[T]) func(fiber.Ctx) error

WrapTransformHandler wraps a REST handler with BeforeTransform/AfterTransform hooks. The hooks must implement EntryHooks[T] where T is the request model. BeforeTransform parses the request body into T, calls the hook, stores the result in c.Locals("transformed"), then executes the handler. AfterTransform is called with the response body after the handler completes.

Usage:

svc.WithRest("onTransform", runtime.WrapTransformHandler(
    func(c fiber.Ctx) error {
        input := c.Locals("transformed").(Product)
        return c.JSON(fiber.Map{"name": input.Name})
    },
    &ProductHooks{},
))

Types

type AsyncCallbackConf added in v0.12.0

type AsyncCallbackConf struct {
	// URL is the webhook endpoint called on job completion (required).
	URL string `json:"url" config:",optional"`
	// Secret is the HMAC key for signing the callback payload.
	Secret string `json:"secret" config:",optional"`
	// Retry is the number of retry attempts if the callback fails.
	Retry int `json:"retry" config:",optional"`
	// RetryDelay is the delay between retry attempts.
	RetryDelay string `json:"retry_delay" config:",optional"`
}

AsyncCallbackConf configures a webhook to notify on job completion or failure.

type AsyncHandler added in v0.1.0

type AsyncHandler func(body []byte, job *JobState) error

AsyncHandler is a function that processes an async job.

type AsyncJobManager added in v0.1.0

type AsyncJobManager struct {
	// contains filtered or unexported fields
}

AsyncJobManager coordinates async job creation, processing, and status retrieval.

func NewAsyncJobManager added in v0.1.0

func NewAsyncJobManager(store JobStore, processor AsyncHandler) *AsyncJobManager

func NewAsyncJobManagerWithRetry added in v0.12.0

func NewAsyncJobManagerWithRetry(store JobStore, processor AsyncHandler, maxRetries int) *AsyncJobManager

func (*AsyncJobManager) HandleCancel added in v0.12.0

func (m *AsyncJobManager) HandleCancel() fiber.Handler

HandleCancel returns a Fiber handler for DELETE /path/:job_id requests.

func (*AsyncJobManager) HandleList added in v0.12.0

func (m *AsyncJobManager) HandleList() fiber.Handler

HandleList returns a Fiber handler for GET /path requests.

func (*AsyncJobManager) HandleStatus added in v0.1.0

func (m *AsyncJobManager) HandleStatus() fiber.Handler

HandleStatus returns a Fiber handler for GET /path/:job_id requests.

func (*AsyncJobManager) HandleStatusSSE added in v0.12.0

func (m *AsyncJobManager) HandleStatusSSE() fiber.Handler

HandleStatusSSE returns a Fiber handler for SSE streaming of job status changes.

func (*AsyncJobManager) HandleSubmit added in v0.1.0

func (m *AsyncJobManager) HandleSubmit() fiber.Handler

HandleSubmit returns a Fiber handler for POST requests that creates a job.

type AsyncReassignConf added in v0.12.0

type AsyncReassignConf struct {
	// Enabled enables the background reaper goroutine.
	Enabled bool `json:"enabled" config:",optional"`
	// ProcessingTimeout is how long a job can stay in "processing" before being reaped.
	// Default: 5m
	ProcessingTimeout string `json:"processing_timeout" config:",optional"`
	// ReapInterval is how often the reaper checks for stale jobs.
	// Default: 30s
	ReapInterval string `json:"reap_interval" config:",optional"`
	// MaxRetries is the maximum number of times a job can be retried before moving to "failed".
	// Default: 3
	MaxRetries int `json:"max_retries" config:",optional"`
}

AsyncReassignConf configures automatic recovery of stuck processing jobs.

type AsyncStoreConf added in v0.12.0

type AsyncStoreConf struct {
	// Driver selects the backend: "memory" (default), "postgres", "redis", "nats_kv".
	Driver string `json:"driver" config:",optional"`
	// DB references a database name for driver: postgres.
	DB string `json:"db" config:",optional"`
	// KV references a kv store name for driver: redis.
	KV string `json:"kv" config:",optional"`
	// Stream references a stream name for driver: nats_kv.
	Stream string `json:"stream" config:",optional"`
	// Bucket is the NATS KV bucket name (driver: nats_kv).
	Bucket string `json:"bucket" config:",optional"`
	// Table is the PostgreSQL table name (driver: postgres).
	Table string `json:"table" config:",optional"`

	// Reassign configures automatic recovery of stuck jobs (reaper).
	Reassign *AsyncReassignConf `json:"reassign" config:",optional"`
	// Callback configures a webhook to notify on job completion.
	Callback *AsyncCallbackConf `json:"callback" config:",optional"`
	// ResultTTL is how long completed/failed jobs are kept before cleanup.
	// Default: 0 (keep forever)
	ResultTTL string `json:"result_ttl" config:",optional"`
	// MaxConcurrent limits the number of jobs processed simultaneously.
	// Default: 0 (unlimited)
	MaxConcurrent int `json:"max_concurrent" config:",optional"`
}

AsyncStoreConf configures the job store backend for async entries.

type AuthConfig added in v0.1.1

type AuthConfig struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// Driver is a constant.
	Driver string `json:"driver" config:",default=none"` // none | manual | openfga-zitadel | ory
	// Secret is a constant.
	Secret string `json:"secret" config:",optional"`
	// PrevSecret is a constant.
	PrevSecret string `json:"prev_secret" config:",optional"`
	// Algorithm is a constant.
	Algorithm string `json:"algorithm" config:",default=HS256"`
	// ContextKey is a constant.
	ContextKey string `json:"context_key" config:",default=claims"`
	// Issuer is a constant.
	Issuer string `json:"issuer" config:",optional"`
	// Audience is a constant.
	Audience string `json:"audience" config:",optional"`
	// Expiry is a constant.
	Expiry int `json:"expiry" config:",default=900"` // JWT TTL in seconds (default 15 min)
	// ZitadelURL is a constant.
	ZitadelURL string `json:"zitadel_url" config:",optional"`
	// OpenFGAURL is a constant.
	OpenFGAURL string `json:"openfga_url" config:",optional"`
	// OpenFGAStore is a constant.
	OpenFGAStore string `json:"openfga_store" config:",optional"`
	// KratosURL is a constant.
	KratosURL string `json:"kratos_url" config:",optional"`
	// KetoURL is a constant.
	KetoURL string `json:"keto_url" config:",optional"`
	// Refresh is a constant.
	Refresh *RefreshConfig `json:"refresh" config:",optional"`
	// Cookie is a constant.
	Cookie *AuthCookieConfig `json:"cookie" config:",optional"`
}

type AuthCookieConfig added in v0.9.0

type AuthCookieConfig struct {
	// AccessTokenName is a constant.
	AccessTokenName string `json:"access_token_name" config:",default=token"`
	// RefreshTokenName is a constant.
	RefreshTokenName string `json:"refresh_token_name" config:",default=refresh_token"`
	// Domain is a constant.
	Domain string `json:"domain" config:",optional"`
	// Path is a constant.
	Path string `json:"path" config:",default=/"`
	// HTTPOnly is a constant.
	HTTPOnly bool `json:"http_only" config:",default=true"`
	// Secure is a constant.
	Secure bool `json:"secure" config:",default=true"`
	// SameSite is a constant.
	SameSite string `json:"same_site" config:",default=Strict"`
}

type AutocertTLS added in v0.1.0

type AutocertTLS struct {
	// Domains is a constant.
	Domains []string `json:"domains"`
	// Email is a constant.
	Email string `json:"email"`
	// CacheDir is a constant.
	CacheDir string `json:"cache_dir" config:",optional"`
}

type CORSConf

type CORSConf struct {
	// Origins is a constant.
	Origins []string `json:"origins" config:",optional"`
	// Methods is a constant.
	Methods []string `json:"methods" config:",optional"`
	// Headers is a constant.
	Headers []string `json:"headers" config:",optional"`
	// Credentials is a constant.
	Credentials bool `json:"credentials" config:",optional"`
	// MaxAge is a constant.
	MaxAge int `json:"max_age" config:",default=300"`
}

type CRUDFactory added in v0.3.1

type CRUDFactory func() CRUDProvider

CRUDFactory creates a CRUDProvider when needed (lazy initialization). Use WithCRUDFactory instead of WithCRUD when the provider depends on resources initialized during Run() (e.g., database pools).

type CRUDOverrides

type CRUDOverrides struct {
	// List is a constant.
	List string `json:"list" config:",optional"`
	// Get is a constant.
	Get string `json:"get" config:",optional"`
	// Create is a constant.
	Create string `json:"create" config:",optional"`
	// Update is a constant.
	Update string `json:"update" config:",optional"`
	// Delete is a constant.
	Delete string `json:"delete" config:",optional"`
}

type CRUDProvider

type CRUDProvider interface {
	List(ctx fiber.Ctx, params ListParams) error
	Get(ctx fiber.Ctx, id string) error
	Create(ctx fiber.Ctx, body []byte) error
	Update(ctx fiber.Ctx, id string, body []byte) error
	Delete(ctx fiber.Ctx, id string) error
}

func NewCRUDProvider

func NewCRUDProvider[T any](table *db.Table[T], hooks EntryHooks[T]) CRUDProvider

NewCRUDProvider wraps a db.Table[T] (PostgreSQL) into a CRUDProvider.

func NewMongoCRUDProvider added in v0.4.0

func NewMongoCRUDProvider(model *mon.Model, lookupField string) CRUDProvider

NewMongoCRUDProvider creates a CRUDProvider backed by MongoDB. lookupField is the document field used for Get/Update/Delete (e.g. "_id" or "short_code").

func NewMySQLCRUDProvider

func NewMySQLCRUDProvider[T any](table *db.MySQLTable[T], hooks EntryHooks[T]) CRUDProvider

func NewTursoCRUDProvider

func NewTursoCRUDProvider[T any](table *db.TursoTable[T], hooks EntryHooks[T]) CRUDProvider

type CSPConf added in v0.9.0

type CSPConf struct {
	// Level is a constant.
	Level string `json:"level" config:",default=basic"`
	// DefaultSrc is a constant.
	DefaultSrc []string `json:"default_src" config:",optional"`
	// ScriptSrc is a constant.
	ScriptSrc []string `json:"script_src" config:",optional"`
	// StyleSrc is a constant.
	StyleSrc []string `json:"style_src" config:",optional"`
	// ImgSrc is a constant.
	ImgSrc []string `json:"img_src" config:",optional"`
	// ConnectSrc is a constant.
	ConnectSrc []string `json:"connect_src" config:",optional"`
	// FontSrc is a constant.
	FontSrc []string `json:"font_src" config:",optional"`
	// FrameSrc is a constant.
	FrameSrc []string `json:"frame_src" config:",optional"`
	// FrameAncestors is a constant.
	FrameAncestors []string `json:"frame_ancestors" config:",optional"`
	// ObjectSrc is a constant.
	ObjectSrc []string `json:"object_src" config:",optional"`
	// BaseURI is a constant.
	BaseURI []string `json:"base_uri" config:",optional"`
	// FormAction is a constant.
	FormAction []string `json:"form_action" config:",optional"`
	// UpgradeInsecureReq is a constant.
	UpgradeInsecureReq bool `json:"upgrade_insecure_requests" config:",optional"`
}

type CSRFConf added in v0.1.0

type CSRFConf struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// CookieName is a constant.
	CookieName string `json:"cookie_name" config:",optional"`
	// HeaderName is a constant.
	HeaderName string `json:"header_name" config:",optional"`
	// SameSite is a constant.
	SameSite string `json:"same_site" config:",optional"`
	// Secure is a constant.
	Secure bool `json:"secure" config:",optional"`
	// ExcludePaths is a constant.
	ExcludePaths []string `json:"exclude_paths" config:",optional"`
	// JSONCheck is a constant.
	JSONCheck bool `json:"json_check" config:",optional"`
}

type CacheConfig added in v0.6.0

type CacheConfig struct {
	// L1 is a constant.
	L1 string `json:"l1" config:",default=ram"` // ram | none
	// L1TTL is a constant.
	L1TTL string `json:"l1_ttl" config:",default=5m"`
	// L1Size is a constant.
	L1Size int `json:"l1_size" config:",default=10000"`
	// L2 is a constant.
	L2 string `json:"l2" config:",optional"` // disk | none
	// L2Path is a constant.
	L2Path string `json:"l2_path" config:",optional"`
}

type ClientConnInterface added in v0.15.0

type ClientConnInterface = grpc.ClientConnInterface

ClientConnInterface is a type alias for grpc.ClientConnInterface, exported so example projects can reference the type without importing grpc directly.

func MustGetGrpcClientConn added in v0.15.0

func MustGetGrpcClientConn(svc *Service, name string) ClientConnInterface

MustGetGrpcClientConn returns the gRPC client connection for a named client. Returns nil if the client is not configured.

type ContentSecurityDef added in v0.2.0

type ContentSecurityDef struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// Strict is a constant.
	Strict bool `json:"strict" config:",optional"`
	// PublicKey is a constant.
	PublicKey string `json:"public_key"`
}
type Cookie struct {
	Name     string
	Value    string
	Path     string
	Domain   string
	MaxAge   int
	HTTPOnly bool
	Secure   bool
	SameSite string
}

Cookie configures an HTTP cookie set by the SDK.

func NewCookie added in v0.9.0

func NewCookie(name, value string, maxAge int) *Cookie

type CookieConf added in v0.1.0

type CookieConf struct {
	// SameSite is a constant.
	SameSite string `json:"same_site" config:",optional"` // Strict, Lax, None
	// Secure is a constant.
	Secure bool `json:"secure" config:",optional"`
}

type CorrelationConf added in v0.11.0

type CorrelationConf struct {
	// Enabled enables the correlation ID middleware.
	Enabled bool `json:"enabled" config:",optional"`
	// RequestHeader is the header to read the correlation ID from.
	RequestHeader string `json:"request_header" config:",default=X-Correlation-ID"`
	// ResponseHeader is the header to set the correlation ID on.
	ResponseHeader string `json:"response_header" config:",default=X-Correlation-ID"`
	// SkipPaths are request paths that should not receive a correlation ID.
	SkipPaths []string `json:"skip_paths" config:",optional"`
}

type CronJob

type CronJob struct {
	// Name is a constant.
	Name string `json:"name"`
	// Schedule is a constant.
	Schedule string `json:"schedule"`
	// Mode is a constant.
	Mode string `json:"mode" config:",default=nats"` // nats, handler, internal
	// Publish is a constant.
	Publish *CronPublish `json:"publish" config:",optional"`
	// Handler is a constant.
	Handler string `json:"handler" config:",optional"`
}

func (*CronJob) Validate

func (c *CronJob) Validate() error

type CronJobFunc

type CronJobFunc func(ctx context.Context) error

type CronPublish

type CronPublish struct {
	// Stream is a constant.
	Stream string `json:"stream"`
	// Subject is a constant.
	Subject string `json:"subject" config:",optional"`
}

type CronScheduler

type CronScheduler struct {
	// contains filtered or unexported fields
}

func NewCronScheduler

func NewCronScheduler() *CronScheduler

func (*CronScheduler) AddAll

func (s *CronScheduler) AddAll(ctx context.Context, cronDefs []CronJob, brokers map[string]events.EventBroker, handlers map[string]CronJobFunc) error

func (*CronScheduler) AddJob

func (s *CronScheduler) AddJob(ctx context.Context, cfg CronJob, broker events.EventBroker, handler CronJobFunc) error

func (*CronScheduler) Start

func (s *CronScheduler) Start()

func (*CronScheduler) Stop

func (s *CronScheduler) Stop()

type CryptionDef added in v0.2.0

type CryptionDef struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// Key is a constant.
	Key string `json:"key"`
}

type DBConfig

type DBConfig struct {
	// Name is a constant.
	Name string `json:"name"`
	// Driver is a constant.
	Driver string `json:"driver" config:",default=postgres"`
	// URL is a constant.
	URL string `json:"url"`
	// ReadURL is the read replica connection URL for read/write splitting.
	ReadURL string `json:"read_url" config:",optional"`
	// Database is a constant.
	Database string `json:"database" config:",optional"`
	// Pool is a constant.
	Pool *PoolConf `json:"pool" config:",optional"`
	// Turso is a constant.
	Turso *TursoConf `json:"turso" config:",optional"`
	// SlowQuery is a constant.
	SlowQuery *SlowQueryConf `json:"slow_query" config:",optional"`
}

func (*DBConfig) Validate

func (d *DBConfig) Validate() error

type DefaultExitHooks

type DefaultExitHooks struct{}

func (DefaultExitHooks) OnError

func (DefaultExitHooks) OnError(_ context.Context, _ error)

func (DefaultExitHooks) OnMessage

func (DefaultExitHooks) OnMessage(_ context.Context, msg []byte) ([]byte, error)

func (DefaultExitHooks) OnSuccess

func (DefaultExitHooks) OnSuccess(_ context.Context)

type DefaultHooks

type DefaultHooks[T any] struct{}

func (DefaultHooks[T]) AfterCreate

func (DefaultHooks[T]) AfterCreate(_ context.Context, _ *T) error

func (DefaultHooks[T]) AfterDelete

func (DefaultHooks[T]) AfterDelete(_ context.Context, _ string) error

func (DefaultHooks[T]) AfterTransform

func (DefaultHooks[T]) AfterTransform(_ context.Context, _ any) error

func (DefaultHooks[T]) AfterUpdate

func (DefaultHooks[T]) AfterUpdate(_ context.Context, _ *T) error

func (DefaultHooks[T]) BeforeCreate

func (DefaultHooks[T]) BeforeCreate(_ context.Context, req T) (T, error)

func (DefaultHooks[T]) BeforeDelete

func (DefaultHooks[T]) BeforeDelete(_ context.Context, _ string) error

func (DefaultHooks[T]) BeforeTransform

func (DefaultHooks[T]) BeforeTransform(_ context.Context, req T) (T, error)

func (DefaultHooks[T]) BeforeUpdate

func (DefaultHooks[T]) BeforeUpdate(_ context.Context, _ string, patch map[string]any) (map[string]any, error)

type DeployConfig added in v0.5.0

type DeployConfig struct {
	// Target is a constant.
	Target string `json:"target" config:",default=auto"`
}

type EncryptCookieDef added in v0.8.0

type EncryptCookieDef struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// Key is a constant.
	Key string `json:"key"` // required when enabled
	// Except is a constant.
	Except []string `json:"except" config:",optional"` // cookie names to skip
}

type EntryDef

type EntryDef struct {
	// Type is a constant.
	Type string `json:"type"` // crud, rest, webhook, websocket, sse, file
	// Method is a constant.
	Method string `json:"method" config:",optional"`
	// Path is a constant.
	Path string `json:"path" config:",optional"`
	// Handler is a constant.
	Handler string `json:"handler" config:",optional"`
	// AuthModes is a constant.
	AuthModes []string `json:"auth_modes" config:",optional"` // ["jwt"], ["apikey"], ["jwt","apikey"]
	// JWTFrom is a constant.
	JWTFrom string `json:"jwt_from" config:",optional"` // per-entry: "header:Authorization", "cookie:token", "query:token"
	// Roles is a constant.
	Roles []string `json:"roles" config:",optional"`
	// Permissions is a constant.
	Permissions []string `json:"permissions" config:",optional"`
	// DB is a constant.
	DB string `json:"db" config:",optional"` // references database name
	// TenantScope is a constant.
	TenantScope string `json:"tenant_scope" config:",optional"` // JWT claim for tenant ID (e.g. "org_id")
	// TenantField is a constant.
	TenantField string `json:"tenant_field" config:",optional"` // DB column for tenant filter (e.g. "tenant_id")

	// ServiceName is the gRPC service name (required for type: grpc).
	ServiceName string `json:"service_name" config:",optional"`

	// CRUD
	Model string `json:"model" config:",optional"`
	// Table is a constant.
	Table string `json:"table" config:",optional"`
	// Resource is a constant.
	Resource string `json:"resource" config:",optional"`
	// Overrides is a constant.
	Overrides *CRUDOverrides `json:"overrides" config:",optional"`

	// Event stream selection
	EventStream string `json:"event_stream" config:",optional"`

	// Event publish targets
	EventPublish []EventPublishTarget `json:"event_publish" config:",optional"`

	// File
	AllowedTypes []string `json:"allowed_types" config:",optional"`
	// MaxSize is a constant.
	MaxSize string `json:"max_size" config:",optional"`
	// MaxFiles is a constant.
	MaxFiles int `json:"max_files" config:",optional"`
	// MagicBytes is a constant.
	MagicBytes bool `json:"magic_bytes" config:",optional"`
	// Storage is a constant.
	Storage *StorageDef `json:"storage" config:",optional"`

	// Security per-entry overrides
	CSRF *bool `json:"csrf" config:",optional"` // false = skip CSRF for this entry
	// RequiresMFA is a constant.
	RequiresMFA bool `json:"requires_mfa" config:",optional"` // true = MFA must be verified
	// RateLimit is a constant.
	RateLimit *RateLimitDef `json:"rate_limit" config:",optional"` // per-entry rate limit (pre-auth)
	// RateLimitPerUser is a constant.
	RateLimitPerUser *RateLimitDef `json:"rate_limit_per_user" config:",optional"` // per-entry per-user rate limit (post-auth)
	// RateLimitPerKey is a constant.
	RateLimitPerKey *RateLimitDef `json:"rate_limit_per_key" config:",optional"` // per-entry per-key rate limit (post-auth)
	// PerRoleLimits is a constant.
	PerRoleLimits map[string]*RateLimitDef `json:"rate_limit_per_role" config:",optional"` // per-role rate limits
	// Cache is a constant.
	Cache string `json:"cache" config:",optional"` // references kv[].name for CRUD cache

	// Validation
	ValidationModel string `json:"validate" config:",optional"` // validation model name

	// APIVersion sets the API version prefix for this entry (e.g. "v1", "v2").
	// If empty and the server api_prefix does not already contain a version,
	// defaults to "v1".
	APIVersion string `json:"api_version" config:",optional"`

	// APIStatus indicates the lifecycle status of this endpoint.
	// Values: current | deprecated | removed
	APIStatus string `json:"api_status" config:",optional"`
	// SunsetDate is the RFC3339 date when the endpoint will be removed.
	SunsetDate string `json:"sunset_date" config:",optional"`

	// Timeout per-entry (e.g. "30s")
	Timeout string `json:"timeout" config:",optional"`

	// Retry configures the retry behavior for idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS).
	Retry *RetryConf `json:"retry" config:",optional"`
	// Fallback sets the fallback strategy when the circuit breaker is open.
	// Values: "degraded" | "stale" | "" (disabled)
	Fallback string `json:"fallback" config:",optional"`
	// Bulkhead defines named concurrency limits for external outbound calls.
	// Each key is a dependency name, value is max concurrent calls.
	Bulkhead map[string]int `json:"bulkhead" config:",optional"`

	// API Key prefix (only applies when auth_modes includes "apikey")
	APIPrefix string `json:"api_key_prefix" config:",optional"`

	// Pagination (CRUD only)
	PageSize int `json:"page_size" config:",optional"` // default 10, also min
	// MaxPageSize is a constant.
	MaxPageSize int `json:"max_page_size" config:",optional"` // default 100, also max
	// Pagination is a constant.
	Pagination string `json:"pagination" config:",optional"` // "offset" | "keyset"
	// Sortable is a constant.
	Sortable []string `json:"sortable" config:",optional"` // allowed sort columns

	// AsyncStore configures the job store backend for type: async entries.
	AsyncStore *AsyncStoreConf `json:"async_store" config:",optional"`
}

func (*EntryDef) Validate

func (e *EntryDef) Validate() error

type EntryHandlers

type EntryHandlers struct {
	Rest      map[string]func(fiber.Ctx) error
	WS        map[string]WSHandler
	SSE       map[string]SSEHandler
	CRUD      map[string]CRUDProvider
	Storage   map[string]server.StorageBackend
	Async     map[string]AsyncHandler
	Transform map[string]any
	Reapers   []*Reaper
}

type EntryHooks

type EntryHooks[T any] interface {
	BeforeCreate(ctx context.Context, req T) (T, error)
	AfterCreate(ctx context.Context, entity *T) error
	BeforeUpdate(ctx context.Context, id string, patch map[string]any) (map[string]any, error)
	AfterUpdate(ctx context.Context, entity *T) error
	BeforeDelete(ctx context.Context, id string) error
	AfterDelete(ctx context.Context, id string) error
	BeforeTransform(ctx context.Context, req T) (T, error)
	AfterTransform(ctx context.Context, result any) error
}

EntryHooks defines lifecycle callbacks for entry endpoints (HTTP).

type EventPublishTarget added in v0.1.0

type EventPublishTarget struct {
	// Stream is a constant.
	Stream string `json:"stream"`
	// Subject is a constant.
	Subject string `json:"subject" config:",optional"`
	// EventStream is a constant.
	EventStream string `json:"event_stream" config:",optional"` // broker name; empty = all brokers
}

type EventStreamConnConf added in v0.1.0

type EventStreamConnConf struct {
	// Name is a constant.
	Name string `json:"name"`
	// Driver is a constant.
	Driver string `json:"driver"` // nats, kafka
	// URL is a constant.
	URL string `json:"url" config:",optional"`
	// Brokers is a constant.
	Brokers []string `json:"brokers" config:",optional"`
	// ConsumerGroup is a constant.
	ConsumerGroup string `json:"consumer_group" config:",optional"`
	// MaxReconnects is a constant.
	MaxReconnects int `json:"max_reconnects" config:",optional"`
	// ReconnectWait is a constant.
	ReconnectWait string `json:"reconnect_wait" config:",optional"`
	// Timeout is a constant.
	Timeout string `json:"timeout" config:",optional"`
	// RetryOnFail is a constant.
	RetryOnFail bool `json:"retry_on_fail" config:",optional"`
	// Streams is a constant.
	Streams []StreamDef `json:"streams" config:",optional"`
}

func (*EventStreamConnConf) Validate added in v0.1.0

func (e *EventStreamConnConf) Validate() error

type ExitHandler

type ExitHandler func(ctx context.Context, msg []byte) ([]byte, error)

type ExitHooks

type ExitHooks interface {
	OnMessage(ctx context.Context, msg []byte) ([]byte, error)
	OnSuccess(ctx context.Context)
	OnError(ctx context.Context, err error)
}

ExitHooks defines lifecycle callbacks for exit workers (NATS).

type ExitWorker

type ExitWorker struct {
	// Name is a constant.
	Name string `json:"name"`
	// Subscribe is a constant.
	Subscribe SubscribeDef `json:"subscribe"`
	// Handler is a constant.
	Handler string `json:"handler"`
	// MaxConcurrent is a constant.
	MaxConcurrent int `json:"max_concurrent" config:",default=1"`
	// DB is a constant.
	DB string `json:"db" config:",optional"`
	// Reply is a constant.
	Reply bool `json:"reply" config:",optional"`
	// ReplyTimeout is a constant.
	ReplyTimeout string `json:"reply_timeout" config:",default=30s"`
	// PullBatch is a constant.
	PullBatch int `json:"pull_batch" config:",optional"`
	// PullMaxWait is a constant.
	PullMaxWait string `json:"pull_max_wait" config:",optional"`
	// ConsumerMode is a constant.
	ConsumerMode string `json:"consumer_mode" config:",optional"` // push or pull
	// EventStream is a constant.
	EventStream string `json:"event_stream" config:",optional"` // broker name
	// TermOnFailure terminates (DLQ) instead of Nak when handler returns error.
	TermOnFailure bool `json:"term_on_failure" config:",optional"`
}

func (*ExitWorker) Validate

func (e *ExitWorker) Validate() error

type ExitWorkerManager

type ExitWorkerManager struct {
	// contains filtered or unexported fields
}

func NewExitWorkerManager

func NewExitWorkerManager() *ExitWorkerManager

func (*ExitWorkerManager) Shutdown

func (m *ExitWorkerManager) Shutdown(timeout time.Duration)

func (*ExitWorkerManager) Start

func (m *ExitWorkerManager) Start(ctx context.Context, exitDefs []ExitWorker, brokers map[string]events.EventBroker, handlers map[string]ExitHandler, hooks map[string]ExitHooks) error

type GCConfig added in v0.14.0

type GCConfig struct {
	// GOGC sets the GC target percentage. Default 100. Higher = less GC, more memory.
	// Set to 200 for higher throughput at the cost of ~2x memory.
	GOGC int `json:"go_gc" config:",default=100"`
	// MemoryLimit sets GOMEMLIMIT. Can be a percentage of container memory (e.g. "80%")
	// or an absolute value (e.g. "2GiB", "512MiB"). Empty means no limit.
	MemoryLimit string `json:"memory_limit" config:",optional"`
}

GCConfig configures Go runtime garbage collection parameters.

type GrpcClient added in v0.11.0

type GrpcClient struct {
	// contains filtered or unexported fields
}

func NewGrpcClient added in v0.11.0

func NewGrpcClient(cfg *GrpcClientConf) (*GrpcClient, error)

func (*GrpcClient) Close added in v0.11.0

func (gc *GrpcClient) Close() error

func (*GrpcClient) Conn added in v0.11.0

func (gc *GrpcClient) Conn() *grpc.ClientConn

func (*GrpcClient) Name added in v0.11.0

func (gc *GrpcClient) Name() string

type GrpcClientConf added in v0.11.0

type GrpcClientConf struct {
	// Name is a unique name for this client connection.
	Name string `json:"name"`
	// Target is the gRPC target address (e.g. "dns:///product-svc:8081").
	Target string `json:"target" config:",optional"`
	// Secure enables TLS transport credentials instead of insecure.
	Secure bool `json:"secure" config:",optional"`
	// Endpoints are direct gRPC endpoints (e.g. ["localhost:8081"]).
	Endpoints []string `json:"endpoints" config:",optional"`
	// Timeout is the default RPC timeout in milliseconds.
	Timeout int64 `json:"timeout" config:",default=2000"`
	// NonBlock enables non-blocking dial.
	NonBlock bool `json:"non_block" config:",default=true"`
}

type GrpcInterceptorsConfig added in v0.11.0

type GrpcInterceptorsConfig struct {
	Trace      bool
	Breaker    bool
	Timeout    bool
	Shedding   bool
	Prometheus bool
}

type GrpcRegisterFn added in v0.11.0

type GrpcRegisterFn func(server *grpc.Server)

type GrpcServer added in v0.11.0

type GrpcServer struct {
	// contains filtered or unexported fields
}

func NewGrpcServer added in v0.11.0

func NewGrpcServer(cfg *GrpcServerConf, register GrpcRegisterFn, interceptorCfg ...GrpcInterceptorsConfig) (*GrpcServer, error)

func (*GrpcServer) Server added in v0.11.0

func (gs *GrpcServer) Server() *grpc.Server

func (*GrpcServer) Start added in v0.11.0

func (gs *GrpcServer) Start()

func (*GrpcServer) Stop added in v0.11.0

func (gs *GrpcServer) Stop()

type GrpcServerConf added in v0.11.0

type GrpcServerConf struct {
	// ListenOn is the address to listen on (e.g. ":8081").
	ListenOn string `json:"listen_on" config:",optional"`
	// Timeout is the default RPC timeout in milliseconds.
	Timeout int64 `json:"timeout" config:",default=2000"`
	// CpuThreshold is the CPU load threshold for adaptive shedding (0-1000). 0 disables.
	CpuThreshold int64 `json:"cpu_threshold" config:",default=900"`
	// Health enables the gRPC health check service.
	Health bool `json:"health" config:",default=true"`
	// EtcdEndpoints are the etcd cluster hosts for service registration (micro mode).
	EtcdEndpoints []string `json:"etcd_endpoints" config:",optional"`
	// EtcdKey is the service key to register in etcd (e.g. "user-svc").
	EtcdKey string `json:"etcd_key" config:",optional"`
}

type JobState added in v0.1.0

type JobState struct {
	ID                 string     `json:"id"`
	Status             JobStatus  `json:"status"`
	Result             any        `json:"result,omitempty"`
	Error              string     `json:"error,omitempty"`
	CreatedAt          time.Time  `json:"created_at"`
	UpdatedAt          time.Time  `json:"updated_at"`
	RetryCount         int        `json:"retry_count,omitempty"`
	MaxRetries         int        `json:"max_retries,omitempty"`
	ProcessingDeadline *time.Time `json:"processing_deadline,omitempty"`
	CallbackURL        string     `json:"callback_url,omitempty"`
}

JobState holds the state and result of an async job.

type JobStatus added in v0.1.0

type JobStatus string

JobStatus represents the processing state of a job.

const (
	JobPending    JobStatus = "pending"
	JobProcessing JobStatus = "processing"
	JobCompleted  JobStatus = "completed"
	JobFailed     JobStatus = "failed"
)

type JobStore added in v0.1.0

type JobStore interface {
	Create(id string) *JobState
	Get(id string) (*JobState, bool)
	Update(id string, status JobStatus, result any, errMsg string)
	Delete(id string)
	// List returns all jobs (best-effort, limited).
	List() ([]*JobState, error)
	// ReapStale resets jobs stuck in "processing" for longer than the deadline.
	// Returns the number of jobs reaped.
	ReapStale(ctx context.Context, timeout time.Duration, maxRetries int) (int, error)
	// Cleanup removes completed and failed jobs older than ttl.
	// Returns the number of jobs cleaned.
	Cleanup(ctx context.Context, ttl time.Duration) (int, error)
}

JobStore persists and retrieves job state.

type KVConfig added in v0.9.0

type KVConfig struct {
	// Name is a constant.
	Name string `json:"name"`
	// Driver is a constant.
	Driver string `json:"driver" config:",default=redis"`
	// URL is a constant.
	URL string `json:"url"`
}

type KeysetResponse added in v0.6.0

type KeysetResponse struct {
	Data       any    `json:"data"`
	NextCursor string `json:"nextCursor,omitempty"`
	PageSize   int    `json:"pageSize"`
}

KeysetResponse is used by tableCRUD.List (keyset mode).

type ListParams

type ListParams struct {
	Page       int
	Size       int
	Sort       string
	Filters    map[string]string
	Cursor     string   // keyset pagination cursor
	Pagination string   // "offset" | "keyset"
	Fields     []string // column subset for egress optimization (empty = all)
}

type ManualTLS added in v0.1.0

type ManualTLS struct {
	// CertFile is a constant.
	CertFile string `json:"cert_file"`
	// KeyFile is a constant.
	KeyFile string `json:"key_file"`
}

type Map added in v0.9.0

type Map = map[string]any

Map is a shorthand for map[string]any used in JSON responses.

type OpenAPIConf

type OpenAPIConf struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// Version is a constant.
	Version string `json:"version" config:",default=1.0.0"`
	// SpecPath is a constant.
	SpecPath string `json:"spec_path" config:",default=/openapi.json"`
	// DocsPath is a constant.
	DocsPath string `json:"docs_path" config:",default=/docs"`
	// Theme is a constant.
	Theme string `json:"theme" config:",default=moon"`
	// DarkMode is a constant.
	DarkMode bool `json:"dark_mode" config:",default=true"`
	// SpecCacheTTL sets Cache-Control max-age for /openapi.json
	SpecCacheTTL string `json:"spec_cache_ttl" config:",default=1h"`
}

type OutboxRecord added in v0.13.0

type OutboxRecord struct {
	ID        int64  `db:"id,primary,auto"`
	Subject   string `db:"subject,required"`
	Payload   string `db:"payload,required"`
	Status    string `db:"status,required,default='pending'"`
	CreatedAt string `db:"created_at,default=now()"`
}

OutboxRecord represents a pending event in the outbox table.

type OutboxRelay added in v0.13.0

type OutboxRelay struct {
	// contains filtered or unexported fields
}

OutboxRelay polls the outbox table and publishes pending events to NATS. It runs in a background goroutine and is opt-in via event_publish.outbox: true.

func NewOutboxRelay added in v0.13.0

func NewOutboxRelay(pool *pgxpool.Pool, broker events.EventBroker) (*OutboxRelay, error)

NewOutboxRelay creates a relay that polls pending events and publishes them.

func (*OutboxRelay) Start added in v0.13.0

func (r *OutboxRelay) Start()

Start begins polling in a background goroutine.

func (*OutboxRelay) Stop added in v0.13.0

func (r *OutboxRelay) Stop()

Stop stops the relay and waits for in-flight publishes.

type PGPool added in v0.15.0

type PGPool = pgxpool.Pool

PGPool is a type alias for pgxpool.Pool, exported so example projects can reference the pool type without importing pgx directly.

type PaginatedResponse

type PaginatedResponse struct {
	Data  any   `json:"data"`
	Total int64 `json:"total"`
	Page  int   `json:"page"`
	Size  int   `json:"size"`
}

PaginatedResponse is used by tableCRUD.List (offset mode).

type PoolConf

type PoolConf struct {
	// MaxConns is a constant.
	MaxConns int32 `json:"max_conns" config:",default=10"`
	// MinConns is a constant.
	MinConns int32 `json:"min_conns" config:",default=2"`
	// MaxConnLifetime is a constant.
	MaxConnLifetime string `json:"max_conn_lifetime" config:",optional"`
	// MaxConnIdleTime is a constant.
	MaxConnIdleTime string `json:"max_conn_idle_time" config:",optional"`
	// HealthCheckPeriod is a constant.
	HealthCheckPeriod string `json:"health_check_period" config:",optional"`
	// ReservedConns is a constant.
	ReservedConns int32 `json:"reserved_conns" config:",default=10"`
	// StatementTimeout sets statement_timeout per connection.
	StatementTimeout string `json:"statement_timeout" config:",optional"`
}

type PoolConfig added in v0.1.1

type PoolConfig struct {
	// MaxIdleConns is a constant.
	MaxIdleConns int `json:"max_idle_conns" config:",default=200"`
	// MaxIdlePerHost is a constant.
	MaxIdlePerHost int `json:"max_idle_conns_per_host" config:",default=100"`
	// MaxConnsPerHost is a constant.
	MaxConnsPerHost int `json:"max_conns_per_host" config:",default=250"`
	// IdleTimeout is a constant.
	IdleTimeout string `json:"idle_timeout" config:",default=90s"`
}

type PoolHealth added in v0.11.0

type PoolHealth struct {
	Name           string  `json:"name"`
	Driver         string  `json:"driver"`
	TotalConns     int     `json:"total_connections"`
	IdleConns      int     `json:"idle_connections"`
	InUseConns     int     `json:"in_use_connections"`
	MaxConns       int     `json:"max_connections"`
	UtilizationPct float64 `json:"utilization_pct"`
	WaitCount      int64   `json:"wait_count"`
	WaitDuration   string  `json:"wait_duration"`
	Status         string  `json:"status"`
}

func CheckPoolHealth added in v0.11.0

func CheckPoolHealth(name, driver string, pool any) PoolHealth

type PrometheusConfig added in v0.15.0

type PrometheusConfig struct {
	// Enabled enables the prometheus metrics agent and infra/metric counters.
	Enabled bool `json:"enabled"`
	// Host is the prometheus agent listen address.
	Host string `json:"host" config:",default=0.0.0.0"`
	// Port is the prometheus agent listen port.
	Port int `json:"port" config:",default=9101"`
	// Path is the prometheus metrics endpoint path.
	Path string `json:"path" config:",default=/metrics"`
}

type RateLimitConf added in v0.1.0

type RateLimitConf struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// KV is a constant.
	KV string `json:"kv" config:",optional"` // references kv[].name
	// Algorithm is a constant.
	Algorithm string `json:"algorithm" config:",default=sliding_window"`
	// TTL is a constant.
	TTL string `json:"ttl" config:",optional"`
	// Global is a constant.
	Global *RateLimitDef `json:"global" config:",optional"`
	// PerIP is a constant.
	PerIP *RateLimitDef `json:"per_ip" config:",optional"`
	// PerUser is a constant.
	PerUser *RateLimitDef `json:"per_user" config:",optional"`
	// PerKey is a constant.
	PerKey *RateLimitDef `json:"per_key" config:",optional"`
	// SkipFailedRequests is a constant.
	SkipFailedRequests bool `json:"skip_failed_requests" config:",optional"`
	// SkipSuccessfulRequests is a constant.
	SkipSuccessfulRequests bool `json:"skip_successful_requests" config:",optional"`
}

type RateLimitDef added in v0.1.0

type RateLimitDef struct {
	// RequestsPerSecond is a constant.
	RequestsPerSecond int `json:"requests_per_second"`
	// Burst is a constant.
	Burst int `json:"burst"`
	// TTL is a constant.
	TTL string `json:"ttl" config:",optional"`
}

type Reaper added in v0.12.0

type Reaper struct {
	// contains filtered or unexported fields
}

Reaper periodically calls ReapStale on a JobStore to recover stuck jobs.

func NewReaper added in v0.12.0

func NewReaper(store JobStore, timeout, interval time.Duration, maxRetries int) *Reaper

NewReaper creates a Reaper that runs every interval.

func (*Reaper) Start added in v0.12.0

func (r *Reaper) Start()

Start begins the reap loop in a background goroutine.

func (*Reaper) Stop added in v0.12.0

func (r *Reaper) Stop()

Stop terminates the reap loop.

type RedisConfig added in v0.1.1

type RedisConfig = redis.RedisConf

type RefreshConfig added in v0.9.0

type RefreshConfig struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",default=false"`
	// TTL is a constant.
	TTL int `json:"ttl" config:",default=604800"` // 7 days in seconds
	// Endpoint is a constant.
	Endpoint string `json:"endpoint" config:",default=/auth/refresh"`
	// Secret is a constant.
	Secret string `json:"secret" config:",optional"` // separate from auth.secret
	// ZitadelTokenURL is a constant.
	ZitadelTokenURL string `json:"zitadel_token_url" config:",optional"`
	// ZitadelClientID is a constant.
	ZitadelClientID string `json:"zitadel_client_id" config:",optional"`
	// KratosRefreshURL is a constant.
	KratosRefreshURL string `json:"kratos_refresh_url" config:",optional"`
}

type RestCtx added in v0.4.1

type RestCtx struct {
	// contains filtered or unexported fields
}

func (*RestCtx) Bind added in v0.4.1

func (c *RestCtx) Bind(v any) error

func (*RestCtx) Body added in v0.4.1

func (c *RestCtx) Body() []byte

func (*RestCtx) Context added in v0.4.1

func (c *RestCtx) Context() context.Context

func (*RestCtx) Get added in v0.4.1

func (c *RestCtx) Get(key string) string

func (*RestCtx) JSON added in v0.4.1

func (c *RestCtx) JSON(data any) error

func (*RestCtx) Locals added in v0.4.1

func (c *RestCtx) Locals(key any, values ...any) any

func (*RestCtx) Method added in v0.4.1

func (c *RestCtx) Method() string

func (*RestCtx) Params added in v0.4.1

func (c *RestCtx) Params(key string) string

func (*RestCtx) Path added in v0.4.1

func (c *RestCtx) Path() string

func (*RestCtx) PoolPG added in v0.10.0

func (c *RestCtx) PoolPG(name string) *pgxpool.Pool

func (*RestCtx) PoolRead added in v0.14.0

func (c *RestCtx) PoolRead(name string) *pgxpool.Pool

func (*RestCtx) PoolSQL added in v0.10.0

func (c *RestCtx) PoolSQL(name string) *sql.DB

func (*RestCtx) Query added in v0.4.1

func (c *RestCtx) Query(key string, defaultValue ...string) string

func (*RestCtx) Redirect added in v0.6.0

func (c *RestCtx) Redirect(url string, statusCode ...int) error

func (*RestCtx) ResponseBody added in v0.4.1

func (c *RestCtx) ResponseBody() string

func (*RestCtx) SendStatus added in v0.4.1

func (c *RestCtx) SendStatus(code int) error

func (*RestCtx) SendString added in v0.4.1

func (c *RestCtx) SendString(s string) error

func (*RestCtx) Set added in v0.4.1

func (c *RestCtx) Set(key, val string)

func (*RestCtx) SetCookie added in v0.8.0

func (c *RestCtx) SetCookie(cookie *Cookie)

func (*RestCtx) Status added in v0.4.1

func (c *RestCtx) Status(code int) *RestCtx

func (*RestCtx) StatusCode added in v0.4.1

func (c *RestCtx) StatusCode() int

type RetryConf added in v0.11.0

type RetryConf struct {
	// MaxRetries is the maximum number of retry attempts (default 3).
	MaxRetries int `json:"max_retries" config:",default=3"`
	// InitialInterval is the initial backoff duration (default 500ms).
	InitialInterval string `json:"initial_interval" config:",default=500ms"`
	// MaxBackoff is the maximum backoff duration (default 10s).
	MaxBackoff string `json:"max_backoff" config:",default=10s"`
	// Multiplier is the exponential backoff multiplier (default 2.0).
	Multiplier float64 `json:"multiplier" config:",default=2.0"`
}

type RouteMW

type RouteMW struct {
	// Path is a constant.
	Path string `json:"path"`
	// Apply is a constant.
	Apply []string `json:"apply"`
}

type SLOConfig added in v0.14.0

type SLOConfig struct {
	// Name identifies this SLO.
	Name string
	// Target is the availability target (e.g. 99.9 for 99.9%).
	Target float64
	// Window is the measurement window (e.g. 30d).
	Window time.Duration
}

SLOConfig defines a service level objective.

type SSEHandler

type SSEHandler func(ctx context.Context, send func(data string)) error

SSEHandler is called when an SSE client connects.

type SSRFConf added in v0.1.0

type SSRFConf struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled" config:",optional"`
	// BlockPrivate is a constant.
	BlockPrivate bool `json:"block_private" config:",optional"`
	// BlockLoopback is a constant.
	BlockLoopback bool `json:"block_loopback" config:",optional"`
	// BlockMetadata is a constant.
	BlockMetadata bool `json:"block_metadata" config:",optional"`
	// AllowedHosts is a constant.
	AllowedHosts []string `json:"allowed_hosts" config:",optional"`
}

type SecurityDef added in v0.2.0

type SecurityDef struct {
	// ContentSecurity is a constant.
	ContentSecurity *ContentSecurityDef `json:"content_security" config:",optional"`
	// Cryption is a constant.
	Cryption *CryptionDef `json:"cryption" config:",optional"`
	// EncryptCookie is a constant.
	EncryptCookie *EncryptCookieDef `json:"encrypt_cookie" config:",optional"`
}

type SecurityHeadersConf added in v0.1.0

type SecurityHeadersConf struct {
	// FrameOptions is a constant.
	FrameOptions string `json:"frame_options" config:",optional"`
	// ReferrerPolicy is a constant.
	ReferrerPolicy string `json:"referrer_policy" config:",optional"`
	// PermissionsPolicy is a constant.
	PermissionsPolicy string `json:"permissions_policy" config:",optional"`
	// HSTS is a constant.
	HSTS bool `json:"hsts" config:",optional"`
	// HSTSMaxAge is a constant.
	HSTSMaxAge int `json:"hsts_max_age" config:",optional"`
	// HSTSIncludeSubs is a constant.
	HSTSIncludeSubs bool `json:"hsts_include_subdomains" config:",optional"`
	// CSP is a constant.
	CSP string `json:"csp" config:",optional"`
	// CSPConfig is a constant.
	CSPConfig *CSPConf `json:"csp_config" config:",optional"` // programmatic CSP builder
	// COOP is a constant.
	COOP string `json:"coop" config:",optional"`
	// COEP is a constant.
	COEP string `json:"coep" config:",optional"`
	// CORP is a constant.
	CORP string `json:"corp" config:",optional"`
	// CacheControl is a constant.
	CacheControl string `json:"cache_control" config:",optional"`
	// CSPReportPath is a constant.
	CSPReportPath string `json:"csp_report_path" config:",optional"`
}

type SeedFunc added in v0.13.0

type SeedFunc func(context.Context, *Service) error

SeedFunc is a function that runs after databases are initialized but before the HTTP server starts. Use WithSeed to register seeds for DDL creation, data seeding, and other startup tasks that need database access.

type ServerConf

type ServerConf struct {
	// Mode sets the server operating mode: "monolith" (default) or "micro".
	// In monolith mode, gRPC is disabled and all communication is direct.
	// In micro mode, gRPC server and clients are enabled for inter-service calls.
	Mode string `json:"mode" config:",default=monolith"`
	// Host is a constant.
	Host string `json:"host" config:",default=0.0.0.0"`
	// Prefork is a constant.
	Prefork bool `json:"prefork" config:",optional"`
	// BodyLimit is a constant.
	BodyLimit int `json:"body_limit" config:",default=4194304"`
	// Timeout is a constant.
	Timeout string `json:"timeout" config:",default=30s"`
	// ReadTimeout is a constant.
	ReadTimeout string `json:"read_timeout" config:",default=15s"`
	// WriteTimeout is a constant.
	WriteTimeout string `json:"write_timeout" config:",default=30s"`
	// IdleTimeout is a constant.
	IdleTimeout string `json:"idle_timeout" config:",default=120s"`
	// Compression is a constant.
	Compression bool `json:"compression" config:",optional"`
	// StreamRequestBody is a constant.
	StreamRequestBody bool `json:"stream_request_body" config:",optional"`
	// ReduceMemoryUsage is a constant.
	ReduceMemoryUsage bool `json:"reduce_memory_usage" config:",optional"`
	// MaxConns is a constant.
	MaxConns int `json:"max_conns" config:",default=1000"`
	// MaxBytes is a constant.
	MaxBytes int `json:"max_bytes" config:",default=4194304"`
	// MetricsPath is a constant.
	MetricsPath string `json:"metrics_path" config:",default=/metrics"`
	// HealthPath is a constant.
	HealthPath string `json:"health_path" config:",default=/health"`
	// ShutdownTimeout is a constant.
	ShutdownTimeout string `json:"shutdown_timeout" config:",default=10s"`
	// RecoverStack is a constant.
	RecoverStack bool `json:"recover_stack" config:",default=true"`
	// APIPrefix is a constant.
	APIPrefix string `json:"api_prefix" config:",default=/api"`
	// CORS is a constant.
	CORS *CORSConf `json:"cors" config:",optional"`
	// Middleware is a constant.
	Middleware []RouteMW `json:"middleware" config:",optional"`
	// Static is a constant.
	Static []StaticDef `json:"static" config:",optional"`
	// OpenAPI is a constant.
	OpenAPI *OpenAPIConf `json:"openapi" config:",optional"`
	// SecurityHeaders is a constant.
	SecurityHeaders *SecurityHeadersConf `json:"security_headers" config:",optional"`
	// CSRF is a constant.
	CSRF *CSRFConf `json:"csrf" config:",optional"`
	// RateLimit is a constant.
	RateLimit *RateLimitConf `json:"rate_limit" config:",optional"`
	// TLS is a constant.
	TLS *TLSConf `json:"tls" config:",optional"`
	// SSRF is a constant.
	SSRF *SSRFConf `json:"ssrf" config:",optional"`
	// Cookies is a constant.
	Cookies *CookieConf `json:"cookies" config:",optional"`
	// Security is a constant.
	Security *SecurityDef `json:"security" config:",optional"`
	// SlowQueryThreshold is a constant.
	SlowQueryThreshold string `json:"slow_query_threshold" config:",default=100ms"`
	// GC configures Go runtime garbage collection.
	GC *GCConfig `json:"gc" config:",optional"`
	// Logger is a constant.
	Logger bool `json:"logger" config:",default=true"`
	// LoadShedding is a constant.
	LoadShedding bool `json:"load_shedding" config:",default=true"`
	// Breaker is a constant.
	Breaker bool `json:"breaker" config:",default=true"`
	// Telemetry is a constant.
	Telemetry *TelemetryConf `json:"telemetry" config:",optional"`
	// Correlation enables the X-Correlation-ID tracking middleware.
	Correlation *CorrelationConf `json:"correlation" config:",optional"`
	// LogSkipPaths is a constant.
	LogSkipPaths []string `json:"log_skip_paths" config:",optional"`
	// LogSampleRate is a constant.
	LogSampleRate float64 `json:"log_sample_rate" config:",default=0"`
	// GrpcServer configures the gRPC server.
	GrpcServer *GrpcServerConf `json:"grpc_server" config:",optional"`
	// GrpcClients defines gRPC client connections to other services.
	GrpcClients []GrpcClientConf `json:"grpc_clients" config:",optional"`
}

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the main runtime orchestrator. It reads a service YAML, initializes databases, NATS connections, entry endpoints, and optionally exit workers and cron jobs.

func New

func New(configPath string) (*Service, error)

New creates a Service from a YAML config file path.

func NewFromYAML added in v0.5.3

func NewFromYAML(content []byte) (*Service, error)

NewFromYAML creates a Service from in-memory YAML content (e.g. //go:embed).

func (*Service) App

func (s *Service) App() *fiber.App

App returns the underlying Fiber app.

func (*Service) GetGRPCClient added in v0.12.0

func (s *Service) GetGRPCClient(name string) *GrpcClient

func (*Service) GetGrpcServer added in v0.12.0

func (s *Service) GetGrpcServer() *GrpcServer

KV returns a KV store (Redis/Dragonfly) connection by name, or nil.

func (*Service) KV added in v0.9.0

func (s *Service) KV(name string) *redis.Redis

func (*Service) NATS

func (s *Service) NATS(name string) events.EventBroker

NATS returns a event broker connection by name.

func (*Service) Pool

func (s *Service) Pool(name string) any

Pool returns a DB pool by name.

func (*Service) PoolPG

func (s *Service) PoolPG(name string) any

PoolPG returns a *pgxpool.Pool by name (as any).

func (*Service) PoolPGTyped added in v0.6.0

func (s *Service) PoolPGTyped(name string) *pgxpool.Pool

PoolPGTyped returns a *pgxpool.Pool by name, or nil if not found.

func (*Service) PoolRead added in v0.14.0

func (s *Service) PoolRead(name string) *pgxpool.Pool

PoolRead returns a read replica pool if available, falling back to write pool.

func (*Service) RegisterGrpcService added in v0.15.0

func (s *Service) RegisterGrpcService(name string, fn func(srv *grpc.Server)) *Service

RegisterGrpcService registers a gRPC service factory by proto service name. The factory is called when a "grpc" entry type with matching service_name is declared in the YAML config. Usage:

svc.RegisterGrpcService("AccountService", func(srv *grpc.Server) {
    accountpb.RegisterAccountServiceServer(srv, server.NewAccountGRPCServer(pool))
})

func (*Service) RegisterModel

func (s *Service) RegisterModel(name string, model any) *Service

RegisterModel registers a model for OpenAPI schema generation. Usage: svc.RegisterModel("Product", (*Product)(nil)).

func (*Service) RegisterValidation added in v0.1.0

func (s *Service) RegisterValidation(name string, model any) *Service

RegisterValidation registers a validation model by name for input validation. Usage: svc.RegisterValidation("CreateProduct", CreateProductInput{}).

func (*Service) Run

func (s *Service) Run() error

Run starts the service: init DBs, NATS, register routes, start HTTP server.

func (*Service) RunWithContext

func (s *Service) RunWithContext(ctx context.Context) error

RunWithContext starts the service with a parent context.

func (*Service) SafeHTTPClient added in v0.1.0

func (s *Service) SafeHTTPClient() *middleware.SafeHTTPClient

SafeHTTPClient returns an SSRF-protected HTTP client if configured.

func (*Service) Storage added in v0.6.0

func (s *Service) Storage(path string) server.StorageBackend

Storage returns the storage backend registered for a given entry path.

func (*Service) Stream added in v0.9.0

func (s *Service) Stream(name string) events.EventBroker

Stream returns an event broker connection by name, or nil.

func (*Service) Table added in v0.1.1

func (s *Service) Table(name string) any

Table returns a *db.Table[T] by model name (registered via MustRegister).

func (*Service) WithAPIKeyValidator added in v0.8.0

func (s *Service) WithAPIKeyValidator(fn func(ctx context.Context, key string) (*middleware.AuthContext, error)) *Service

WithAPIKeyValidator registers an API key resolver for "manual" auth mode. The resolver receives the raw API key and returns an AuthContext with the key's identity and roles. Return nil to reject the key. Required when api_key: true + driver: manual.

func (*Service) WithAsync added in v0.1.0

func (s *Service) WithAsync(name string, handler AsyncHandler) *Service

WithAsync registers an async job handler by name.

func (*Service) WithAuthValidator added in v0.3.0

func (s *Service) WithAuthValidator(fn func(context.Context, *middleware.AuthContext, []string, []string) error) *Service

WithAuthValidator registers a custom authorization validator for "manual" auth mode. The validator receives the AuthContext, YAML-defined roles, and YAML-defined permissions. Return nil if allowed, an error with message if denied.

func (*Service) WithCRUD

func (s *Service) WithCRUD(model string, provider CRUDProvider) *Service

WithCRUD registers a CRUD provider for a model name.

func (*Service) WithCRUDFactory added in v0.3.1

func (s *Service) WithCRUDFactory(model string, factory CRUDFactory) *Service

WithCRUDFactory registers a lazy CRUD provider factory. The factory is called once on the first HTTP request, after Run() has initialized all resources (database pools, NATS connections, etc.).

func (*Service) WithCron

func (s *Service) WithCron(name string, handler CronJobFunc) *Service

WithCron registers a cron handler by name (for mode=handler).

func (*Service) WithExit

func (s *Service) WithExit(name string, h ExitHandler) *Service

WithExit registers an exit handler by name (for NATS workers).

func (*Service) WithExitHooks

func (s *Service) WithExitHooks(h map[string]ExitHooks) *Service

WithExitHooks registers exit hooks by worker name.

func (*Service) WithHandlers

func (s *Service) WithHandlers(h *EntryHandlers) *Service

WithHandlers registers all entry handler functions.

func (*Service) WithHooks

func (s *Service) WithHooks(model string, hooks any) *Service

WithHooks registers entry hooks for a model. The hooks are applied to the corresponding CRUD provider if one has been registered for that model.

func (*Service) WithJWTBlacklist added in v0.11.0

func (s *Service) WithJWTBlacklist(fn func(rawToken string) bool) *Service

WithJWTBlacklist registers a callback that checks if a raw JWT is blacklisted. Called after JWT validation succeeds, before the request is processed. Works with all auth drivers: manual, ory, openfga-zitadel. Return true to reject the token (401).

func (*Service) WithRateLimitMaxFunc added in v0.9.0

func (s *Service) WithRateLimitMaxFunc(fn func(c *RestCtx) int) *Service

WithRateLimitMaxFunc registers a dynamic rate limit resolver. The function receives the SDK RestCtx and returns the max requests per window. Overrides YAML-defined static limits when it returns > 0. Useful for per-tenant, per-user, or per-request dynamic rate limits.

func (*Service) WithRest

func (s *Service) WithRest(name string, h func(*RestCtx) error) *Service

WithRest registers a REST handler by name.

func (*Service) WithSSE

func (s *Service) WithSSE(name string, h SSEHandler) *Service

WithSSE registers an SSE handler by name.

func (*Service) WithSeed added in v0.13.0

func (s *Service) WithSeed(fn SeedFunc) *Service

WithSeed registers a seed function that runs after database initialization but before the HTTP server starts. Seeds receive the Service with all pools already initialized. Use for DDL, data seeding, and startup validation.

Example:

svc.WithSeed(func(ctx context.Context, s *runtime.Service) error {
    pool := s.PoolPGTyped("primary")
    _, err := pool.Exec(ctx, "CREATE TABLE IF NOT EXISTS ...")
    return err
})

func (*Service) WithWS

func (s *Service) WithWS(name string, h WSHandler) *Service

WithWS registers a WebSocket handler by name.

type ServiceConfig

type ServiceConfig struct {
	// Name is a constant.
	Name string `json:"name"`
	// Port is a constant.
	Port int `json:"port" config:",default=8080"`
	// Deploy is a constant.
	Deploy *DeployConfig `json:"deploy" config:",optional"`
	// Server is a constant.
	Server ServerConf `json:"server" config:",optional"`
	// Databases is a constant.
	Databases []DBConfig `json:"databases" config:",optional"`
	// KV is a constant.
	KV []KVConfig `json:"kv" config:",optional"`
	// Stream is a constant.
	Stream []StreamConfig `json:"stream" config:",optional"`
	// Entry is a constant.
	Entry []EntryDef `json:"entry" config:",optional"`
	// Exit is a constant.
	Exit []ExitWorker `json:"exit" config:",optional"`
	// Cron is a constant.
	Cron []CronJob `json:"cron" config:",optional"`
	// Auth is a constant.
	Auth *AuthConfig `json:"auth" config:",optional"`
	// Log is a constant.
	Log *logx.LogConf `json:"log" config:",optional"`
	// Prometheus enables prometheus metrics via infra/metric.
	Prometheus *PrometheusConfig `json:"prometheus" config:",optional"`
}

func LoadConfig

func LoadConfig(path string) (*ServiceConfig, error)

func ParseConfig added in v0.5.3

func ParseConfig(content []byte) (*ServiceConfig, error)

type SlowQueryConf added in v0.11.0

type SlowQueryConf struct {
	// Enabled enables slow query logging for this database.
	Enabled bool `json:"enabled" config:",optional"`
	// Threshold is the duration after which a query is considered slow (e.g. "200ms", "1s").
	Threshold string `json:"threshold" config:",default=100ms"`
}

type StaticDef

type StaticDef struct {
	// Prefix is a constant.
	Prefix string `json:"prefix"`
	// Dir is a constant.
	Dir string `json:"dir"`
}

type StorageDef

type StorageDef struct {
	// Mode is a constant.
	Mode string `json:"mode"` // s3, local
	// Bucket is a constant.
	Bucket string `json:"bucket" config:",optional"`
	// Path is a constant.
	Path string `json:"path" config:",optional"`
	// Region is a constant.
	Region string `json:"region" config:",optional"`
	// Endpoint is a constant.
	Endpoint string `json:"endpoint" config:",optional"`
	// AccessKey is a constant.
	AccessKey string `json:"access_key" config:",optional"`
	// SecretKey is a constant.
	SecretKey string `json:"secret_key" config:",optional"`
	// Presign is a constant.
	Presign bool `json:"presign" config:",optional"`
	// PresignTTL is a constant.
	PresignTTL string `json:"presign_ttl" config:",default=5m"`
	// Pool is a constant.
	Pool *PoolConfig `json:"pool" config:",optional"`
	// Cache is a constant.
	Cache *CacheConfig `json:"cache" config:",optional"`
}

type StreamConfig added in v0.9.0

type StreamConfig struct {
	// Name is a constant.
	Name string `json:"name"`
	// Driver is a constant.
	Driver string `json:"driver" config:",default=nats"`
	// URL is a constant.
	URL string `json:"url" config:",optional"`
	// Brokers is a constant.
	Brokers []string `json:"brokers" config:",optional"`
	// ConsumerGroup is a constant.
	ConsumerGroup string `json:"consumer_group" config:",optional"`
	// MaxReconnects is a constant.
	MaxReconnects int `json:"max_reconnects" config:",optional"`
	// ReconnectWait is a constant.
	ReconnectWait string `json:"reconnect_wait" config:",optional"`
	// Timeout is a constant.
	Timeout string `json:"timeout" config:",optional"`
	// RetryOnFail is a constant.
	RetryOnFail bool `json:"retry_on_fail" config:",optional"`
	// Streams is a constant.
	Streams []StreamDef `json:"streams" config:",optional"`
}

type StreamDef

type StreamDef struct {
	// Name is a constant.
	Name string `json:"name"`
	// MaxAge is a constant.
	MaxAge string `json:"max_age" config:",optional"`
	// MaxBytes is a constant.
	MaxBytes int64 `json:"max_bytes" config:",optional"`
	// Storage is a constant.
	Storage string `json:"storage" config:",default=file"`
	// Compression is a constant.
	Compression string `json:"compression" config:",default=s2"`
}

type SubscribeDef

type SubscribeDef struct {
	// Stream is a constant.
	Stream string `json:"stream"`
	// Subject is a constant.
	Subject string `json:"subject" config:",optional"`
	// Durable is a constant.
	Durable string `json:"durable" config:",optional"`
}

type TLSConf added in v0.1.0

type TLSConf struct {
	// Enabled is a constant.
	Enabled bool `json:"enabled"`
	// Manual is a constant.
	Manual *ManualTLS `json:"manual" config:",optional"`
	// Autocert is a constant.
	Autocert *AutocertTLS `json:"autocert" config:",optional"`
	// MinVersion is a constant.
	MinVersion string `json:"min_version" config:",optional"`
	// MaxVersion is a constant.
	MaxVersion string `json:"max_version" config:",optional"`
	// CurvePrefs is a constant.
	CurvePrefs []string `json:"curve_preferences" config:",optional"`
	// CipherSuites is a constant.
	CipherSuites []string `json:"cipher_suites" config:",optional"`
	// RedirectHTTP is a constant.
	RedirectHTTP bool `json:"redirect_http" config:",optional"`
	// RedirectPort is a constant.
	RedirectPort int `json:"redirect_port" config:",optional"`
}

type TelemetryConf added in v0.1.1

type TelemetryConf struct {
	Enabled bool   `json:"enabled" config:",optional"`
	Name    string `json:"name" config:",optional"`
	// Endpoint is the OTLP receiver address (e.g. "localhost:4317").
	Endpoint string  `json:"endpoint" config:",optional"`
	Sampler  float64 `json:"sampler" config:",default=1.0"`
	// Batcher is the exporter type: otlpgrpc | otlphttp | zipkin | file.
	Batcher string `json:"batcher" config:",default=otlpgrpc"`
	// OtlpHeaders are additional headers sent with OTLP export requests.
	OtlpHeaders map[string]string `json:"otlp_headers" config:",optional"`
	// OtlpHttpPath is the URL path for OTLP HTTP transport (e.g. "/v1/traces").
	OtlpHttpPath string `json:"otlp_http_path" config:",optional"`
	// OtlpHttpSecure enables TLS for OTLP HTTP transport.
	OtlpHttpSecure bool `json:"otlp_http_secure" config:",optional"`
	// TraceResponseHeader sets a response header exposing the trace ID (e.g. "X-Trace-Id").
	TraceResponseHeader string `json:"trace_response_header" config:",optional"`
	// SkipPaths are request paths that should not be traced.
	SkipPaths []string `json:"skip_paths" config:",optional"`
}

type TursoConf added in v0.4.2

type TursoConf struct {
	// Mode is a constant.
	Mode string `json:"mode" config:",default=local"` // local | remote
	// BusyTimeout is a constant.
	BusyTimeout int `json:"busy_timeout" config:",default=30000"` // ms, 0 = no wait
}

func (*TursoConf) Validate added in v0.5.1

func (t *TursoConf) Validate() error

type WSHandler

type WSHandler func(ctx context.Context, conn *websocket.Conn) error

WSHandler is called when a WebSocket client connects.

Directories

Path Synopsis
Package auth provides password hashing, verification, token generation, and role hierarchy utilities.
Package auth provides password hashing, verification, token generation, and role hierarchy utilities.

Jump to

Keyboard shortcuts

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