fletch

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0, MIT Imports: 79 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Fletch

Fletch is an all-Go full-stack web framework. Crest (.crest files) is its HTML-first template language. Everything builds with CGO_ENABLED=0 and needs no Node.

Website: fletch.page · Documentation: fletch.page/docs

Quick start

go install github.com/fletchhq/fletch/cmd/fletch@latest
fletch new shop && cd shop     # a runnable app: modules, config, migrations, tests, AGENTS.md
go mod tidy                    # fetch Fletch modules and populate go.sum
fletch dev                     # rebuilds on save, CSS swap, error overlay, dev dashboard

When you are ready to ship a single CGO_ENABLED=0 binary (stop fletch dev first):

fletch build -o bin/shop       # fletch gen, assets, then a CGO_ENABLED=0 binary

fletch new prints the next step. go test ./... runs the scaffold's tests, fletch check reports route, template, module, and schema problems, and fletch --help lists every command.

Layout

fletch new writes a modular monolith: one directory per domain under modules/, no internal/, no cmd/<name>/.

main.go                thin entry: bootstrap.App().Main(ctx)
bootstrap/app.go       config, database, and the modules passed to app.Mount(...)
config/                typed config structs and YAML
modules/<domain>/      module.go, routes.go, handlers.go, service.go, schema.go, store.go,
                       views/*.crest, jobs.go, events.go, policy.go, *_test.go
ui/layouts/            shared page layouts (<slot:head>, <slot:scripts>)
ui/components/         shared Crest UI primitives
ui/partials/           shared app fragments: nav, header, flash
ui/emails/             Crest email templates (fletch make email); rendered with mail.RenderHTML
commands/              app commands (fletch make command)
resources/  public/    CSS and JS sources; static files
database/              migrations/ (SQL and snapshot.json), seeders/
storage/  tests/       local disk, SQLite file; app-level tests
.fletch/               caches, the scaffold manifest (never edit)

A module owns its tables and talks to other modules only through its Service and events; fletch check enforces it. See docs/modules.md.

Modules

Each subsystem is its own Go module and works without the rest:

Module What it is Fletch modules it may import
crest Template runtime, crest/ast, crest/plugin, crest/slot none
crest/tools Compiler, plugin build host, crest CLI crest
router Radix router with typed JSON routes, webhooks, secure headers, rate limits, SSE none
live Live sessions, wire protocol, browser runtime crest/slot only
nock (nock/sqlite, nock/postgres) Declarative schema DSL, offline differ, migrator, typed query builder (v1.4) none
quiver (quiver/sqlite, quiver/postgres, quiver/sqs) Job queue v2: typed jobs, unique and transactional enqueue, schedules (v1.5) none
pubsub (pubsub/postgres, pubsub/nats, pubsub/sns, pubsub/redis) Typed events, consumer groups, patterns, outbox (v1.6) none
config (config/aws) Layered typed configuration, encrypted credentials (v1.7) none
storage (storage/s3, storage/blob, storage/variants) Multi-disk object storage, signed URLs, attachments (v1.8) none
cache, mail, auth, audit, obs, pdf Cache, mail, sessions and auth, audit log, observability, PDFs none
data Read-only transactions and database helpers none
assets, assets/pipeline Asset resolver; build pipeline assets (pipeline only)
images Image service interfaces and presets none
ax Inspect registry and diagnostics none
cli Command runner for the app's own command line none
github.com/fletchhq/fletch This meta-module: fletch.New, built-in elements, the fletch CLI all of the above

depgraph_test.go enforces these rules with go list in module mode.

Ecosystem modules

Larger features live in their own repositories and build on the leaf modules above. The meta-module never requires them; fletch.MountAdmin and fletch.DevPanel take them through structural interfaces.

Module What it is Docs and skill
github.com/fletchhq/sight Sight: admin panels over Nock tables, plugins, sighttest (was fletch/admin) sight/sight, sight/plugins; skill sight
github.com/fletchhq/aikit AI SDK: providers, tools, MCP, agents, Converse bots, evals (was fletch/ai) aikit/ai, aikit/mcp, aikit/agents, aikit/converse; skills ai, mcp, agents, converse
github.com/fletchhq/domains Custom domains: normalization, cached resolver, TLS ask, DNS verification (was fletch/domains) domains/domains; skill domains
github.com/fletchhq/tally Billing: tally/stripe (was fletch/billing/stripe) tally/stripe; skill tally

Their docs and agent skills ship with each module. fletch ax sync (and fletch upgrade) discovers every github.com/fletchhq/* module in the app's go.mod, writes its skills to .agents/skills/ and lists them in AGENTS.md, and prunes them when the module goes away; fletch docs list|show|search and fletch mcp serve their docs as <module>/<topic>.

The CLI side of v1.4 to v1.8: fletch make generators, fletch db generate|migrate|rollback|status|fresh|seed, fletch gen, fletch build (generate, assets, and a CGO_ENABLED=0 compile in one step), fletch mod sync (point a local-checkout app's go.mod at every Fletch module), fletch upgrade, fletch storage, fletch jobs, and fletch config.

App

app := fletch.New(
	fletch.WithRoutes(func(r *router.Router) {
		r.Handle(http.MethodGet, "/", fletch.Live(func() live.Component { return &pages.Counter{} }))
	}),
	fletch.WithImages(images.New(images.WithPresets(presets.All...))),
)
http.ListenAndServe(":8080", app.Handler())

Every subsystem has a default that needs no external service: disk storage under data/uploads, an in-process cache, queue, session store, and pub/sub, and a mail outbox that sends nothing. Swap one with its option: WithStorage, WithCache, WithQuiver, WithSessions, WithAuth, WithPubSub, WithMailer, WithAssets, WithImages.

Configuration

github.com/fletchhq/fletch/config loads layered, typed settings into a struct: default tags, config/*.yaml (one file or one per section), config/environments/<env>.yaml, AES-256-GCM encrypted credentials (fletch credentials), .env files, providers such as AWS SSM, then the OS environment, with ${VAR:-default} interpolation and every problem reported at once. A provenance report with secrets masked feeds fletch config show, fletch config check, fletch config env-example, fletch ax inspect config, and the dev dashboard's Config panel. See docs/config.md.

Storage

github.com/fletchhq/fletch/storage is a stdlib-only object storage contract with a multi-disk Manager (fletch.WithStorageManager), optional interfaces for listing, copying, batch deletes, ranges, options, and metadata, HMAC-signed local disks with direct uploads, and Disk, Memory, and storagetest.Fake. storage/s3 adds S3, R2, MinIO, and Spaces; storage/blob adds attachments with direct uploads; storage/variants adds cached image variants. fletch storage ls|stat|put|get|rm|sign, fletch ax inspect storage, and the dev dashboard's Storage panel work on the disks in config/storage.yaml. See docs/storage.md.

Crest element plugins

List plugins in fletch.plugins.go at the app root:

//go:build fletchbuild

package main

import (
	"github.com/fletchhq/fletch/cmd/fletchbuild"
	"github.com/fletchhq/fletch/elements/icon"
)

func main() { fletchbuild.Main(fletchbuild.Elements(icon.Element())) }

Build the compiler with CGO_ENABLED=0 go build -tags fletchbuild -o .fletch/bin/compiler ./fletch.plugins.go, then run .fletch/bin/compiler describe --json or .fletch/bin/compiler compile ./....

Built-in elements use only the public crest/ast and crest/plugin API:

  • <f:icon name="lucide:check" size="16" stroke="1.75" class="..." /> inlines assets/icons/lucide/check.svg at build time. name, size, class, and stroke also take Go expressions; a dynamic name renders from the set installed with iconset.Use (see docs/crest-plugins.md).

CLI

fletch --help                  # every command; fletch <command> --help for one
fletch ax inspect --json       # subsystems, assets, images, elements
fletch inspect routes --json
fletch docs                    # list the bundled docs; fletch docs show <topic>

Development

CGO_ENABLED=0 go test -race ./... && go vet ./...    # workspace (go.work), from any module directory

Every published go.mod requires its sibling Fletch modules at the release version, with no replace, so go install ...@<version> and apps resolve the published modules. go.work points the workspace at this checkout instead. The module-graph tests (depgraph_test.go) and the API freeze check each module alone in module mode, against this checkout.

examples/, bench/techempower, auth/dbcheck, cache/sqlitecheck, and live/client/sizecheck are not published. They are outside go.work, keep local replace directives, and build with GOWORK=off as standalone consumers.

Releases tag the root module vX.Y.Z and every published submodule <dir>/vX.Y.Z; scripts/release-tags.sh lists them.

License

MIT or Apache-2.0, at your option: LICENSE-MIT, LICENSE-APACHE.

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

View Source
const ContractPath = "/_fletch/contract"

ContractPath serves the backend's contract with its static frontends.

View Source
const LivePrefix = "/_fletch/live"

LivePrefix is where WithStaticFrontend serves every Live page's endpoint: the page at /counter joins at /_fletch/live/counter.

View Source
const RequestIDHeader = "X-Request-ID"

RequestIDHeader carries the request ID on requests and responses.

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

func CSRF(secret []byte, opts ...auth.CSRFOption) (func(http.Handler) http.Handler, error)

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

func DB(ctx context.Context) *sql.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 DumpCtx

func DumpCtx(ctx context.Context, values ...any)

DumpCtx is Dump that also records the request ID of ctx.

func Live

func Live(fn func() live.Component, opts ...live.Option) http.Handler

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

func MountLive(r *router.Router, name, path string, fn func() live.Component, opts ...live.Option)

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

func ObserveCache(c cache.Cache) cache.Cache

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

func Pool[T any](ctx context.Context) (pool T, ok bool)

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

func ReadDB(ctx context.Context) *sql.DB

ReadDB returns the read replica of the app serving ctx (the Replica of WithPgxPool), or its primary database when it has none.

func Recover

func Recover(next http.Handler) http.Handler

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

func RequestID(next http.Handler) http.Handler

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

func RequestIDFrom(ctx context.Context) string

RequestIDFrom returns the request ID that RequestID stored in ctx.

func Run

func Run(a *App, opts ...RunOption) error

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

func StaticOrigin(r *http.Request, origin string) bool

StaticOrigin reports whether origin is one of the WithStaticFrontend origins of the app serving r. Its signature fits auth.OriginProtectionFunc.

func WrapHTTPClient added in v0.3.0

func WrapHTTPClient(c *http.Client) *http.Client

WrapHTTPClient returns a copy of c, or of http.DefaultClient when c is nil, whose transport is ObserveTransport of c's.

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

type AdminPanel interface {
	Path() string
	Handler() http.Handler
	Adopt(AdminHost) error
}

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

func AppFrom(ctx context.Context) *App

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 New

func New(opts ...Option) *App

New builds an App. It does no I/O: providers open connections and files on first use.

func (*App) Alpine

func (a *App) Alpine() *alpine.Bundle

Alpine returns the bundle WithAlpine configured, or nil.

func (*App) Assets

func (a *App) Assets() assets.Resolver

Assets returns the asset Resolver.

func (*App) Auth

func (a *App) Auth() auth.Authenticator

Auth returns the Authenticator.

func (*App) Cache

func (a *App) Cache() cache.Cache

Cache returns the cache.

func (*App) Clock

func (a *App) Clock() func() time.Time

Clock returns the app's clock: time.Now, or the one given to WithClock.

func (*App) Command

func (a *App) Command(cmds ...cli.Command)

Command adds commands to the app's command line, like WithCommands.

func (*App) Commands

func (a *App) Commands() []cli.Command

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

func (a *App) ConfigReport() *config.Report

ConfigReport returns the redacted report given to WithConfigReport, or nil.

func (*App) Contract added in v0.4.0

func (a *App) Contract() Contract

Contract returns the app's contract with its static frontends.

func (*App) DB

func (a *App) DB() *sql.DB

DB returns the database given to WithDB, or nil.

func (*App) EvictLiveBinding

func (a *App) EvictLiveBinding(key string) int

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

func (a *App) HandleInspectFlag(args []string, w io.Writer) bool

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

func (a *App) Handler() http.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) Images

func (a *App) Images() images.Service

Images returns the image Service.

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

func (a *App) JobObserver() quiver.Observer

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

func (a *App) ListenAndServe(ctx context.Context, addr string) error

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

func (a *App) Mailer() mail.Mailer

Mailer returns the Mailer.

func (*App) Main

func (a *App) Main(ctx context.Context)

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

func (a *App) Modules() []string

Modules returns the names of the mounted modules, in mount order.

func (*App) Mount

func (a *App) Mount(mods ...Module) error

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

func (a *App) Nock() NockDB

Nock returns the database given to WithNock, or nil.

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

func (a *App) OnShutdown(fn func(context.Context) error)

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

func (a *App) OnStart(fn func(context.Context) error)

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

func (a *App) PubSub() pubsub.Broker

PubSub returns the pub/sub Broker, a *pubsub.Bus.

func (*App) PubSubBus

func (a *App) PubSubBus() *pubsub.Bus

PubSubBus returns the Bus around the pub/sub Broker, for observers such as the dev dashboard.

func (*App) Quiver

func (a *App) Quiver() quiver.Queue

Quiver returns the job queue.

func (*App) Registry

func (a *App) Registry() *ax.Registry

Registry collects the app's routes, subsystems, assets, images, and elements for AX.

func (*App) Router

func (a *App) Router() *router.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

func (a *App) RunCLI(ctx context.Context, args []string) error

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

func (a *App) ServeOpenAPI(path string, spec []byte)

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

func (a *App) Start(ctx context.Context) (<-chan struct{}, error)

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

func (a *App) Storage() storage.Store

Storage returns the upload store.

func (*App) StorageManager

func (a *App) StorageManager() *storage.Manager

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.

func (*App) Use

func (a *App) Use(mw ...func(http.Handler) http.Handler)

Use adds middleware around every route and mount of the app, inside the built-in request ID, panic recovery, and render context. The first is the outermost. Call it before the app serves its first request.

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 Ctx

type Ctx = router.Ctx

Ctx is the per-request context of a route handler.

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 Input

type Input = router.Input

Input is the request type of a typed route.

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

type Module interface {
	Name() string
	Register(a *App) error
}

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

type NockDB interface {
	nock.DB
	StdDB() *sql.DB
	AddObserver(o nock.QueryObserver) (remove func())
}

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

func WithAlpine(opts ...alpine.Option) Option

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

func WithAssets(r assets.Resolver) Option

WithAssets sets the asset Resolver. Default: an empty manifest.

func WithAudit

func WithAudit(rec audit.Recorder) Option

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 WithCache

func WithCache(c cache.Cache) Option

WithCache sets the cache. Default: a 64 MiB in-process LRU.

func WithClock

func WithClock(now func() time.Time) Option

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

func WithCommands(cmds ...cli.Command) Option

WithCommands adds commands to the app's command line (see RunCLI). A command named like a built-in one replaces it.

func WithConfigReport

func WithConfigReport(r *config.Report) Option

WithConfigReport keeps a redacted copy of r, the provenance report of config.LoadWithReport, for tools such as the dev dashboard and AX.

func WithDB

func WithDB(db *sql.DB) Option

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

func WithHealthPaths(live, ready string) Option

WithHealthPaths moves the built-in liveness and readiness endpoints. An empty path turns that one off. Default /healthz and /readyz.

func WithImageOptions

func WithImageOptions(opts ...images.Option) Option

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

func WithImages(s images.Service) Option

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

func WithMailer(m mail.Mailer) Option

WithMailer sets the Mailer. Default: an in-process outbox that sends nothing.

func WithMigrations

func WithMigrations(fsys fs.FS) Option

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

func WithNock(db NockDB) Option

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

func WithOpenAPI(spec []byte) Option

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

func WithPgxPool(pool any) Option

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

func WithPinger(name string, p Pinger) Option

WithPinger adds a named check to /readyz.

func WithPubSub

func WithPubSub(b pubsub.Broker) Option

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

func WithQuiver(q quiver.Queue) Option

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

func WithRouterOptions(opts ...router.Option) Option

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

func WithRoutes(fn func(*router.Router)) Option

WithRoutes registers routes on the app's router. It may be given more than once; the functions run in order.

func WithSeeders

func WithSeeders(s ...migrate.Seeder) Option

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

func WithStorage(s storage.Store) Option

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

func WithStorageManager(m *storage.Manager) Option

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

type Pinger interface {
	Ping(ctx context.Context) error
}

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 Public

type Public = router.Public

Public is embedded in an Input to allow any caller.

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

func WithAddr(addr string) RunOption

WithAddr sets the listen address of Run. Default: $FLETCH_ADDR, then :$PORT, then :8080.

func WithDeregisterDelay

func WithDeregisterDelay(d time.Duration) RunOption

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

func WithShutdownGrace(d time.Duration) RunOption

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.

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

Jump to

Keyboard shortcuts

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