Documentation
¶
Overview ¶
Package app bootstraps Hyrule services: configuration, database connections, authentication, REST resources, health endpoints and graceful shutdown.
Describe a service with Spec and register resources in its Setup function. Main owns process signals and exits on failure; Run accepts a caller-owned context. Build returns an http.Handler using caller-owned dependencies, suitable for tests or composition with an existing HTTP router.
MongoDB is the default backend. Spec.Backend can select Postgres or the experimental local SQLite backend. See the examples for complete programs. Some HTTP response conventions preserve compatibility with Eve, the Python REST framework from which Hyrule migrated; Werkzeug is its HTTP utility library.
Index ¶
- func AuthenticatorFromConfig(cfg config.Config) (*auth.Authenticator, error)
- func Build(ctx context.Context, spec Spec, deps Deps) (http.Handler, error)
- func DryRun() (bool, error)
- func DryRunTimeout() (time.Duration, error)
- func ElasticsearchCheck(name string, c interface{ ... }) health.Checker
- func Main(spec Spec)
- func Run(ctx context.Context, spec Spec) error
- func WarnEmbedded(next http.Handler) http.Handler
- type Backend
- type Deps
- type Env
- type Spec
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuthenticatorFromConfig ¶
func AuthenticatorFromConfig(cfg config.Config) (*auth.Authenticator, error)
AuthenticatorFromConfig reads the keys of auth_settings.py and azure_settings.py.
func Build ¶
Build wires the service and returns its HTTP handler.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/Gui-Rondon/hyrule/app"
"github.com/Gui-Rondon/hyrule/platform/config"
"github.com/Gui-Rondon/hyrule/platform/sqlite"
"github.com/Gui-Rondon/hyrule/rest"
"github.com/Gui-Rondon/hyrule/restsqlite"
)
func main() {
ctx := context.Background()
db, err := sqlite.Open(ctx, ":memory:")
if err != nil {
panic(err)
}
defer db.Close()
spec := app.Spec{Name: "example", Backend: app.BackendSQLite, Setup: func(ctx context.Context, env *app.Env) error {
resource := &rest.Resource{Name: "products", Schema: rest.Schema{"name": {Type: rest.TypeString, Required: true}}}
adapter, err := restsqlite.NewAdapter(ctx, env.SQLite, "products", resource)
if err != nil {
return err
}
resource.Adapter = adapter
env.API.Register(resource)
return nil
}}
handler, err := app.Build(ctx, spec, app.Deps{SQLite: db, Config: config.Config{"auth": map[string]any{"enable": false}}})
if err != nil {
panic(err)
}
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/products", nil))
fmt.Println(response.Code)
}
Output: 200
func DryRun ¶
DryRun tells whether the service runs in dry run, from the DRY_RUN variable of the Deployment. An unknown value is an error, so a typo never turns the writes on.
func DryRunTimeout ¶
DryRunTimeout is the limit of each request in dry run, from the DRY_RUN_TIMEOUT variable (a Go duration, e.g. 20s); 0 when not set. Raising it is useful to measure slow reads, at the cost of holding the client's next request longer.
func ElasticsearchCheck ¶
func ElasticsearchCheck(name string, c interface { Check(ctx context.Context) (bool, string) }) health.Checker
ElasticsearchCheck is the Elasticsearch checker of the Eve APIs; name is the Python function name shown in /healthcheck ("elasticsearch_check" in tags-api, "elasticearch_healthcheck" in the Eve-Elastic APIs).
func Run ¶
Run loads the configuration (CONFIG_FILE or properties-api), connects to the database (Spec.Backend) and serves until ctx is done.
Types ¶
type Backend ¶ added in v0.102.0
type Backend string
Backend selects which database a Spec's Env wires up. The zero value, BackendMongo, keeps every existing service (which never sets this field) exactly as it behaved before Backend existed.
const ( // BackendMongo wires Env.DB/mongodb.Connect, as every service did // before Backend existed -- also the zero value, so an unset // [Spec.Backend] means this. BackendMongo Backend = "" // BackendPostgres wires Env.Postgres/platform/postgres.Connect // instead. Dry run is implemented via postgres.Transactor.Rollback // -- no WriteGuard-equivalent exists (or is needed): every // production write already goes through Store.Querier(ctx), which // only ever runs inside the ambient transaction Rollback discards. BackendPostgres Backend = "postgres" // BackendSQLite is experimental local storage; no dry run or outbox. BackendSQLite Backend = "sqlite" )
type Deps ¶
type Deps struct {
// SQLite is caller-owned; Build never closes it.
SQLite *sql.DB
Config config.Config
// Mongo/DB are for BackendMongo; Run connects them via mongodb.Connect.
Mongo *mongo.Client
// DB overrides the database from the configuration (tests).
DB *mongo.Database
// Postgres is the pool for BackendPostgres; Run connects it via
// platform/postgres.Connect.
Postgres *pgxpool.Pool
// Auth overrides the authenticator from the configuration (tests).
Auth *auth.Authenticator
// Start runs the tasks registered with Env.Go; nil skips them.
Start func(name string, task func(ctx context.Context) error)
// DryRun runs the service in dry run; Run sets it from DRY_RUN.
DryRun bool
// DryRunTimeout limits each request in dry run; Run sets it from
// DRY_RUN_TIMEOUT, and 0 means defaultDryRunTimeout.
DryRunTimeout time.Duration
// WriteGuard watches the commands of Mongo in dry run; a write outside a
// transaction fails /healthcheck. Required in dry run.
WriteGuard *mongodb.WriteGuard
}
Deps are the external dependencies of Build.
type Env ¶
type Env struct {
// SQLite is set only for BackendSQLite.
SQLite *sql.DB
SQLiteTx sqlite.Transactor
Config config.Config
// DB is set only for [BackendMongo].
DB *mongo.Database
// Postgres is set only for [BackendPostgres].
Postgres *pgxpool.Pool
// PostgresTx is the Transactor already wired into API's Options --
// a BackendPostgres Setup passes this same value to
// restpostgres.NewAdapter, so a resource's own transaction (e.g. an
// optimistic-concurrency retry) joins the same Rollback/pool
// configuration as the request-level one, instead of a second,
// independently-constructed Transactor silently diverging from it.
// Zero value for BackendMongo.
PostgresTx postgres.Transactor
API *rest.API
Info health.Info
// DryRun: the writes are rolled back, the post-write hooks and the
// background tasks do not run. A service whose routes have other
// effects refuses them with RefuseInDryRun.
DryRun bool
// contains filtered or unexported fields
}
Env is what Setup receives.
func (*Env) Go ¶
Go runs a task while Run serves, such as a worker publishing persisted events. Run cancels its context and waits for it before closing the database. Build does not start tasks unless Deps.Start is supplied. Dry run skips tasks because publishing events or updating worker leases would cause writes.
func (*Env) RefuseInDryRun ¶
RefuseInDryRun answers 503 with the reason in dry run, for a route whose effects are outside Mongo and cannot be rolled back (e.g. a call to another service). Without dry run it returns h.
func (*Env) Store ¶
Store builds the rest.Store of a collection, for Setup to assign to rest.Resource.Store. DB stays available directly for anything that needs the raw *mongo.Database (health checks, indexes, a custom query). BackendMongo only -- a BackendPostgres Setup builds postgres.NewStore(e.Postgres, table) directly and assigns it to rest.Resource.Adapter via restpostgres.NewAdapter, since platform/postgres.Store does not implement rest.Store. For local experiments use Env.SQLite instead.
type Spec ¶
type Spec struct {
// Name is the APP_NAME in properties-api, e.g. "tags-api".
Name string
// Backend selects MongoDB (default), Postgres, or experimental SQLite.
// See [BackendMongo], [BackendPostgres] and [BackendSQLite].
Backend Backend
// DefaultDB is used when building a URI from individual connection settings.
// Mongo also falls back to it for a URI without a database. Specify the
// database explicitly in Postgres URIs (pgx otherwise resolves its default).
DefaultDB string
Version string
// Setup registers the resources, custom endpoints and checkers.
Setup func(ctx context.Context, env *Env) error
// Messages selects legacy Python HTTP error wording. Nil uses
// [rest.Werkzeug1]; [rest.Werkzeug0] preserves older client expectations.
Messages rest.Messages
// HTMLForbidden is rest.Options.HTMLForbidden (Eve 0.7 without 403
// in STANDARD_ERRORS).
HTMLForbidden bool
// CacheControl and CacheExpires are Eve's global CACHE_CONTROL and
// CACHE_EXPIRES (the home endpoint); resources set their own.
CacheControl string
CacheExpires int
// Indexes is the service's <service>.indices.conf (go:embed); config-files
// adds or replaces entries with mongo.indexes (legacy configuration compatibility). BackendMongo only.
Indexes []byte
// PostgresIndexes declares a BackendPostgres service's indexes,
// ensured at boot the same moment Indexes/mongo.indexes are for
// Mongo. Go-typed values, not text: platform/postgres.IndexSpec has
// no .indices.conf-equivalent parser to mirror mongodb.ParseIndexes
// with.
PostgresIndexes []postgres.IndexSpec
// URLPrefix is Eve's URL_PREFIX (e.g. "auth"): every route, /status and
// /healthcheck included, is served under /<prefix>, and anything else is
// a 404. Routes are registered without it, and the links leave it out,
// as Eve's resource_link does.
URLPrefix string
// NoDryRun is why the service refuses to start in dry run, when it
// cannot run without effects.
NoDryRun string
}
Spec describes a service.
Example ¶
package main
import (
"context"
"fmt"
"github.com/Gui-Rondon/hyrule/app"
"github.com/Gui-Rondon/hyrule/rest"
)
func main() {
spec := app.Spec{Name: "products", Version: "dev", Setup: func(_ context.Context, env *app.Env) error {
env.API.Register(&rest.Resource{Name: "products", Store: env.Store("products"), Schema: rest.Schema{"name": {Type: rest.TypeString, Required: true}}})
return nil
}}
// app.Main(spec) connects to MongoDB and serves until shutdown.
fmt.Println(spec.Name, spec.Version)
}
Output: products dev