keel

module
v0.0.0-...-6ebc918 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0

README

keel

Pages

Reusable Go packages for building a web backend: configuration, structured logging, HTTP serving, Postgres access and migrations, search, background jobs, events and transactional email, and durable, governed AI agents: runs that survive a crash, wait for a person's approval and are held to written rules, on Postgres alone. Each package is usable on its own, and every package that talks to an external service ships an in-process default, so a project running only Postgres gets a complete backend.

Tutorial and package showcase: https://manava.github.io/keel/

Install

go get github.com/ManavA/keel

Go 1.26 or later. Docker is needed only by pg/testdb.

Quick start

A service that uses Postgres and nothing else:

package main

import (
	"context"
	"fmt"
	"log/slog"
	"os"

	"github.com/ManavA/keel/config"
	"github.com/ManavA/keel/httpx"
	"github.com/ManavA/keel/log"
	"github.com/ManavA/keel/pg"
)

type Config struct {
	Port        int    `envconfig:"PORT" default:"8080"`
	DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
}

func main() {
	slog.SetDefault(log.New(log.Options{}))

	var cfg Config
	if err := config.Load(&cfg); err != nil {
		slog.Error("load config", "error", err)
		os.Exit(1)
	}

	ctx := context.Background()
	pool, err := pg.Open(ctx, pg.Options{URL: cfg.DatabaseURL})
	if err != nil {
		slog.Error("open database", "error", err)
		os.Exit(1)
	}
	defer pool.Close()

	r := httpx.NewRouter(httpx.RouterOptions{})
	r.Mount("/", httpx.Health(httpx.HealthOptions{
		Checks: map[string]httpx.Check{"database": pg.HealthCheck(pool)},
	}))

	srv := httpx.NewServer(httpx.ServerOptions{
		Addr:    fmt.Sprintf(":%d", cfg.Port),
		Handler: r,
	})
	if err := srv.ListenAndServe(ctx); err != nil {
		slog.Error("server stopped", "error", err)
		os.Exit(1)
	}
}

examples/minimal is a runnable service built this way, with a notes API over Postgres. Run it with make run-local, or start your own from it with go run ./cmd/keel new <name>.

Packages

Package Description
config Environment loading over envconfig, optional dotenv, validation, secret trimming and redaction
log A JSON slog handler carrying request ids, with credential-shaped keys redacted
httpx HTTP server with graceful shutdown, chi router, middleware, JSON responses, health endpoints, server-sent event streams
httpx/middleware Real client address, request id, request log, panic recovery, CORS, rate limiting
httpx/buildinfo The revision the running binary was built from
pg pgx v5 pool, transaction helper, offset and keyset paging
pg/migrate Migration runner with a ledger, and a replay check
pg/testdb Docker Postgres harness for tests
search Document index over Postgres, or Meilisearch via search/meili
jobs Background work with run outcomes, an in-process scheduler, and jobs/cloudrun triggers
events Publish and subscribe in memory, or over Cloud Pub/Sub via events/pubsub
mail Transactional email over a log sender or Postmark
media Object storage and image derivatives, local filesystem or Google Cloud Storage
geocode Address to coordinate lookup with a degrade chain, Mapbox or a no-op default
perf Response caching, ETag, gzip, and singleflight middleware for HTTP handlers
auth Authentication composable across local, Firebase and generic OIDC sources; sessions, verification, password reset (auth/pg for Postgres)
admin Administrative session auth, a CORS-scoped router, and a helper for keeping admin-only fields out of public responses (admin/pg for Postgres)
textpolicy One normalize-then-match guard for generated and forwarded text, with no domain-specific rules of its own
retry Exponential backoff with full jitter, and context cancellation
idempotency HTTP middleware that replays a stored response for a repeated Idempotency-Key
flags Per-subject feature flags with percentage rollout and allowlist (flags/pg for Postgres)
outbox Writes an event with a domain transaction, then relays it to events
metrics Counters and histograms for HTTP, pool, jobs, outbox, events and geocode, with a no-op default and OTel via metrics/otel
webhooks Signed HTTP delivery of events to external URLs, over the outbox relay
notifyprefs Per-user notification opt-outs with send-path enforcement (notifyprefs/pg for Postgres)
llm One call to a language model: text, tool calls, structured replies, streaming, embeddings; wrappers for retries, fallback, budgets and metering; no provider and no price table
llm/anthropic The Anthropic Messages API over net/http, no vendor SDK
llm/openai The OpenAI chat completions and embeddings API, and compatible servers, over net/http
policy Rules that allow, ask a person about, or block an action, with every decision recorded under the rule that made it
policy/pg The Postgres recorder for policy: an append-only decision log
agent A run as a journal: model and tool calls written down around each step, a lease any process can take over, budgets, approvals and child runs
agent/pg The Postgres agent.Store, its migration, and Once for tools that write to the same database
agent/httpapi Runs, timelines, approvals and an event stream over HTTP; it names the caller but does not authenticate or authorise
agent/agenttest A hand-moved clock, a scripted model, a fault-injecting store and the Store contract suite
app The service lifecycle: logger, pool, migrations, router, auth and admin mounts, jobs, shutdown; and the adapters that put llm and policy behind agent
cmd/keel Scaffolds a project from a template profile (keel new <name> [-profile minimal|standard|api|worker|webhook|agent]; minimal copies examples/minimal, standard copies examples/fullstack, api copies examples/apionly, worker copies examples/worker, webhook copies examples/webhook, agent copies examples/agentdemo)

Configuration

config.Load reads a struct from the environment, calls Validate if the struct implements it, and trims whitespace from fields holding a secret or a URL.

type Config struct {
	Port        int    `envconfig:"PORT" default:"8080"`
	DatabaseURL string `envconfig:"DATABASE_URL" required:"true"`
	APIToken    string `envconfig:"API_TOKEN"`
}

var cfg Config
if err := config.Load(&cfg); err != nil {
	return err
}

config.Redacted(&cfg) renders the struct as name and value pairs safe to log at startup: secrets are replaced, collections report a count, and URLs keep their host and lose their password.

Each package that talks to an external service selects its backend by configuration and falls back to an in-process default:

Package Default External option
search Postgres full-text (PostgresIndex) Meilisearch (search/meili)
mail log sender (LogSender) Postmark
events in-memory bus (InMemoryBus) Cloud Pub/Sub (events/pubsub)
jobs in-process scheduler Cloud Run triggers (jobs/cloudrun)
media local filesystem (LocalStore) Google Cloud Storage (GCSStore)
geocode NoopProvider returns nil when it has no result Mapbox
auth local — email, password, verification, reset, sessions, all in-memory (auth/pg for Postgres) firebase (ID tokens), oidc (any issuer)
idempotency in-memory (MemoryStore) Postgres (idempotency/pg)
flags in-memory (MemoryStore) Postgres (flags/pg)
metrics no-op recorder, in-process capture (InMemory) OpenTelemetry (metrics/otel)
llm Scripted model and HashEmbedder, answering with no network Anthropic (llm/anthropic), OpenAI and compatible servers (llm/openai)
policy in-memory recorder (MemoryRecorder) Postgres (policy/pg)
agent in-memory store (MemoryStore), whose runs last as long as the process Postgres (agent/pg)

Nothing in llm/anthropic or llm/openai has been run against a real provider yet. Each has a live test behind the live build tag that needs an API key. See docs/agents.md for the agent packages.

Deployment

deploy/ holds a Dockerfile that injects the build revision, Cloud Build configuration, and scripts that check a deployed revision is the one that was pushed. scripts/ holds the repository's own developer and CI scripts.

See docs/deploy.md for health checks, proxy configuration, migrations, shutdown, pool sizing and build identification, and docs/backup.md for the backup and restore runbook.

Contributing

See CONTRIBUTING.md. ARCHITECTURE.md describes the package layout and the import rules. Tests run with:

make test               # everything that needs no Docker
make test-db            # database-backed packages, Docker required
make migrations-check   # replay every migrations directory in the module

pg/testdb starts a real Postgres in Docker for tests. KEEL_REQUIRE_DB=1 turns a missing Docker from a skip into a failure. See docs/testing.md.

License

Apache License 2.0. See LICENSE.

Directories

Path Synopsis
Package admin provides authentication and a router skeleton for an operator-facing HTTP API, separate from the auth package's end-user sessions.
Package admin provides authentication and a router skeleton for an operator-facing HTTP API, separate from the auth package's end-user sessions.
cmd/seed command
Command seed creates the first admin account, using admin.Seed against a Postgres-backed admin.AdminStore (admin/pg).
Command seed creates the first admin account, using admin.Seed against a Postgres-backed admin.AdminStore (admin/pg).
pg
Package pg is a Postgres-backed implementation of admin.AdminStore.
Package pg is a Postgres-backed implementation of admin.AdminStore.
Package agent runs an agent to completion across process deaths.
Package agent runs an agent to completion across process deaths.
agenttest
Package agenttest is what tests of agents are built from: a Clock a test moves by hand, a Model that answers from a script, a FaultStore that stops a process at a chosen store call, and RunStoreSuite, the contract every agent.Store passes.
Package agenttest is what tests of agents are built from: a Clock a test moves by hand, a Model that answers from a script, a FaultStore that stops a process at a chosen store call, and RunStoreSuite, the contract every agent.Store passes.
httpapi
Package httpapi serves runs, their timelines and their approvals over HTTP, for a person or a front end to list runs, read what one has done, follow it as it goes, and approve, decline or cancel.
Package httpapi serves runs, their timelines and their approvals over HTTP, for a person or a front end to list runs, read what one has done, follow it as it goes, and approve, decline or cancel.
internal/storerule
Package storerule is the part of the agent.Store contract that says what a store keeps, what it refuses and what it keeps as something else, written once.
Package storerule is the part of the agent.Store contract that says what a store keeps, what it refuses and what it keeps as something else, written once.
pg
Package pg is the Postgres-backed agent.Store: the one that keeps a run and its journal when the process executing it does not survive.
Package pg is the Postgres-backed agent.Store: the one that keeps a run and its journal when the process executing it does not survive.
Package app wires keel packages into a running service.
Package app wires keel packages into a running service.
Package auth provides authentication for an HTTP API: password accounts, session tokens, email verification, password reset, and identity-token exchange for Firebase and generic OpenID Connect providers.
Package auth provides authentication for an HTTP API: password accounts, session tokens, email verification, password reset, and identity-token exchange for Firebase and generic OpenID Connect providers.
pg
Package pg is a Postgres-backed implementation of the auth package's storage interfaces: UserStore, SessionStore, VerificationStore, PasswordResetStore and AttemptStore.
Package pg is a Postgres-backed implementation of the auth package's storage interfaces: UserStore, SessionStore, VerificationStore, PasswordResetStore and AttemptStore.
cmd
keel command
Command keel scaffolds projects built on keel.
Command keel scaffolds projects built on keel.
Package config loads a service's configuration from the environment.
Package config loads a service's configuration from the environment.
Package events publishes and subscribes to messages, between processes or between goroutines in one process, behind two interfaces.
Package events publishes and subscribes to messages, between processes or between goroutines in one process, behind two interfaces.
pubsub
Package pubsub implements events.Publisher and events.Subscriber for Google Cloud Pub/Sub.
Package pubsub implements events.Publisher and events.Subscriber for Google Cloud Pub/Sub.
examples
agentdemo command
Command agentdemo is a durable, governed agent service built out of keel, to be read rather than deployed.
Command agentdemo is a durable, governed agent service built out of keel, to be read rather than deployed.
apionly command
Command apionly is a small API-only service built out of keel, to be read rather than deployed.
Command apionly is a small API-only service built out of keel, to be read rather than deployed.
fullstack command
Command fullstack is the standard stack built out of keel, to be read rather than deployed.
Command fullstack is the standard stack built out of keel, to be read rather than deployed.
minimal command
Command minimal is a small service built out of keel, to be read rather than deployed.
Command minimal is a small service built out of keel, to be read rather than deployed.
webhook command
Command webhook is a minimal webhook receiver built out of keel, to be read rather than deployed.
Command webhook is a minimal webhook receiver built out of keel, to be read rather than deployed.
worker command
Command worker is a jobs-only service built out of keel, to be read rather than deployed.
Command worker is a jobs-only service built out of keel, to be read rather than deployed.
Package flags evaluates per-subject feature flags: a percentage rollout plus an explicit allowlist, over flag definitions kept in a Store.
Package flags evaluates per-subject feature flags: a percentage rollout plus an explicit allowlist, over flag definitions kept in a Store.
pg
Package pg is a Postgres-backed flags.Store, for a deployment that runs more than one instance and needs flag definitions to be visible to all of them.
Package pg is a Postgres-backed flags.Store, for a deployment that runs more than one instance and needs flag definitions to be visible to all of them.
Package geocode converts addresses to coordinates behind one interface.
Package geocode converts addresses to coordinates behind one interface.
Package httpx is the HTTP layer a service would otherwise write from scratch: a server that shuts down without dropping requests, a router with a middleware stack already in the right order, JSON responses, and health endpoints that check something.
Package httpx is the HTTP layer a service would otherwise write from scratch: a server that shuts down without dropping requests, a router with a middleware stack already in the right order, JSON responses, and health endpoints that check something.
buildinfo
Package buildinfo reports which revision the running binary was built from.
Package buildinfo reports which revision the running binary was built from.
middleware
Package middleware holds the HTTP middleware httpx assembles into a router, each usable on its own.
Package middleware holds the HTTP middleware httpx assembles into a router, each usable on its own.
Package idempotency lets a client safely retry an HTTP request that may have already succeeded, by replaying the first response instead of running the handler again.
Package idempotency lets a client safely retry an HTTP request that may have already succeeded, by replaying the first response instead of running the handler again.
pg
Package pg is a Postgres-backed idempotency.Store, for a deployment that runs more than one instance and needs a claim to be visible to all of them.
Package pg is a Postgres-backed idempotency.Store, for a deployment that runs more than one instance and needs a claim to be visible to all of them.
Package jobs runs background work: one-shot batch jobs and simple scheduled loops.
Package jobs runs background work: one-shot batch jobs and simple scheduled loops.
cloudrun
Package cloudrun implements jobs.Trigger for Google Cloud Run.
Package cloudrun implements jobs.Trigger for Google Cloud Run.
pg
Package pg is a Postgres-backed jobs.HistoryStore, for run history that survives a restart.
Package pg is a Postgres-backed jobs.HistoryStore, for run history that survives a restart.
llm
Package llm is how a service asks a language model for the next turn of a conversation: text, tool calls, a reply held to a JSON Schema, a streamed reply, and, separately, embeddings.
Package llm is how a service asks a language model for the next turn of a conversation: text, tool calls, a reply held to a JSON Schema, a streamed reply, and, separately, embeddings.
anthropic
Package anthropic is the llm.Model for Anthropic's Messages API.
Package anthropic is the llm.Model for Anthropic's Messages API.
internal/sse
Package sse reads a server-sent event stream.
Package sse reads a server-sent event stream.
openai
Package openai is the llm.Model and llm.Embedder for the OpenAI chat completions protocol, which local runtimes also speak.
Package openai is the llm.Model and llm.Embedder for the OpenAI chat completions protocol, which local runtimes also speak.
Package log builds the slog logger a service uses.
Package log builds the slog logger a service uses.
Package mail sends transactional email over a provider interface, and distinguishes "the code did not error" from "the provider accepted the message."
Package mail sends transactional email over a provider interface, and distinguishes "the code did not error" from "the provider accepted the message."
deliverycheck
Package deliverycheck compares what a send job reported as delivered against what the mail provider's own records hold.
Package deliverycheck compares what a send job reported as delivered against what the mail provider's own records hold.
reconcile
Package reconcile runs mail delivery reconciliation as a scheduled job: it polls recent sends, asks the provider for each message's status, and records confirmed, bounced and complained outcomes.
Package reconcile runs mail delivery reconciliation as a scheduled job: it polls recent sends, asks the provider for each message's status, and records confirmed, bounced and complained outcomes.
testing
Package testing provides a Recorder, a [mail.Sender] that captures every send in memory instead of delivering it, for use in tests and local development.
Package testing provides a Recorder, a [mail.Sender] that captures every send in memory instead of delivering it, for use in tests and local development.
Package media decodes, resizes, and stores photos, and defines a job pattern for doing this in the background: fetch a source, derive variants, store them, and record what was stored.
Package media decodes, resizes, and stores photos, and defines a job pattern for doing this in the background: fetch a source, derive variants, store them, and record what was stored.
Package metrics is the instrumentation other keel packages report through: HTTP request duration, pg pool acquire wait, job outcomes, outbox relay lag and attempts, event publish and drop counts, and geocode lookup outcomes.
Package metrics is the instrumentation other keel packages report through: HTTP request duration, pg pool acquire wait, job outcomes, outbox relay lag and attempts, event publish and drop counts, and geocode lookup outcomes.
otel
Package otel adapts metrics.Instruments to OpenTelemetry: one OTel instrument per keel instrument, under the names and attributes the metrics package documents.
Package otel adapts metrics.Instruments to OpenTelemetry: one OTel instrument per keel instrument, under the names and attributes the metrics package documents.
Package notifyprefs stores per-user notification preferences — which categories of message a user still wants on which channels — and enforces them on the send path.
Package notifyprefs stores per-user notification preferences — which categories of message a user still wants on which channels — and enforces them on the send path.
pg
Package pg is a Postgres-backed notifyprefs.Store, for a deployment that runs more than one instance and needs one user's preferences to read the same everywhere.
Package pg is a Postgres-backed notifyprefs.Store, for a deployment that runs more than one instance and needs one user's preferences to read the same everywhere.
Package outbox writes an event to Postgres in the same transaction as the domain change it describes, then relays it to an events.Publisher afterward, so a crash between the domain write and the publish cannot leave one without the other.
Package outbox writes an event to Postgres in the same transaction as the domain change it describes, then relays it to an events.Publisher afterward, so a crash between the domain write and the publish cannot leave one without the other.
pg
Package pg holds the Postgres schema [outbox.Relay] needs.
Package pg holds the Postgres schema [outbox.Relay] needs.
Package perf provides small, composable HTTP performance middleware: ResponseCache (an in-process cache with explicit tag-based invalidation), ETag (conditional GET via If-None-Match), Gzip (response compression), and SingleFlight (collapsing concurrent identical work).
Package perf provides small, composable HTTP performance middleware: ResponseCache (an in-process cache with explicit tag-based invalidation), ETag (conditional GET via If-None-Match), Gzip (response compression), and SingleFlight (collapsing concurrent identical work).
pg
Package pg is the Postgres plumbing a service needs before its first query: a configured pgx pool, pool stats for sizing and watching it, a transaction helper, and paging that does not silently ignore the caller.
Package pg is the Postgres plumbing a service needs before its first query: a configured pgx pool, pool stats for sizing and watching it, a transaction helper, and paging that does not silently ignore the caller.
migrate
Package migrate applies SQL migrations exactly once each and keeps a ledger of what ran.
Package migrate applies SQL migrations exactly once each and keeps a ledger of what ran.
testdb
Package testdb runs a real Postgres in Docker for tests, with a readiness check that does not report a database ready before it is.
Package testdb runs a real Postgres in Docker for tests, with a readiness check that does not report a database ready before it is.
Package policy decides what an action may do.
Package policy decides what an action may do.
pg
Package pg is the Postgres-backed policy.Recorder: the audit log of what agents were and were not allowed to do.
Package pg is the Postgres-backed policy.Recorder: the audit log of what agents were and were not allowed to do.
Package retry runs a function with exponential backoff, stopping on the first success, the first error Options.Retryable rejects, the attempt limit, or context cancellation, whichever comes first.
Package retry runs a function with exponential backoff, stopping on the first success, the first error Options.Retryable rejects, the attempt limit, or context cancellation, whichever comes first.
Package search indexes and queries generic, schema-less documents.
Package search indexes and queries generic, schema-less documents.
meili
Package meili implements search.Index for Meilisearch: facets, typo tolerance, synonyms, and settings-drift detection against a live index.
Package meili implements search.Index for Meilisearch: facets, typo tolerance, synonyms, and settings-drift detection against a live index.
Package site holds the static showcase site served from GitHub Pages.
Package site holds the static showcase site served from GitHub Pages.
gengallery command
Command gengallery renders site/gallery from the real minimal-example templates, so the gallery shows every block exactly as the service serves it: the same template source, the same stylesheets, in both themes.
Command gengallery renders site/gallery from the real minimal-example templates, so the gallery shows every block exactly as the service serves it: the same template source, the same stylesheets, in both themes.
Package textpolicy checks generated and forwarded text against a named set of patterns before it reaches storage or an audience.
Package textpolicy checks generated and forwarded text against a named set of patterns before it reaches storage or an audience.
Package webhooks delivers events to external URLs over HTTP, with each delivery signed so the receiver can verify it came from a holder of the endpoint's secret.
Package webhooks delivers events to external URLs over HTTP, with each delivery signed so the receiver can verify it came from a holder of the endpoint's secret.

Jump to

Keyboard shortcuts

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