runtime

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

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

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

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

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) error, fgaClient openfga.Checker, oryClient *ory.Client, zitadelClient *zitadel.Client) error

func SanitizeFilename added in v0.1.0

func SanitizeFilename(name string) string

SanitizeFilename removes dangerous characters from filenames. - Removes path separators (/, \) - Removes null bytes - Limits length to 255 chars - Only allows [a-zA-Z0-9._-]

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

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

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      bool   `json:"enabled" config:",optional"`
	Driver       string `json:"driver" config:",default=none"` // none | manual | openfga-zitadel | ory
	Secret       string `json:"secret" config:",optional"`
	PrevSecret   string `json:"prev_secret" config:",optional"`
	Algorithm    string `json:"algorithm" config:",default=HS256"`
	TokenLookup  string `json:"token_lookup" config:",default=header:Authorization"`
	ContextKey   string `json:"context_key" config:",default=claims"`
	Issuer       string `json:"issuer" config:",optional"`
	Audience     string `json:"audience" config:",optional"`
	Expiry       int    `json:"expiry" config:",default=3600"`
	ZitadelURL   string `json:"zitadel_url" config:",optional"`
	OpenFGAURL   string `json:"openfga_url" config:",optional"`
	OpenFGAStore string `json:"openfga_store" config:",optional"`
	KratosURL    string `json:"kratos_url" config:",optional"`
	KetoURL      string `json:"keto_url" config:",optional"`
}

type AutocertTLS added in v0.1.0

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

type CORSConf

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

type CRUDOverrides

type CRUDOverrides struct {
	List   string `json:"list" config:",optional"`
	Get    string `json:"get" config:",optional"`
	Create string `json:"create" config:",optional"`
	Update string `json:"update" config:",optional"`
	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 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 CSRFConf added in v0.1.0

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

type ContentSecurityDef added in v0.2.0

type ContentSecurityDef struct {
	Enabled   bool   `json:"enabled" config:",optional"`
	Strict    bool   `json:"strict" config:",optional"`
	PublicKey string `json:"public_key"`
}

type CookieConf added in v0.1.0

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

type CronJob

type CronJob struct {
	Name     string       `json:"name"`
	Schedule string       `json:"schedule"`
	Mode     string       `json:"mode" config:",default=nats"` // nats, handler, internal
	Publish  *CronPublish `json:"publish" config:",optional"`
	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  string `json:"stream"`
	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 bool   `json:"enabled" config:",optional"`
	Key     string `json:"key"`
}

type DBConfig

type DBConfig struct {
	Name   string    `json:"name"`
	Driver string    `json:"driver" config:",default=postgres"`
	URL    string    `json:"url"`
	Pool   *PoolConf `json:"pool" 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 EntryDef

type EntryDef struct {
	Type        string   `json:"type"` // crud, rest, webhook, websocket, sse, file
	Method      string   `json:"method" config:",optional"`
	Path        string   `json:"path" config:",optional"`
	Handler     string   `json:"handler" config:",optional"`
	Auth        bool     `json:"auth" config:",optional"`
	Roles       []string `json:"roles" config:",optional"`
	Permissions []string `json:"permissions" config:",optional"`
	DB          string   `json:"db" config:",optional"` // references database name

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

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

	// Publish after entry — event_publish is the new name, nats_publish is legacy
	EventPublish []EventPublishTarget `json:"event_publish" config:",optional"`
	NATSPublish  []EventPublishTarget `json:"nats_publish" config:",optional"`

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

	// Security per-entry overrides
	CSRF      *bool         `json:"csrf" config:",optional"`       // false = skip CSRF for this entry
	RateLimit *RateLimitDef `json:"rate_limit" config:",optional"` // per-entry rate limit

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

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
}

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      string `json:"stream"`
	Subject     string `json:"subject" config:",optional"`
	EventStream string `json:"event_stream" config:",optional"` // broker name; empty = all brokers
}

type EventStreamConnConf added in v0.1.0

type EventStreamConnConf struct {
	Name          string      `json:"name"`
	Driver        string      `json:"driver"` // nats, kafka
	URL           string      `json:"url" config:",optional"`
	Brokers       []string    `json:"brokers" config:",optional"`
	ConsumerGroup string      `json:"consumer_group" config:",optional"`
	MaxReconnects int         `json:"max_reconnects" config:",optional"`
	ReconnectWait string      `json:"reconnect_wait" config:",optional"`
	Timeout       string      `json:"timeout" config:",optional"`
	RetryOnFail   bool        `json:"retry_on_fail" config:",optional"`
	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          string       `json:"name"`
	Subscribe     SubscribeDef `json:"subscribe"`
	Handler       string       `json:"handler"`
	MaxConcurrent int          `json:"max_concurrent" config:",default=1"`
	DB            string       `json:"db" config:",optional"`
	Reply         bool         `json:"reply" config:",optional"`
	ReplyTimeout  string       `json:"reply_timeout" config:",default=30s"`
	PullBatch     int          `json:"pull_batch" config:",optional"`
	PullMaxWait   string       `json:"pull_max_wait" config:",optional"`
	ConsumerMode  string       `json:"consumer_mode" config:",optional"` // push or pull
	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 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.

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

JobStore persists and retrieves job state.

type ListParams

type ListParams struct {
	Page    int
	Size    int
	Sort    string
	Filters map[string]string
}

type ManualTLS added in v0.1.0

type ManualTLS struct {
	CertFile string `json:"cert_file"`
	KeyFile  string `json:"key_file"`
}

type NATSPublishTarget

type NATSPublishTarget = EventPublishTarget

type OpenAPIConf

type OpenAPIConf struct {
	Enabled  bool   `json:"enabled" config:",optional"`
	Version  string `json:"version" config:",default=1.0.0"`
	SpecPath string `json:"spec_path" config:",default=/openapi.json"`
	DocsPath string `json:"docs_path" config:",default=/docs"`
	Theme    string `json:"theme" config:",default=moon"`
	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.

type PoolConf

type PoolConf struct {
	MaxConns          int32  `json:"max_conns" config:",default=10"`
	MinConns          int32  `json:"min_conns" config:",default=2"`
	MaxConnLifetime   string `json:"max_conn_lifetime" config:",optional"`
	MaxConnIdleTime   string `json:"max_conn_idle_time" config:",optional"`
	HealthCheckPeriod string `json:"health_check_period" config:",optional"`
	ReservedConns     int32  `json:"reserved_conns" config:",default=10"`
}

type RateLimitConf added in v0.1.0

type RateLimitConf struct {
	Enabled  bool          `json:"enabled" config:",optional"`
	Driver   string        `json:"driver" config:",default=memory"`
	RedisURL string        `json:"redis_url" config:",optional"`
	Global   *RateLimitDef `json:"global" config:",optional"`
	PerIP    *RateLimitDef `json:"per_ip" config:",optional"`
	PerUser  *RateLimitDef `json:"per_user" config:",optional"`
}

type RateLimitDef added in v0.1.0

type RateLimitDef struct {
	RequestsPerSecond int `json:"requests_per_second"`
	Burst             int `json:"burst"`
}

type RouteMW

type RouteMW struct {
	Path  string   `json:"path"`
	Apply []string `json:"apply"`
}

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       bool     `json:"enabled" config:",optional"`
	BlockPrivate  bool     `json:"block_private" config:",optional"`
	BlockLoopback bool     `json:"block_loopback" config:",optional"`
	BlockMetadata bool     `json:"block_metadata" config:",optional"`
	AllowedHosts  []string `json:"allowed_hosts" config:",optional"`
}

type SecurityDef added in v0.2.0

type SecurityDef struct {
	ContentSecurity *ContentSecurityDef `json:"content_security" config:",optional"`
	Cryption        *CryptionDef        `json:"cryption" config:",optional"`
}

type SecurityHeadersConf added in v0.1.0

type SecurityHeadersConf struct {
	FrameOptions      string `json:"frame_options" config:",optional"`
	ReferrerPolicy    string `json:"referrer_policy" config:",optional"`
	PermissionsPolicy string `json:"permissions_policy" config:",optional"`
	HSTS              bool   `json:"hsts" config:",optional"`
	HSTSMaxAge        int    `json:"hsts_max_age" config:",optional"`
	HSTSIncludeSubs   bool   `json:"hsts_include_subdomains" config:",optional"`
	CSP               string `json:"csp" config:",optional"`
	COOP              string `json:"coop" config:",optional"`
	COEP              string `json:"coep" config:",optional"`
	CORP              string `json:"corp" config:",optional"`
	CacheControl      string `json:"cache_control" config:",optional"`
	CSPReportPath     string `json:"csp_report_path" config:",optional"` // auto-register POST endpoint for CSP reports (e.g. "/csp-violation")
}

type ServerConf

type ServerConf struct {
	Host            string               `json:"host" config:",default=0.0.0.0"`
	Prefork         bool                 `json:"prefork" config:",optional"`
	BodyLimit       int                  `json:"body_limit" config:",default=4194304"`
	Timeout         string               `json:"timeout" config:",default=30s"`
	MaxConns        int                  `json:"max_conns" config:",default=1000"`
	MaxBytes        int                  `json:"max_bytes" config:",default=4194304"`
	MetricsPath     string               `json:"metrics_path" config:",default=/metrics"`
	HealthPath      string               `json:"health_path" config:",default=/health"`
	ShutdownTimeout string               `json:"shutdown_timeout" config:",default=10s"`
	RecoverStack    bool                 `json:"recover_stack" config:",default=true"`
	APIPrefix       string               `json:"api_prefix" config:",default=/api/v1"`
	CORS            *CORSConf            `json:"cors" config:",optional"`
	Middleware      []RouteMW            `json:"middleware" config:",optional"`
	Static          []StaticDef          `json:"static" config:",optional"`
	MaxConnLimit    int                  `json:"max_conn_limit" config:",default=1000"`
	OpenAPI         *OpenAPIConf         `json:"openapi" config:",optional"`
	SecurityHeaders *SecurityHeadersConf `json:"security_headers" config:",optional"`
	CSRF            *CSRFConf            `json:"csrf" config:",optional"`
	RateLimit       *RateLimitConf       `json:"rate_limit" config:",optional"`
	TLS             *TLSConf             `json:"tls" config:",optional"`
	SSRF            *SSRFConf            `json:"ssrf" config:",optional"`
	Cookies         *CookieConf          `json:"cookies" config:",optional"`
	Security        *SecurityDef         `json:"security" 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.

func (*Service) App

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

App returns the underlying Fiber app.

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.

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) 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) error) *Service

WithAuthValidator registers a custom authorization validator for "manual" auth mode. The validator receives the AuthContext and the YAML-defined roles for the entry. 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) 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) WithRest

func (s *Service) WithRest(name string, h func(*fiber.Ctx) 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) WithWS

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

WithWS registers a WebSocket handler by name.

type ServiceConfig

type ServiceConfig struct {
	Name         string                `json:"name"`
	Port         int                   `json:"port" config:",default=8080"`
	Server       ServerConf            `json:"server" config:",optional"`
	Databases    []DBConfig            `json:"databases" config:",optional"`
	EventStreams []EventStreamConnConf `json:"event_streams" config:",optional"`
	Entry        []EntryDef            `json:"entry" config:",optional"`
	Exit         []ExitWorker          `json:"exit" config:",optional"`
	Cron         []CronJob             `json:"cron" config:",optional"`
	Auth         *AuthConfig           `json:"auth" config:",optional"`
}

func LoadConfig

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

type StaticDef

type StaticDef struct {
	Prefix string `json:"prefix"`
	Dir    string `json:"dir"`
}

type StorageDef

type StorageDef struct {
	Mode      string `json:"mode"` // s3, local
	Bucket    string `json:"bucket" config:",optional"`
	Path      string `json:"path" config:",optional"`
	Region    string `json:"region" config:",optional"`
	Endpoint  string `json:"endpoint" config:",optional"`
	AccessKey string `json:"access_key" config:",optional"`
	SecretKey string `json:"secret_key" config:",optional"`
}

type StreamDef

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

type SubscribeDef

type SubscribeDef struct {
	Stream  string `json:"stream"`
	Subject string `json:"subject" config:",optional"`
	Durable string `json:"durable" config:",optional"`
}

type TLSConf added in v0.1.0

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

type WSHandler

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

WSHandler is called when a WebSocket client connects.

Jump to

Keyboard shortcuts

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