Documentation
¶
Overview ¶
Package runtime provides the service orchestrator.
Index ¶
- Constants
- Variables
- func BuildDirectTarget(endpoints []string) string
- func BuildEtcdTarget(endpoints []string, key string) string
- func BuildOpenAPI(cfg *ServiceConfig, models map[string]*db.TableInfo) (*openapi3.T, error)
- func BulkheadGet(name string) *syncx.Limit
- func BulkheadRegister(name string, limit int)
- func CachedCRUD[T any](svc *Service, name, poolName, tableName string, kvName string, ...)
- func CheckVercelWarnings(cfg *ServiceConfig)
- func GetTable[T any](s *Service, name string) *db.Table[T]
- func MongoMustRegister(svc *Service, name, poolName, database, collection, lookupField string)
- func MustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
- func MySQLCachedCRUD[T any](svc *Service, name, poolName, tableName string, kvName string, ...)
- func MySQLMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
- func Pool(pools map[string]any, name string) any
- func PoolPG(pools map[string]any, name string) *pgxpool.Pool
- func PoolSQL(pools map[string]any, name string) *sql.DB
- func RegisterEntries(app *fiber.App, cfg *ServiceConfig, handlers *EntryHandlers, prefix string, ...) error
- func SanitizeFilename(name string) string
- func SetRateLimitMaxFunc(fn func(c fiber.Ctx) int)
- func TableFor[T any](pools map[string]any, poolName, tableName string) (*db.Table[T], error)
- func TursoMustRegister[T any](svc *Service, name, poolName, tableName string, hooks EntryHooks[T])
- func ValidateProjectStructure(yamlPath string, target string) error
- func WrapTransformHandler[T any](handler func(fiber.Ctx) error, hooks EntryHooks[T]) func(fiber.Ctx) error
- type AsyncHandler
- type AsyncJobManager
- type AuthConfig
- type AuthCookieConfig
- type AutocertTLS
- type CORSConf
- type CRUDFactory
- type CRUDOverrides
- type CRUDProvider
- func NewCRUDProvider[T any](table *db.Table[T], hooks EntryHooks[T]) CRUDProvider
- func NewMongoCRUDProvider(model *mon.Model, lookupField string) CRUDProvider
- func NewMySQLCRUDProvider[T any](table *db.MySQLTable[T], hooks EntryHooks[T]) CRUDProvider
- func NewTursoCRUDProvider[T any](table *db.TursoTable[T], hooks EntryHooks[T]) CRUDProvider
- type CSPConf
- type CSRFConf
- type CacheConfig
- type ContentSecurityDef
- type Cookie
- type CookieConf
- type CorrelationConf
- type CronJob
- type CronJobFunc
- type CronPublish
- type CronScheduler
- type CryptionDef
- type DBConfig
- type DefaultExitHooks
- type DefaultHooks
- func (DefaultHooks[T]) AfterCreate(_ context.Context, _ *T) error
- func (DefaultHooks[T]) AfterDelete(_ context.Context, _ string) error
- func (DefaultHooks[T]) AfterTransform(_ context.Context, _ any) error
- func (DefaultHooks[T]) AfterUpdate(_ context.Context, _ *T) error
- func (DefaultHooks[T]) BeforeCreate(_ context.Context, req T) (T, error)
- func (DefaultHooks[T]) BeforeDelete(_ context.Context, _ string) error
- func (DefaultHooks[T]) BeforeTransform(_ context.Context, req T) (T, error)
- func (DefaultHooks[T]) BeforeUpdate(_ context.Context, _ string, patch map[string]any) (map[string]any, error)
- type DeployConfig
- type EncryptCookieDef
- type EntryDef
- type EntryHandlers
- type EntryHooks
- type EventPublishTarget
- type EventStreamConnConf
- type ExitHandler
- type ExitHooks
- type ExitWorker
- type ExitWorkerManager
- type GrpcClient
- type GrpcClientConf
- type GrpcInterceptorsConfig
- type GrpcRegisterFn
- type GrpcServer
- type GrpcServerConf
- type JobState
- type JobStatus
- type JobStore
- type KVConfig
- type KeysetResponse
- type ListParams
- type ManualTLS
- type Map
- type OpenAPIConf
- type PaginatedResponse
- type PoolConf
- type PoolConfig
- type PoolHealth
- type RateLimitConf
- type RateLimitDef
- type RedisConfig
- type RefreshConfig
- type RestCtx
- func (c *RestCtx) Bind(v any) error
- func (c *RestCtx) Body() []byte
- func (c *RestCtx) Context() context.Context
- func (c *RestCtx) Get(key string) string
- func (c *RestCtx) JSON(data any) error
- func (c *RestCtx) Locals(key any, values ...any) any
- func (c *RestCtx) Method() string
- func (c *RestCtx) Params(key string) string
- func (c *RestCtx) Path() string
- func (c *RestCtx) PoolPG(name string) *pgxpool.Pool
- func (c *RestCtx) PoolSQL(name string) *sql.DB
- func (c *RestCtx) Query(key string, defaultValue ...string) string
- func (c *RestCtx) Redirect(url string, statusCode ...int) error
- func (c *RestCtx) ResponseBody() string
- func (c *RestCtx) SendStatus(code int) error
- func (c *RestCtx) SendString(s string) error
- func (c *RestCtx) Set(key, val string)
- func (c *RestCtx) SetCookie(cookie *Cookie)
- func (c *RestCtx) Status(code int) *RestCtx
- func (c *RestCtx) StatusCode() int
- type RetryConf
- type RouteMW
- type SSEHandler
- type SSRFConf
- type SecurityDef
- type SecurityHeadersConf
- type ServerConf
- type Service
- func (s *Service) App() *fiber.App
- func (s *Service) KV(name string) *redis.Redis
- func (s *Service) NATS(name string) events.EventBroker
- func (s *Service) Pool(name string) any
- func (s *Service) PoolPG(name string) any
- func (s *Service) PoolPGTyped(name string) *pgxpool.Pool
- func (s *Service) RegisterModel(name string, model any) *Service
- func (s *Service) RegisterValidation(name string, model any) *Service
- func (s *Service) Run() error
- func (s *Service) RunWithContext(ctx context.Context) error
- func (s *Service) SafeHTTPClient() *middleware.SafeHTTPClient
- func (s *Service) Storage(path string) server.StorageBackend
- func (s *Service) Stream(name string) events.EventBroker
- func (s *Service) Table(name string) any
- func (s *Service) WithAPIKeyValidator(fn func(ctx context.Context, key string) (*middleware.AuthContext, error)) *Service
- func (s *Service) WithAsync(name string, handler AsyncHandler) *Service
- func (s *Service) WithAuthValidator(fn func(context.Context, *middleware.AuthContext, []string, []string) error) *Service
- func (s *Service) WithCRUD(model string, provider CRUDProvider) *Service
- func (s *Service) WithCRUDFactory(model string, factory CRUDFactory) *Service
- func (s *Service) WithCron(name string, handler CronJobFunc) *Service
- func (s *Service) WithExit(name string, h ExitHandler) *Service
- func (s *Service) WithExitHooks(h map[string]ExitHooks) *Service
- func (s *Service) WithHandlers(h *EntryHandlers) *Service
- func (s *Service) WithHooks(model string, hooks any) *Service
- func (s *Service) WithJWTBlacklist(fn func(rawToken string) bool) *Service
- func (s *Service) WithRateLimitMaxFunc(fn func(c *RestCtx) int) *Service
- func (s *Service) WithRest(name string, h func(*RestCtx) error) *Service
- func (s *Service) WithSSE(name string, h SSEHandler) *Service
- func (s *Service) WithWS(name string, h WSHandler) *Service
- type ServiceConfig
- type SlowQueryConf
- type StaticDef
- type StorageDef
- type StreamConfig
- type StreamDef
- type SubscribeDef
- type TLSConf
- type TelemetryConf
- type TursoConf
- type WSHandler
Constants ¶
const ( TargetAuto = "auto" TargetVercel = "vercel" TargetDocker = "docker" TargetKube = "kube" TargetBare = "bare-metal" )
const NodeType = redis.NodeType
Variables ¶
var ErrNotFound = db.ErrNotFound
ErrNotFound is returned when a database record is not found.
Functions ¶
func BuildDirectTarget ¶ added in v0.11.0
func BuildEtcdTarget ¶ added in v0.11.0
func BuildOpenAPI ¶
BuildOpenAPI generates an OpenAPI 3.0.3 spec from the service config and registered models.
func BulkheadGet ¶ added in v0.11.0
func BulkheadRegister ¶ added in v0.11.0
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 GetTable ¶ added in v0.6.0
GetTable returns a typed *db.Table[T] for a model registered via MustRegister.
func MongoMustRegister ¶ added in v0.4.0
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 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 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 SanitizeFilename ¶ added in v0.1.0
func SetRateLimitMaxFunc ¶ added in v0.9.0
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
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 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 AsyncHandler ¶ added in v0.1.0
AsyncHandler is a function that processes an async job. body contains the raw request body from the POST. job holds the job state — mutate job.Result before returning.
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
NewAsyncJobManager creates a new manager with the given store and processor.
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) 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 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 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 ContentSecurityDef ¶ added in v0.2.0
type Cookie ¶ added in v0.9.0
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.
type CookieConf ¶ added in v0.1.0
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"`
}
type CronJobFunc ¶
type CronPublish ¶
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 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"`
// 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"`
}
type DefaultExitHooks ¶
type DefaultExitHooks struct{}
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)
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 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
}
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
}
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 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 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
}
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 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"`
// 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 GrpcRegisterFn ¶ added in v0.11.0
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"`
}
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"`
}
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.
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)
}
JobStore persists and retrieves job state.
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 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"`
}
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"`
}
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 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 RedisConfig ¶ added in v0.1.1
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) ResponseBody ¶ added in v0.4.1
func (*RestCtx) SendStatus ¶ added in v0.4.1
func (*RestCtx) SendString ¶ added in v0.4.1
func (*RestCtx) StatusCode ¶ added in v0.4.1
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 SSEHandler ¶
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 ServerConf ¶
type ServerConf struct {
// 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"`
// 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"`
// 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"`
// 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 NewFromYAML ¶ added in v0.5.3
NewFromYAML creates a Service from in-memory YAML content (e.g. //go:embed).
func (*Service) KV ¶ added in v0.9.0
KV returns a KV store (Redis/Dragonfly) connection by name, or nil.
func (*Service) NATS ¶
func (s *Service) NATS(name string) events.EventBroker
NATS returns a event broker connection by name.
func (*Service) PoolPGTyped ¶ added in v0.6.0
PoolPGTyped returns a *pgxpool.Pool by name, or nil if not found.
func (*Service) RegisterModel ¶
RegisterModel registers a model for OpenAPI schema generation. Usage: svc.RegisterModel("Product", (*Product)(nil)).
func (*Service) RegisterValidation ¶ added in v0.1.0
RegisterValidation registers a validation model by name for input validation. Usage: svc.RegisterValidation("CreateProduct", CreateProductInput{}).
func (*Service) RunWithContext ¶
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
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 ¶
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 ¶
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
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
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.
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"`
}
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 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 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"`
}
Source Files
¶
- async_job.go
- async_store.go
- bulkhead.go
- config.go
- cron.go
- db_health.go
- db_resolver.go
- docs.go
- entry.go
- entry_async.go
- entry_crud.go
- entry_file.go
- entry_graphql.go
- entry_grpc.go
- entry_realtime.go
- entry_rest.go
- exit.go
- graphql_resolver.go
- graphql_schema.go
- grpc.go
- grpc_interceptors.go
- grpc_resolver.go
- hooks.go
- lazy_crud.go
- openapi.go
- redis.go
- rest_ctx.go
- service.go
- table_provider.go
- validate.go