Documentation
¶
Overview ¶
Package fletch composes the standalone Fletch modules into an app: the router, Crest elements, Live, assets, images, and the pluggable subsystems, each with a default that needs no external service.
Index ¶
- Constants
- func BuildID() string
- func CSRF(secret []byte, opts ...auth.CSRFOption) (func(http.Handler) http.Handler, error)
- func DB(ctx context.Context) *sql.DB
- func Dump(values ...any)
- func DumpCtx(ctx context.Context, values ...any)
- func Live(fn func() live.Component, opts ...live.Option) http.Handler
- func MountAdmin(a *App, panels ...AdminPanel) error
- func MountAdminHost(a *App, host string, panels ...AdminPanel) error
- func MountLive(r *router.Router, name, path string, fn func() live.Component, ...)
- func ObserveCache(c cache.Cache) cache.Cache
- func ObserveTransport(rt http.RoundTripper) http.RoundTripper
- func Pool[T any](ctx context.Context) (pool T, ok bool)
- func ReadDB(ctx context.Context) *sql.DB
- func Recover(next http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequestIDFrom(ctx context.Context) string
- func Run(a *App, opts ...RunOption) error
- func SiteAssets(byHost map[string]assets.Resolver, fallback assets.Resolver) func(http.Handler) http.Handler
- func StaticOrigin(r *http.Request, origin string) bool
- func WrapHTTPClient(c *http.Client) *http.Client
- type AdminHost
- type AdminPanel
- type App
- func (a *App) Alpine() *alpine.Bundle
- func (a *App) Assets() assets.Resolver
- func (a *App) Auth() auth.Authenticator
- func (a *App) Cache() cache.Cache
- func (a *App) Clock() func() time.Time
- func (a *App) Command(cmds ...cli.Command)
- func (a *App) Commands() []cli.Command
- func (a *App) ConfigReport() *config.Report
- func (a *App) Contract() Contract
- func (a *App) DB() *sql.DB
- func (a *App) EvictLiveBinding(key string) int
- func (a *App) GateObserver() DecisionObserver
- func (a *App) HandleInspectFlag(args []string, w io.Writer) bool
- func (a *App) Handler() http.Handler
- func (a *App) Images() images.Service
- func (a *App) InlineFast(x *httpengine.Context) bool
- func (a *App) Inspect() ax.InspectReport
- func (a *App) JobObserver() quiver.Observer
- func (a *App) ListenAndServe(ctx context.Context, addr string) error
- func (a *App) Mailer() mail.Mailer
- func (a *App) Main(ctx context.Context)
- func (a *App) Modules() []string
- func (a *App) Mount(mods ...Module) error
- func (a *App) Nock() NockDB
- func (a *App) NockObserver() nock.QueryObserver
- func (a *App) OnShutdown(fn func(context.Context) error)
- func (a *App) OnStart(fn func(context.Context) error)
- func (a *App) PubSub() pubsub.Broker
- func (a *App) PubSubBus() *pubsub.Bus
- func (a *App) Quiver() quiver.Queue
- func (a *App) Registry() *ax.Registry
- func (a *App) Router() *router.Router
- func (a *App) RunCLI(ctx context.Context, args []string) error
- func (a *App) ServeFast(x *httpengine.Context) bool
- func (a *App) ServeOpenAPI(path string, spec []byte)
- func (a *App) SessionCookie(secret []byte, opts ...auth.CookieOption) (*auth.SessionCookie, error)
- func (a *App) Sessions() auth.SessionStore
- func (a *App) Start(ctx context.Context) (<-chan struct{}, error)
- func (a *App) Storage() storage.Store
- func (a *App) StorageManager() *storage.Manager
- func (a *App) Use(mw ...func(http.Handler) http.Handler)
- type Contract
- type ContractLive
- type Ctx
- type DecisionObserver
- type DevDashboard
- type DevPanel
- type Input
- type JobsResult
- type JobsSummary
- type LiveSessionInfo
- type Module
- type NockDB
- type Observability
- type Option
- func WithAllowMemoryQueue() Option
- func WithAlpine(opts ...alpine.Option) Option
- func WithAssets(r assets.Resolver) Option
- func WithAudit(rec audit.Recorder) Option
- func WithAuth(au auth.Authenticator) Option
- func WithCache(c cache.Cache) Option
- func WithClock(now func() time.Time) Option
- func WithCommands(cmds ...cli.Command) Option
- func WithConfigReport(r *config.Report) Option
- func WithDB(db *sql.DB) Option
- func WithDevDashboard(d DevDashboard) Option
- func WithElements(ps ...plugin.ElementPlugin) Option
- func WithFastServer(opts ...httpengine.Option) Option
- func WithHealthPaths(live, ready string) Option
- func WithImageOptions(opts ...images.Option) Option
- func WithImages(s images.Service) Option
- func WithMailer(m mail.Mailer) Option
- func WithMigrations(fsys fs.FS) Option
- func WithNock(db NockDB) Option
- func WithObservability(o Observability) Option
- func WithOpenAPI(spec []byte) Option
- func WithPgxPool(pool any) Option
- func WithPinger(name string, p Pinger) Option
- func WithPubSub(b pubsub.Broker) Option
- func WithQuiver(q quiver.Queue) Option
- func WithRedactedPanics() Option
- func WithRouterOptions(opts ...router.Option) Option
- func WithRoutes(fn func(*router.Router)) Option
- func WithSeeders(s ...migrate.Seeder) Option
- func WithSessions(s auth.SessionStore) Option
- func WithStaticFrontend(sf StaticFrontend) Option
- func WithStorage(s storage.Store) Option
- func WithStorageManager(m *storage.Manager) Option
- func WithoutHealthChecks() Option
- func WithoutQueueWorker() Option
- type Pinger
- type Public
- type QueryResult
- type RunOption
- type ScheduleStatus
- type StaticFrontend
Constants ¶
const ContractPath = "/_fletch/contract"
ContractPath serves the backend's contract with its static frontends.
const LivePrefix = "/_fletch/live"
LivePrefix is where WithStaticFrontend serves every Live page's endpoint: the page at /counter joins at /_fletch/live/counter.
const RequestIDHeader = "X-Request-ID"
RequestIDHeader carries the request ID on requests and responses.
const Version = "0.4.0"
Version is the Fletch version reported by fletch ax inspect.
Variables ¶
This section is empty.
Functions ¶
func BuildID ¶ added in v0.4.0
func BuildID() string
BuildID identifies this build: $FLETCH_BUILD_ID, else the VCS revision the binary was built from (with -dirty for uncommitted changes), else "unknown".
func CSRF ¶
CSRF returns the auth.CSRF middleware with the token also installed where <f:csrf /> reads it, in the request context and in the context of a Live view mounted by that request. Install it with Router.Use after auth.OriginProtection; opts are those of auth.CSRF. Live pages served by Live or MountLive carry the token on their root, and the Live runtime sends it in the X-CSRF-Token header, so keep the default header name when the app has Live pages.
With WithStaticFrontend, Live endpoints and StaticFrontend.Forms paths check the Origin instead of the token: a request from an allowed origin passes, and a POST with neither an Origin nor Sec-Fetch-Site: same-origin is refused.
func DB ¶
DB returns the database of the request that reached ctx: the one given to WithDB, or nil. In a Live view it works with the *live.Ctx of Mount and of actions.
func Dump ¶
func Dump(values ...any)
Dump shows values in the dev dashboard's Dumps panel with the file and line of the call. It does nothing unless a dev dashboard is running, so a stray call costs nothing in production.
func Live ¶
Live returns the handler of one Live page.
The view renders with the app's asset resolver and image service, so crest.AssetURL and <f:img> work in Mount, actions, and re-renders.
The page reports to the WithObservability provider of the app whose router serves it. A live.WithObserver in opts replaces that.
func MountAdmin ¶ added in v0.2.0
func MountAdmin(a *App, panels ...AdminPanel) error
MountAdmin mounts admin panels on the app. Each panel takes the app's Nock database, audit recorder, authenticator, Alpine bundle, job queue, storage, image service, and pub/sub broker unless it was given its own, and is served under its Path. A panel's Live sessions join the app's, so logout eviction (App.EvictLiveBinding) and graceful shutdown reach them. Configuration errors of every panel are returned together, before anything is mounted. A panel at "/" is refused, since it would cover the app's own routes; serve it on a host of its own with MountAdminHost. So is a panel under /healthz, /readyz, /metrics, /assets, or /_fletch.
func MountAdminHost ¶ added in v0.3.0
func MountAdminHost(a *App, host string, panels ...AdminPanel) error
MountAdminHost mounts admin panels as MountAdmin does, but only for requests whose host matches host, a pattern router.Host accepts such as "admin.platform.com". Other hosts do not reach the panels. The Alpine bundle and other infrastructure routes stay host-agnostic, so they reach the panel's host through host fallthrough (router.WithHostFallthrough). An invalid host pattern is returned as an error and nothing is mounted.
A panel with sight.WithPath("/") serves the host's root: its overview at "/", its resources at /<slug>. It is mounted under its MountPrefixes rather than as a catch-all, so /healthz, /readyz, /metrics, /assets, /_fletch, and the app's other routes still reach the host; a resource whose slug would take one of those paths is an error.
func MountLive ¶
MountLive registers a Live page on r as a named GET route of kind "live", plus an unnamed POST on the same path for the SSE+POST transport's join and events. The page's WebSocket attaches to the GET. With WithStaticFrontend the page also answers at LivePrefix+path.
func ObserveCache ¶ added in v0.3.0
ObserveCache wraps c so its gets (hit or miss), sets, and deletes show in the dev dashboard, tied to the request whose context they carry. The wrapper keeps cache.Appender when c has it. The app's default cache is already observed; wrap one given to WithCache to see it too. It does nothing extra unless a dev dashboard is running.
func ObserveTransport ¶ added in v0.3.0
func ObserveTransport(rt http.RoundTripper) http.RoundTripper
ObserveTransport wraps rt, or http.DefaultTransport when rt is nil, so every outbound request shows in the dev dashboard's request timeline, tied to the request whose context it carries. The time is to the response headers. Query values that carry credentials are redacted. It does nothing extra unless a dev dashboard is running.
func Pool ¶
Pool returns the pool given to WithPgxPool as a T, such as *pgxpool.Pool or *postgres.Pool, for the app serving ctx. A wrapper whose Pool() method returns a T works too. ok is false without a pool of that type.
func ReadDB ¶
ReadDB returns the read replica of the app serving ctx (the Replica of WithPgxPool), or its primary database when it has none.
func Recover ¶
Recover turns a panic in a handler into a 500 with a fixed body. The panic and its stack go to the log with the request ID, never to the client. http.ErrAbortHandler passes through, as net/http expects. An App built with WithRedactedPanics logs "[redacted]" in place of the panic value.
func RequestID ¶
RequestID keeps the X-Request-ID of the request, or makes one when it is missing or not a short token, sets it on the response, and stores it in the request context for RequestIDFrom.
func RequestIDFrom ¶
RequestIDFrom returns the request ID that RequestID stored in ctx.
func Run ¶
Run serves app until SIGTERM or SIGINT and then stops it gracefully: /readyz fails at once, the deregister delay passes, the listener closes and open requests finish, Live sockets close with 1001 so clients move to another replica, streaming responses end, job workers stop claiming and drain, OnShutdown hooks run, and providers that are io.Closers close.
func SiteAssets ¶ added in v0.3.0
func SiteAssets(byHost map[string]assets.Resolver, fallback assets.Resolver) func(http.Handler) http.Handler
SiteAssets returns middleware that picks the asset resolver of each request by its host: byHost for the request host as router.NormalizeHost returns it, else fallback. The chosen resolver replaces the app's in the request context, so assets.FromContext, Crest asset() calls, and Live views mounted by the request all resolve through it. With no match and a nil fallback the request passes through unchanged.
byHost keys are normalized once, so "Brand-A.com" and "brand-a.com:443" both match host brand-a.com. SiteAssets only resolves names; serve each resolver's files on its host, as in app.Router().Host("brand-a.com").Mount("/assets/", resA.Handler()). It panics on an invalid host key, on two keys that normalize to the same host, and on a nil resolver in byHost.
func StaticOrigin ¶ added in v0.4.0
StaticOrigin reports whether origin is one of the WithStaticFrontend origins of the app serving r. Its signature fits auth.OriginProtectionFunc.
Types ¶
type AdminHost ¶ added in v0.2.0
type AdminHost = interface {
NockDB() nock.DB
AuditRecorder() audit.Recorder
Authenticator() auth.Authenticator
AlpineBundle() *alpine.Bundle
Queue() quiver.Queue
Store() storage.Store
ImageService() images.Service
Broker() pubsub.Broker
}
AdminHost is what MountAdmin hands a panel. sight.Host, from github.com/fletchhq/sight, is the same interface literal, so the two types are identical without either module importing the other.
type AdminPanel ¶ added in v0.2.0
AdminPanel is satisfied by *sight.Panel from github.com/fletchhq/sight.
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is a configured Fletch application.
func AppFrom ¶
AppFrom returns the App running the command whose context is ctx, or nil. A command run by RunCLI also reaches the app's database with DB(ctx).
func (*App) Commands ¶
Commands returns the app's command line: the built-in serve, migrate, work, jobs, and routes, then the app's own commands.
func (*App) ConfigReport ¶
ConfigReport returns the redacted report given to WithConfigReport, or nil.
func (*App) Contract ¶ added in v0.4.0
Contract returns the app's contract with its static frontends.
func (*App) EvictLiveBinding ¶
EvictLiveBinding ends the Live sessions bound to key on every Live page the app serves (see live.Handler.EvictBinding) and returns how many it ended. SessionCookies from App.SessionCookie call it for every session they log out or revoke.
func (*App) GateObserver ¶ added in v0.3.0
func (a *App) GateObserver() DecisionObserver
GateObserver returns a DecisionObserver that logs every decision in the dev dashboard, tied to its request, while one is running.
func (*App) HandleInspectFlag ¶
HandleInspectFlag answers --fletch-inspect [section] (or --fletch-inspect=section) in args by writing the inspect document as JSON to w, and reports whether it did. A main function calls it before starting the server, so an agent can read the app's configuration without running it. Without a section it prints the whole report.
func (*App) Handler ¶
Handler returns the app's HTTP handler: the router behind the health endpoints, trace propagation, and the tracking that lets a graceful stop end streaming responses.
func (*App) InlineFast ¶ added in v0.3.0
func (a *App) InlineFast(x *httpengine.Context) bool
InlineFast reports whether ServeFast serves x with a typed route registered through router.Router.Inline, so an httpengine event loop can serve it on the loop itself. It makes the app an httpengine.InlineHandler.
func (*App) Inspect ¶
func (a *App) Inspect() ax.InspectReport
Inspect returns the fletch ax inspect document.
func (*App) JobObserver ¶ added in v0.3.0
JobObserver returns a quiver.Observer that shows enqueued jobs in the dev dashboard's request timeline and keeps the run history of schedules, for a queue the app does not build itself (pass it with quiver.WithObserver). The app's default queue already has it.
func (*App) ListenAndServe ¶
ListenAndServe serves the app on addr and runs its background work (see Start) until ctx is done. It then stops gracefully, as Run does, within 10 seconds, without closing the app's providers.
func (*App) Main ¶
Main runs the process's command line with RunCLI, prints any error, and exits with the command's exit code: 2 for a bad command line, the code of a cli.ExitError, 1 for any other error. SIGINT and SIGTERM cancel ctx.
func (*App) Mount ¶
Mount registers modules in order. A module whose name is empty or already mounted is an error, and so is any error from its Register; Mount stops at the first one.
func (*App) NockObserver ¶
func (a *App) NockObserver() nock.QueryObserver
NockObserver returns an observer that sends statements to the dev dashboard while one is running, for a Nock database the app does not pass to WithNock (nock.WithObserver, nock/postgres.WithObserver).
func (*App) OnShutdown ¶
OnShutdown adds a function that a graceful stop runs, in order, after requests and jobs have drained and before providers are closed. Its context ends with the shutdown grace period.
func (*App) OnStart ¶
OnStart adds a function that Start runs, in order, before the job workers start and the server accepts requests. An error stops the start.
func (*App) PubSubBus ¶
PubSubBus returns the Bus around the pub/sub Broker, for observers such as the dev dashboard.
func (*App) Registry ¶
Registry collects the app's routes, subsystems, assets, images, and elements for AX.
func (*App) Router ¶
Router returns the app's router, with the routes from WithRoutes, the asset handler mounted at /assets/, and the Live runtime.
func (*App) RunCLI ¶
RunCLI runs the command that args name, with the process's standard streams. With no command, or a leading flag, it runs serve. It also answers help, --fletch-inspect (see HandleInspectFlag), and --fletch-commands --json, the command manifest the fletch CLI reads.
func (*App) ServeFast ¶
func (a *App) ServeFast(x *httpengine.Context) bool
ServeFast serves x without building an *http.Request when its route is a typed route whose only middleware is the app's default (request ID, panic recovery, request context): the router's ServeFast, with the default middleware's work done here instead. It returns false, having done nothing, for every other request, which the caller then serves with Handler(). An app with an Observability middleware never serves fast. It makes the app an httpengine.FastHandler for a server of your own.
func (*App) ServeOpenAPI ¶
ServeOpenAPI serves spec at GET path, with an ETag so clients revalidate cheaply. Call it before the app serves its first request.
func (*App) SessionCookie ¶
func (a *App) SessionCookie(secret []byte, opts ...auth.CookieOption) (*auth.SessionCookie, error)
SessionCookie returns a SessionCookie over the app's session store that shares the app's clock. Options given to it override that default.
Sessions it logs out or revokes are evicted from every Live page of the app (see live.Handler.EvictBinding) when those pages bind sessions with the cookie's BindingKey.
func (*App) Sessions ¶
func (a *App) Sessions() auth.SessionStore
Sessions returns the session store.
func (*App) Start ¶
Start runs the app's background work until ctx is done: the job queue's workers (Quiver().Run), unless WithoutQueueWorker, and the pub/sub outbox relay when the Bus has one. It returns at once with a channel that is closed once that work has stopped, after in-flight jobs finish. An App starts once; a second call is an error.
func (*App) StorageManager ¶
StorageManager returns the disks given with WithStorageManager. An app given only WithStorage gets a one-disk manager named "default" around that store; an app given neither gets nil.
type Contract ¶ added in v0.4.0
type Contract struct {
Proto int `json:"proto"`
Build string `json:"build"`
Fletch string `json:"fletch"`
Live []ContractLive `json:"live"`
Transports []string `json:"transports"`
Credentials bool `json:"credentials"`
}
Contract is what ContractPath serves: what a static site needs to know the backend can serve the shells it exported.
type ContractLive ¶ added in v0.4.0
type ContractLive struct {
Name string `json:"name"`
Path string `json:"path"`
FP string `json:"fp,omitempty"`
}
ContractLive is one Live page in the Contract. FP is its root template fingerprint, which a shell exported from the same build carries.
type DecisionObserver ¶ added in v0.3.0
type DecisionObserver interface {
ObserveDecision(ctx context.Context, subject, action, resource string, allowed bool, reason string)
}
DecisionObserver sees access decisions. auth/rbac's Policy.Observe takes it: policy.Observe(app.GateObserver()).
type DevDashboard ¶
type DevDashboard struct {
// Addr is the loopback address to listen on. When it is busy the next
// free port is used. Default: 127.0.0.1 on the app's port plus 1000.
// The serve command's --dashboard-addr and FLETCH_DASHBOARD_ADDR
// override it.
Addr string
// Disabled turns the dashboard off, like --no-dashboard.
Disabled bool
// Panels are shown after the built-in ones.
Panels []DevPanel
// SlowQuery is the time at or above which a statement is flagged slow
// in the Queries panel and request timelines. Default: 100ms.
SlowQuery time.Duration
}
DevDashboard configures the development dashboard: a local web UI with the app's routes, recent requests, jobs, sent mail, and commands. It runs only in dev mode (serve --dev, fletch dev, or FLETCH_DEV=1), on its own loopback port, never in production.
type DevPanel ¶
type DevPanel struct {
// ID is the panel's URL name: lower-case letters, digits, and '-'.
ID string
Title string
Data func(r *http.Request) (any, error)
// Action, when set, handles POST /api/<ID>/action from the panel's
// buttons, behind the dashboard's CSRF and same-origin checks.
Action func(r *http.Request) (any, error)
}
DevPanel is one panel of the dev dashboard. Its data is served as JSON at /api/<ID> and refreshed live; a list of objects is shown as a table, any other value as JSON. The panel with ID "ai" is drawn by the AI renderer (runs, steps, tokens, tool I/O, approvals), fed by ai/airec.
type JobsResult ¶
type JobsResult struct {
Provider string `json:"provider"`
Settings map[string]string `json:"settings,omitempty"`
Summary *JobsSummary `json:"summary"`
}
JobsResult is the answer of the jobs tool. Summary is nil when the queue provider cannot be summarized.
type JobsSummary ¶
type JobsSummary struct {
Pending int `json:"pending"`
Delayed int `json:"delayed"`
Dead int `json:"dead"`
Schedules []ScheduleStatus `json:"schedules"`
}
JobsSummary counts the jobs of a database-backed queue. Delayed jobs include jobs in flight, whose visibility the worker has pushed out.
type LiveSessionInfo ¶
type LiveSessionInfo struct {
ID string `json:"id"`
Path string `json:"path"`
View string `json:"view"`
Mounted string `json:"mounted"`
// State is the view's exported fields after its last render. Fields
// tagged fletch:"phi" read "[redacted]"; unexported ones are left out.
State map[string]any `json:"state,omitempty"`
// contains filtered or unexported fields
}
LiveSessionInfo is one mounted Live view in the live_state answer.
type Module ¶
Module is a self-contained slice of an app, such as modules/billing: it registers its routes, jobs, and subscriptions on the app in Register.
type NockDB ¶
NockDB is a Nock database: a *nock.Database, or a driver's database that embeds one (nock/postgres.DB, nock/sqlite.DB).
type Observability ¶
type Observability interface {
RouterObserver() router.Observer
LiveObserver() live.Observer
QuiverObserver() quiver.Observer
// MetricsHandler serves the metrics at MetricsPath.
MetricsHandler() http.Handler
// MetricsPath is where the app mounts MetricsHandler, or "" for
// nowhere.
MetricsPath() string
// Describe reports the provider for fletch ax inspect, with secrets
// already redacted.
Describe() (provider string, settings map[string]string)
}
Observability is a tracing and metrics provider, such as the one in github.com/fletchhq/fletch/obs. Its methods use only types of the standard library and the leaf modules, so fletch itself does not depend on OpenTelemetry or Prometheus.
type Option ¶
type Option func(*App)
Option configures New.
func WithAllowMemoryQueue ¶
func WithAllowMemoryQueue() Option
WithAllowMemoryQueue lets an app on Postgres run without WithQuiver, its jobs in process memory, outside dev mode. Without it Start refuses, since a restart or a second replica would lose or never see the jobs.
func WithAlpine ¶
WithAlpine serves Alpine.js and the $fletch Live bridge under alpine.Prefix, renders <f:alpine /> (register alpine.Element() from elements/alpine in fletch.plugins.go) with the request's CSP nonce, and writes signal names on Live roots for $fletch.signal. The default build is @alpinejs/csp; alpine.Standard() opts in to the standard build, which needs 'unsafe-eval'. An app without WithAlpine serves and links none of it.
func WithAssets ¶
WithAssets sets the asset Resolver. Default: an empty manifest.
func WithAudit ¶
WithAudit records every request to a typed route that runs an Authorize (not router.Public) in rec: action "route.<name>" (or the method and pattern of an unnamed route), the path as the resource, the caller as the actor, and outcome denied for 401 and 403, failure for 5xx, and success otherwise. rec is also put in every request's context, so handlers call audit.Record for their own events. Without it nothing is recorded and nothing is added to requests.
func WithAuth ¶
func WithAuth(au auth.Authenticator) Option
WithAuth sets the Authenticator. Default: every request is unauthenticated.
func WithClock ¶
WithClock sets the clock of the app. The default session store, the default job queue, and App.SessionCookie read it, so a session's expiry in the store and in its cookie never disagree and delayed jobs and schedules run on the same time as the app. App.Clock hands it to anything else that needs the same time (live.WithClock, a queue given to WithQuiver). A store, cookie, or queue you build yourself reads its own clock: give it the same one (auth.WithClock, auth.WithCookieClock, quiver.WithClock) or sessions can look expired right after login.
func WithCommands ¶
WithCommands adds commands to the app's command line (see RunCLI). A command named like a built-in one replaces it.
func WithConfigReport ¶
WithConfigReport keeps a redacted copy of r, the provenance report of config.LoadWithReport, for tools such as the dev dashboard and AX.
func WithDB ¶
WithDB sets the application database. Handlers and Live sessions reach it with DB(ctx). When no queue or session store is given, a SQLite database also backs them: a quiver/sqlite queue and database-backed sessions.
func WithDevDashboard ¶
func WithDevDashboard(d DevDashboard) Option
WithDevDashboard configures the development dashboard.
func WithElements ¶
func WithElements(ps ...plugin.ElementPlugin) Option
WithElements reports Crest element plugins in fletch ax inspect. The compiler itself gets its plugins from fletch.plugins.go.
func WithFastServer ¶
func WithFastServer(opts ...httpengine.Option) Option
WithFastServer serves the app with httpengine instead of net/http's server: HTTP/1.1 with pipelined batches answered in one write, epoll or kqueue event loops on Linux and macOS, and HTTP/2 over TLS and h2c. Typed routes whose only middleware is the app's default run without an *http.Request (see App.ServeFast); every other request, such as Live, SSE, forms, sessions, mounts, or a route with its own middleware, goes through httpengine's net/http adapter unchanged. opts configure the server; the app sets its handlers. In dev mode every request takes the adapter, so the request log and dashboard see it.
func WithHealthPaths ¶
WithHealthPaths moves the built-in liveness and readiness endpoints. An empty path turns that one off. Default /healthz and /readyz.
func WithImageOptions ¶
WithImageOptions configures the default image Service, such as images.WithPresets and images.WithAuthorizer, on top of its storage wiring. They can override that wiring. It has no effect when WithImages is given.
func WithImages ¶
WithImages sets the image Service. Default: images.New() reading stored images from the app's storage (see WithStorage). A service given here replaces that wiring.
func WithMailer ¶
WithMailer sets the Mailer. Default: an in-process outbox that sends nothing.
func WithMigrations ¶
WithMigrations sets the migrations the app's db and migrate commands apply, usually an embed.FS of database/migrations, so a deployed binary migrates without the source tree. Default: the database/migrations directory.
func WithNock ¶
WithNock sets the app's Nock database. Its *sql.DB becomes the app's database (see WithDB) unless WithDB is given too, its statements show in the dev dashboard's Queries panel, and the app's command line gets db migrate|rollback|status|fresh|seed.
func WithObservability ¶
func WithObservability(o Observability) Option
WithObservability traces and measures the app with o: every request the router serves, every Live page made with Live or MountLive, and the default queue. A queue given to WithQuiver needs quiver.WithObserver(o.QuiverObserver()), and the database given to WithDB needs data.OpenObserved or data.ObserveConnector, since both are built before the app.
func WithOpenAPI ¶
WithOpenAPI serves spec, an OpenAPI document such as the one fletch gen openapi writes, at GET /openapi.json. Use ServeOpenAPI for another path.
func WithPgxPool ¶
WithPgxPool sets the app's Postgres pool: a *pgxpool.Pool, a data/postgres.Pool, or a nock/postgres.DB. Handlers reach it with Pool. When it has a database/sql view (StdDB, or an embedded *sql.DB) and WithDB is not given, that view becomes the app's database; a Replica() *sql.DB becomes what ReadDB returns. /readyz pings it.
func WithPinger ¶
WithPinger adds a named check to /readyz.
func WithPubSub ¶
WithPubSub sets the pub/sub Broker. Default: in process. The App wraps it in a pubsub.Bus unless it is one, so pass a Bus to add middleware, observers, or an outbox.
func WithQuiver ¶
WithQuiver sets the job queue. Default: an in-process queue, or quiver/sqlite over the WithDB database when it is SQLite.
func WithRedactedPanics ¶
func WithRedactedPanics() Option
WithRedactedPanics makes the app's panic recovery log "[redacted]" in place of the panic value, which can carry request data such as PHI. The stack, route, and request ID are still logged.
func WithRouterOptions ¶
WithRouterOptions passes options to the app's router: router.MapError, router.WithErrorMapper, router.WithErrorPage, router.WithErrorReporter. It may be given more than once; the options apply in order, after the defaults, so a router.WithErrorReporter here replaces the default one that logs 5xx errors.
func WithRoutes ¶
WithRoutes registers routes on the app's router. It may be given more than once; the functions run in order.
func WithSeeders ¶
WithSeeders sets what the app's db seed command runs, in order.
func WithSessions ¶
func WithSessions(s auth.SessionStore) Option
WithSessions sets the session store. Default: in process, or the WithDB database.
func WithStaticFrontend ¶ added in v0.4.0
func WithStaticFrontend(sf StaticFrontend) Option
WithStaticFrontend serves the app's Live pages to static sites on other origins. Every page mounted with MountLive also answers at LivePrefix+path behind the page's own middleware, Live endpoints and ContractPath answer CORS for Origins, and CSRF from fletch.CSRF accepts requests there by Origin instead of by token. Routes the sites call that sit behind auth.OriginProtection need its trust as well: pass StaticOrigin to auth.OriginProtectionFunc.
func WithStorage ¶
WithStorage sets the upload store. Default: disk under data/uploads. The default image Service reads images.Stored refs from it, and keeps variants in memory when the store is in memory. Stored refs still need an images.Authorizer, so an app that renders them passes its own WithImages.
func WithStorageManager ¶
WithStorageManager sets named storage disks. Without WithStorage, the manager's default disk is also the upload store that Storage returns.
func WithoutHealthChecks ¶
func WithoutHealthChecks() Option
WithoutHealthChecks turns off the built-in /healthz and /readyz.
func WithoutQueueWorker ¶
func WithoutQueueWorker() Option
WithoutQueueWorker keeps Start and ListenAndServe from running the job queue's workers, for a web process whose jobs run elsewhere or a main that calls Quiver().Run itself.
type Pinger ¶
Pinger is implemented by providers that can check their backend: a database, a pool, a queue, a broker, a cache, a session store. /readyz pings every provider that implements it, or PingContext as *sql.DB does.
type QueryResult ¶
type QueryResult struct {
Columns []string `json:"columns"`
Rows [][]any `json:"rows"`
Truncated bool `json:"truncated"`
ReadOnly bool `json:"read_only"`
}
QueryResult is the answer of the query tool.
type RunOption ¶
type RunOption func(*runConfig)
RunOption configures Run.
func WithAddr ¶
WithAddr sets the listen address of Run. Default: $FLETCH_ADDR, then :$PORT, then :8080.
func WithDeregisterDelay ¶
WithDeregisterDelay keeps serving for d after SIGTERM with /readyz already failing, so a load balancer stops routing to the replica before it stops accepting. Match it to the target group's health check. Default 0, or $FLETCH_DEREGISTER_DELAY.
func WithShutdownGrace ¶
WithShutdownGrace sets how long a stop may take, from SIGTERM to exit, after the deregister delay. Keep it under the orchestrator's kill timeout (ECS stopTimeout, up to 120s). Default 10s, or $FLETCH_SHUTDOWN_GRACE.
type ScheduleStatus ¶
type ScheduleStatus struct {
Name string `json:"name"`
Spec string `json:"spec"`
NextRun string `json:"next_run"`
}
ScheduleStatus is one periodic job and its next run.
type StaticFrontend ¶ added in v0.4.0
type StaticFrontend struct {
// Origins are the sites' origins: exact ("https://example.com") or a
// leading-label wildcard ("https://*.example.pages.dev"), which matches
// subdomains only. The scheme must match. $FLETCH_STATIC_ORIGINS adds
// more, comma-separated.
Origins []string
// Credentials lets the sites' Live and backend requests carry the
// user's cookies. Lax cookies reach the backend only from the same site.
Credentials bool
// Forms are path globs ("/contact", "/app/*") whose POSTs the sites
// send cross-origin; they get the Live endpoints' CSRF rule.
Forms []string
}
StaticFrontend describes the static sites that front this backend.
Source Files
¶
- adminmount.go
- alpine.go
- appcli.go
- audit.go
- banner.go
- config.go
- database.go
- dbcli.go
- defaults.go
- devax.go
- devdash.go
- devdash_cmd.go
- devdash_config.go
- devdash_db.go
- devdash_dump.go
- devdash_events.go
- devdash_jobs.go
- devdash_logs.go
- devdash_mail.go
- devdash_static.go
- devdash_storage.go
- devdash_telemetry.go
- devhttps.go
- fastserver.go
- fletch.go
- jobscli.go
- lifecycle.go
- livereg.go
- openapi.go
- reqstate.go
- siteassets.go
- staticfrontend.go
- subsystems.go
Directories
¶
| Path | Synopsis |
|---|---|
|
admin
module
|
|
|
alpine
module
|
|
|
assets
module
|
|
|
pipeline
module
|
|
|
audit
module
|
|
|
postgres
module
|
|
|
auth
module
|
|
|
apikey
module
|
|
|
dbcheck
module
|
|
|
jwt
module
|
|
|
oauth
module
|
|
|
oidc
module
|
|
|
passkey
module
|
|
|
rbac
module
|
|
|
redis
module
|
|
|
totp
module
|
|
|
ax
module
|
|
|
cache
module
|
|
|
postgres
module
|
|
|
redis
module
|
|
|
sqlitecheck
module
|
|
|
cli
module
|
|
|
cmd
|
|
|
fletch
command
Command fletch is the Fletch CLI.
|
Command fletch is the Fletch CLI. |
|
fletchbuild
Package fletchbuild is the main function of an app's Crest compiler.
|
Package fletchbuild is the main function of an app's Crest compiler. |
|
config
module
|
|
|
aws
module
|
|
|
crest
module
|
|
|
tools
module
|
|
|
data
module
|
|
|
postgres
module
|
|
|
sqlite
module
|
|
|
Package devtls is Fletch's local HTTPS for development: a local root CA and leaf certificates minted on demand, OS trust-store setup, a loopback DNS responder for a development TLD, a registry of linked sites, and an HTTPS reverse proxy in front of them.
|
Package devtls is Fletch's local HTTPS for development: a local root CA and leaf certificates minted on demand, OS trust-store setup, a loopback DNS responder for a development TLD, a registry of linked sites, and an HTTPS reverse proxy in front of them. |
|
Package docs holds Fletch's framework docs.
|
Package docs holds Fletch's framework docs. |
|
elements
|
|
|
alpine
Package alpine is the built-in <f:alpine /> Crest element.
|
Package alpine is the built-in <f:alpine /> Crest element. |
|
alpine/rt
Package alpinert renders <f:alpine /> at request time.
|
Package alpinert renders <f:alpine /> at request time. |
|
csrf
Package csrf is the built-in <f:csrf /> Crest element.
|
Package csrf is the built-in <f:csrf /> Crest element. |
|
csrf/rt
Package csrfrt renders <f:csrf /> at request time.
|
Package csrfrt renders <f:csrf /> at request time. |
|
icon
Package icon is the built-in <f:icon> Crest element.
|
Package icon is the built-in <f:icon> Crest element. |
|
icon/iconset
Package iconset renders <f:icon> SVGs.
|
Package iconset renders <f:icon> SVGs. |
|
img
Package img is the built-in <f:img> Crest element.
|
Package img is the built-in <f:img> Crest element. |
|
img/rt
Package rt renders <f:img> elements whose attributes are only known at render time.
|
Package rt renders <f:img> elements whose attributes are only known at render time. |
|
markdown
Package markdown is the built-in <f:markdown> Crest element.
|
Package markdown is the built-in <f:markdown> Crest element. |
|
httpengine
module
|
|
|
images
module
|
|
|
prewarm
module
|
|
|
vips
module
|
|
|
live
module
|
|
|
wasm
module
|
|
|
mail
module
|
|
|
postmark
module
|
|
|
resend
module
|
|
|
ses
module
|
|
|
nock
module
|
|
|
postgres
module
|
|
|
sqlite
module
|
|
|
obs
module
|
|
|
pdf
module
|
|
|
pubsub
module
|
|
|
nats
module
|
|
|
pgnotify
module
|
|
|
postgres
module
|
|
|
redis
module
|
|
|
sns
module
|
|
|
quiver
module
|
|
|
goqite
module
|
|
|
postgres
module
|
|
|
sqlite
module
|
|
|
sqs
module
|
|
|
router
module
|
|
|
ratelimit/postgres
module
|
|
|
ratelimit/redis
module
|
|
|
Package skills holds Fletch's agent skills as Markdown.
|
Package skills holds Fletch's agent skills as Markdown. |
|
storage
module
|
|
|
blob
module
|
|
|
s3
module
|
|
|
variants
module
|
|
|
testkit
module
|