nucleus

module
v1.28.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: Apache-2.0

README

Nucleus

CI Go Reference Go Report Card

Status: stable v1.x line. v1.0.0 was tagged 2026-07-10; the latest release is v1.28.0 and main tracks the next v1.x. The in-core admin panel was extracted to the separate orbit module (ADR-019). Public APIs are classified stable, transitional, or experimental (see docs/reference/API_CONTRACT_INVENTORY.md) and frozen by an automated contract test. The Compatibility SLO is active: application code on stable surfaces will not need rewrites within v1.x.

Nucleus is a web framework for Go. It pairs the ergonomics of a Django-style CLI with a stdlib-first runtime: net/http, database/sql, and log/slog are the substrate; everything else is added intentionally and stays behind framework-owned adapter boundaries so it can be swapped without breaking application code.

The framework ships as a core Go module plus twelve optional modules — the five database drivers (drivers/postgres, mysql, sqlite, mssql, oracle), the two telemetry exporters (exporters/otlp, prometheus), the three cloud storage providers (providers/storage-s3, storage-gcs, storage-azure), the AWS secrets resolver (providers/secrets-aws) and the LDAP backend (providers/ldap) — and a single CLI binary (nucleus). An application links only what it uses, with a blank import that nucleus add <name> writes for you (ADR-030, ADR-031). The admin panel is not in the core either — it ships as the separate orbit module, mounted in-process when an app wants it (ADR-019). Nucleus targets long-lived systems, not one-shot prototypes.


Why Nucleus

  • stdlib-first runtime. net/http, database/sql, log/slog, context are used directly — no Gin/Chi/Echo, no GORM/Bun/Ent, no zap/zerolog, no per-framework debugger plumbing in stack traces. (ADR-001)
  • Django-inspired CLI, Go-native semantics. 40 lifecycle commands — nucleus serve, migrate, createuser, inspectdb, dumpdata, loaddata, mailproviders, plugin doctor, makemessages, compilemessages, collectstatic, etc. — with both Go-style names and Django-compatible aliases (runserver, makemigrations, createsuperuser, dbshell). (ADR-002)
  • The pieces you are most likely to replace are pluggable. Storage backends, session stores and authentication backends are selected by name from a registry, so running Ceph instead of S3 — or authenticating against a corporate directory — does not mean forking the framework. A provider brings its own configuration subtree, and the built-ins register through the same public call as anyone else. (ADR-023)
  • Authentication as an ordered chain. auth_backends: [ldap, local] consults the directory first and falls through to your own user table when the directory cannot be reached — which is what makes a break-glass account work the morning it is needed. A backend that rejects ends the attempt; one that is unreachable is skipped, and the caller can tell the two apart.
  • Out-of-process plugins too. The plugin SDK v1 uses capability envelopes (mail.send, queue.publish, webhook.deliver) discovered via the nucleus-plugin-<provider> PATH convention, for backends that should not share the application's process.
  • Admin via orbit. The admin panel — auto-generated CRUD against registered models, a live request/SQL feed (single binary or multi-node via Redis), RBAC management, audit log, and operational views — ships as the separate orbit module, mounted in-process. The core exposes the Runtime accessors orbit reads (model registry, DB handles, session manager, RBAC enforcer, observability bus); it no longer bundles a UI.
  • Multi-database, multi-engine. SQLite, PostgreSQL, MySQL are required lanes; MSSQL and Oracle run as live lanes too, with parity tests for migrations, fixtures, sessions, cache, and inspect commands. Each driver is its own module (nucleus add postgres|mysql|sqlite|sqlserver|oracle), so an application carries one engine, not five — and the module also registers the error classifier that turns a duplicate key into a 409.
  • Operational depth. Transactional outbox with leasing dispatcher, task scheduler with periodic and queue-runtime helpers (Asynq + Redis), signals bus with optional Redis relay, OpenTelemetry tracing/metrics, structured logging with request correlation, deploy-readiness health command, and doctor checks for plugins/tasks/storage/observability.
  • Multi-tenant and multi-site. Subdomain or header-based tenant resolution, per-tenant DB isolation, automatic storage prefixing, a rate limiter keyed by user and tenant once the request is authenticated (by client IP before that; by route with rate_limit_by_route, by role with rate_limit_by_role), and explicit override APIs when you need to step around the convention.

5-minute start

go install github.com/jcsvwinston/nucleus/cmd/nucleus@latest

nucleus new myapp --module github.com/acme/myapp
cd myapp
nucleus generate module notes --mount
go run .

nucleus new generates a minimal skeleton — a composition-root main.go, nucleus.yml, .gitignore, and an empty migrations/ directory — with the database driver already resolved (--db picks the engine, --offline skips the network). There is no pre-built demo content: generate module --mount writes your first feature as a self-contained package (routes, storage, policy rows, embedded migrations, a test) and mounts it in main.go. The mvc template runs with full framework defaults and includes rbac_policy.csv (the default-deny Casbin policy); to add an admin UI, mount the orbit module. The api template uses WithoutDefaults() and serves only /healthz.

Open after go run .:

URL Surface
http://localhost:8080/healthz Liveness/readiness probe (always available)
http://localhost:8080/admin Admin panel — available once you mount the orbit module

To build your first feature module, see the working reference application in examples/mvc_api — it adds a notes REST resource on the fluent nucleus.Module surface and is the canonical starting point.

Generated projects are self-contained: go.mod already requires the right Nucleus version, no replace directive, no Nucleus source tree needed.

Minimal API in code
package main

import "github.com/jcsvwinston/nucleus/pkg/nucleus"

func main() {
    nucleus.New().
        FromConfigFile("nucleus.yml").
        WithoutDefaults().
        Start()
}

Add features as modules; see examples/mvc_api for a complete worked example using the nucleus.Module surface. The fluent package is a façade over the same pkg/app runtime.


What's in the box

Runtime packages
Package Lifecycle Purpose
pkg/app stable Application container, configuration, lifecycle, multi-tenant context
pkg/router stable net/http-backed router, middleware, request Context, binding/rendering helpers
pkg/model stable BaseModel, struct tags, validation, hook lifecycle, admin metadata (consumed by orbit)
pkg/db stable database/sql adapter, multi-DB resolution, migration runner
pkg/auth stable JWT manager, claims context, SCS-backed sessions (memory/SQL/Redis)
pkg/authz stable Casbin policy engine + middleware
pkg/mail stable Sender abstraction, built-in noop/smtp, vendor senders as nucleus-plugin-<provider> capability plugins
pkg/plugins stable Plugin SDK v1 envelopes, discovery, capability probe, runtime execution
pkg/tasks stable Asynq-backed task manager, scheduler, queue runtime ops, instrumentation
pkg/storage stable Provider registry with local built in; S3/GCS/Azure via the providers/storage-* modules (nucleus add s3|gcs|azure); credential resolution, public-path mapping, signed URLs
pkg/signals stable In-process bus + optional Redis pub/sub relay
pkg/observe stable slog setup + OTel pipeline
pkg/observability stable In-process event bus (HTTP/SQL/session events); modules consume it via the stable nucleus.EventBus facade
pkg/errors stable Domain error types and HTTP writer
pkg/validate stable Validator integration + custom rule registry
pkg/health stable Dependency health checks backing /healthz and the health command
pkg/circuit stable Circuit breaker wrapping mail and remote storage
pkg/outbox transitional SQL transactional outbox, leasing dispatcher (Kafka/Webhook bridges = preview)
pkg/openapi experimental OpenAPI 3.1 document model for internal/contracts projects
pkg/i18n experimental Runtime for the compiled i18n catalogs: Accept-Language negotiation middleware + c.T(...) translation
pkg/cache experimental Minimal TTL cache: in-memory backend + SQL backend over the createcachetable table
pkg/nucleus stable Fluent builder façade — the nucleus.New() entry point
pkg/auth/backend stable Contract a third-party authentication backend implements (Backend, Registration, registry); a leaf so a plugin author does not inherit the runtime (ADR-025)
pkg/auth/backend/backendtest stable Conformance suite a third-party authentication backend runs against itself (ADR-027)
pkg/auth/federated stable Contract a browser-redirect identity provider (OIDC, SAML) implements; the framework keeps the anti-forgery state (ADR-028)
pkg/auth/secrets transitional AWS Secrets Manager resolver behind an internal interface; slated for extraction (ADR-005)
pkg/auth/sessionstore stable Contract a third-party session store implements; typed parameters, zero third-party packages (ADR-026)
pkg/db/driver stable Contract a database driver module implements: the driver plus its error classifier (ADR-031)
pkg/db/driver/drivertest stable Conformance kit for driver modules, in the shape of backendtest (ADR-027)
pkg/observe/exporter stable Contract a telemetry exporter module implements; the framework keeps the SDK and none of the exporters (ADR-031)
pkg/router/interceptor stable Contract a third-party request interceptor implements, registered by name and ordered from configuration (ADR-029)
pkg/storage/provider stable Contract a third-party storage backend implements; a leaf so a plugin author does not inherit the cloud SDKs (ADR-026)
pkg/tasks/providers/asynq transitional asynq task backend; wraps asynq and OpenTelemetry behind unexported fields
pkg/tasks/providers/memory transitional In-process task backend for development; honours MaxRetry and Timeout, single queue

See docs/reference/API_CONTRACT_INVENTORY.md for the contract per package.

CLI command groups
Project lifecycle    new, startapp, wizard, generate, add, serve, health, doctor
Database             migrate, sqlmigrate, sqlflush, sqlsequencereset,
                     squashmigrations, optimizemigration, inspectdb,
                     ogrinspect, shell, flush
Data                 loaddata, dumpdata, seed, outbox
Cache & sessions     createcachetable, clearsessions,
                     remove_stale_contenttypes
Identity             createuser, changepassword
Mail                 mailproviders, sendtestemail
Plugins              plugin list, plugin doctor, plugin test
Static & i18n        collectstatic, findstatic, makemessages,
                     compilemessages
Contracts            openapi
Diagnostics          config, diffsettings, routes, testserver, test

Aliases mirror Django where it is unambiguous: runserver, startproject, makemigrations, showmigrations, createsuperuser, dbshell. The global output flags --json, --output, --color, --symbols are honoured by the inspection commands (health, routes, config, mailproviders, plugin, cache/contenttype/static tooling); adoption across the remaining commands is tracked, not claimed.

Configuration

A single nucleus.yml per project (extension is .yml, not .yaml). All keys are versioned in docs/reference/CONFIG_KEY_REGISTRY.md and frozen by contracts/baseline/config_key_patterns.txt.

Credentials never live in plaintext in source. Every sensitive value accepts the CredentialSource shape (value / env_var / file / secret_manager) for K8s secrets, mounted volumes, or cloud secret managers.


Reference applications

Two reference applications ship in-tree:

  • examples/mvc_api — the canonical worked module: a notes REST resource on the fluent nucleus.Module surface (package-per-feature, mounted with one line). Reintroduced against the ADR-010 API after the original examples/* tree was removed in Phase 1 (2026-05-16) so it would not constrain the fluent surface during its rewrite.
  • examples/showcase_demo — the three suite products working together (Nucleus app + Quark ORM + orbit panel), with the integration bridges wired and curls included. It is its own Go module so Quark and orbit stay out of the framework's dependency graph.

nucleus generate module <name> scaffolds a new feature in the same package-per-feature shape: one package under internal/<name>/ whose module carries its routes, storage, policy rows, CSRF exemption, embedded migrations and page template — mounting it is the whole integration (see ADR-022).


Documentation map

The user-facing documentation is the public site: jcsvwinston.github.io/quantum/nucleus (source: website/docs/). It is the living narrative — quickstart, concepts, features, operations, reference — and wins over the internal guides below when they disagree. What follows is the in-repo map: contracts, governance and the internal depth the site links into.

Start here
Build
Operate
Govern

Compatibility and contracts

Six text files in contracts/baseline/ freeze the public surface and are checked on every CI run:

File Asserts
api_exported_symbols.txt No exported symbol disappears from the curated stable packages without an explicit ADR
cli_primary_commands.txt No CLI command name disappears
cli_json_status_keys.txt No JSON status key disappears from --json output
config_key_patterns.txt No nucleus.yml key shape disappears
extension_surface.txt No framework service an extension may read disappears — and none appears without being declared
security_posture.txt The default security posture does not change in EITHER direction without being stated

The first four block removals: new surface area is allowed and captured in the next baseline commit.

The last two block change in both directions, for the same reason. An extension-facing field appearing is a promise to plugin authors, so it is made on purpose rather than by accident. And a security default that gets stricter changes the behaviour of deployments that relied on the old one, which is a compatibility event even though it sounds like an improvement.

The security posture baseline is also the only one that is measured rather than transcribed: it comes out of a real HTTP response from a really booted application, so it cannot claim a protection the framework does not emit. See contracts/freeze_test.go, contracts/firewall_test.go, contracts/extension_surface_test.go and contracts/security_posture_test.go.


Requirements

  • Go 1.26+ (the exact minimum is the go directive in go.mod — the only place that number lives)
  • One database driver module: drivers/sqlite, drivers/postgres, drivers/mysql (required lanes), drivers/mssql or drivers/oracle (live lanes) — nucleus add <engine> adds the import
  • Optional: Redis (sessions, tasks, signals relay; orbit's multi-node live cluster)

For local dev, docker-compose.yml brings up Postgres, MySQL, MariaDB, Redis, SQL Server, Oracle and Jaeger instances aligned with the test matrix.


License

Apache-2.0 — see LICENSE.

Directories

Path Synopsis
admin
agent module
proto module
cmd
nucleus command
drivers
mssql module
mysql module
oracle module
postgres module
sqlite module
exporters
otlp module
prometheus module
internal
cli
`nucleus generate module <name>` — the package-per-feature slice generator (ADR-022 §4).
`nucleus generate module <name>` — the package-per-feature slice generator (ADR-022 §4).
cli/scaffold
Package scaffold renders the `nucleus new` starter project from a tree of embedded template files instead of inline Go string literals.
Package scaffold renders the `nucleus new` starter project from a tree of embedded template files instead of inline Go string literals.
configbind
Package configbind is the single place a merged koanf tree becomes a framework config struct.
Package configbind is the single place a merged koanf tree becomes a framework config struct.
dbclassify
Package dbclassify holds the per-driver error predicates.
Package dbclassify holds the per-driver error predicates.
dupfixture
Package dupfixture holds a model whose type NAME collides with one in the model package's tests: two packages each declaring a Product is the ordinary way two modules end up registering the same model name (NU-20).
Package dupfixture holds a model whose type NAME collides with one in the model package's tests: two packages each declaring a Product is the ordinary way two modules end up registering the same model name (NU-20).
knownproviders
Package knownproviders names the backends this project ships as separate modules.
Package knownproviders names the backends this project ships as separate modules.
providerconfig
Package providerconfig binds the configuration subtree that belongs to a registered provider — a storage backend, a session store, an authentication backend — into the provider's own typed struct.
Package providerconfig binds the configuration subtree that belongs to a registered provider — a storage backend, a session store, an authentication backend — into the provider's own typed struct.
providerns
Package providerns answers one question for every configuration validator in the framework: does this key belong to the private subtree of a REGISTERED provider, rather than to app.Config's schema?
Package providerns answers one question for every configuration validator in the framework: does this key belong to the private subtree of a REGISTERED provider, rather than to app.Config's schema?
routedump
Package routedump is the wire format between a Nucleus application that prints its route table at boot (NUCLEUS_PRINT_ROUTES=1, read by pkg/nucleus.RunContext) and the `nucleus routes` command that runs the application to read it.
Package routedump is the wire format between a Nucleus application that prints its route table at boot (NUCLEUS_PRINT_ROUTES=1, read by pkg/nucleus.RunContext) and the `nucleus routes` command that runs the application to read it.
pkg
accounts
Package accounts is the part of authentication an end user touches: registering, confirming an address, signing in and out, recovering a password, and being locked out after enough wrong guesses.
Package accounts is the part of authentication an end user touches: registering, confirming an address, signing in and out, recovering a password, and being locked out after enough wrong guesses.
app
Package app provides the application configuration and bootstrap for Nucleus.
Package app provides the application configuration and bootstrap for Nucleus.
auth
Package auth provides authentication utilities for the Nucleus framework, including password hashing, JWT management, and session handling.
Package auth provides authentication utilities for the Nucleus framework, including password hashing, JWT management, and session handling.
auth/apikeys
Package apikeys is the credential a program uses to call an API: issued once, shown once, revocable, scoped, and recognisable in a log.
Package apikeys is the credential a program uses to call an API: issued once, shown once, revocable, scoped, and recognisable in a log.
auth/backend
Package backend is the contract a third-party authentication backend implements — and nothing else.
Package backend is the contract a third-party authentication backend implements — and nothing else.
auth/backend/backendtest
Package backendtest is a conformance suite for authentication backends.
Package backendtest is a conformance suite for authentication backends.
auth/federated
Package federated is the contract a browser-redirect identity provider implements — OIDC, SAML, anything where the user leaves for an identity provider and comes back — and nothing else.
Package federated is the contract a browser-redirect identity provider implements — OIDC, SAML, anything where the user leaves for an identity provider and comes back — and nothing else.
auth/federated/oidc
Package oidc is an OpenID Connect provider for the federated sign-in seam: authorization code flow with PKCE, discovery, and an id_token verified against the provider's published keys.
Package oidc is an OpenID Connect provider for the federated sign-in seam: authorization code flow with PKCE, discovery, and an id_token verified against the provider's published keys.
auth/secrets
Package secrets resolves opaque reference strings into raw secret bytes for the auth layer — JWT signing keys, primarily.
Package secrets resolves opaque reference strings into raw secret bytes for the auth layer — JWT signing keys, primarily.
auth/sessionstore
Package sessionstore is the contract a third-party session store implements — and nothing else.
Package sessionstore is the contract a third-party session store implements — and nothing else.
authz
Package authz provides authorization for the Nucleus framework using Casbin.
Package authz provides authorization for the Nucleus framework using Casbin.
cache
Package cache is the runtime counterpart of the `nucleus createcachetable` CLI command: a minimal key/value cache with TTL semantics, an in-memory backend for single-process deployments, and a SQL backend wired to the table that command creates (`nucleus_cache_entries` by default) for multi-replica deployments that share a database.
Package cache is the runtime counterpart of the `nucleus createcachetable` CLI command: a minimal key/value cache with TTL semantics, an in-memory backend for single-process deployments, and a SQL backend wired to the table that command creates (`nucleus_cache_entries` by default) for multi-replica deployments that share a database.
circuit
Package circuit provides a small circuit-breaker primitive for wrapping calls to external dependencies (mail, storage, plugin bridges, third-party APIs) in a deterministic failure-isolation pattern.
Package circuit provides a small circuit-breaker primitive for wrapping calls to external dependencies (mail, storage, plugin bridges, third-party APIs) in a deterministic failure-isolation pattern.
db
Package db provides database connectivity for the Nucleus framework.
Package db provides database connectivity for the Nucleus framework.
db/driver
Package driver is the contract a database driver module implements to plug into pkg/db.
Package driver is the contract a database driver module implements to plug into pkg/db.
db/driver/drivertest
Package drivertest is a conformance kit for database driver modules.
Package drivertest is a conformance kit for database driver modules.
errors
Package errors provides domain-specific error types for the Nucleus framework.
Package errors provides domain-specific error types for the Nucleus framework.
health
Package health provides a small abstraction for dependency probes used by the /healthz handler in pkg/app.
Package health provides a small abstraction for dependency probes used by the /healthz handler in pkg/app.
i18n
Package i18n is the runtime counterpart of the `nucleus makemessages` / `nucleus compilemessages` CLI pair.
Package i18n is the runtime counterpart of the `nucleus makemessages` / `nucleus compilemessages` CLI pair.
model
Package model provides the model registry, metadata extraction, and generic CRUD operations for the Nucleus framework.
Package model provides the model registry, metadata extraction, and generic CRUD operations for the Nucleus framework.
nucleus
Package nucleus — config.go implements the configuration loader surfaced by `AppBuilder.FromConfigFile`.
Package nucleus — config.go implements the configuration loader surfaced by `AppBuilder.FromConfigFile`.
nucleustest
Package nucleustest boots a nucleus application inside the test process (DX-22).
Package nucleustest boots a nucleus application inside the test process (DX-22).
observability
Package observability is the in-process EVENT BUS — not the logging package.
Package observability is the in-process EVENT BUS — not the logging package.
observability/hooks
Package hooks plugs the framework's existing instrumentation points (HTTP middleware, SQL observer, session manager) into the observability.Bus so the agent (and direct subscribers) can receive strongly typed events.
Package hooks plugs the framework's existing instrumentation points (HTTP middleware, SQL observer, session manager) into the observability.Bus so the agent (and direct subscribers) can receive strongly typed events.
observe
Package observe is the one you almost always want: structured logging (slog with context-aware fields), request/trace IDs and the small set of helpers the rest of the framework logs through.
Package observe is the one you almost always want: structured logging (slog with context-aware fields), request/trace IDs and the small set of helpers the rest of the framework logs through.
observe/exporter
Package exporter is the contract a telemetry exporter module implements to plug into pkg/observe.
Package exporter is the contract a telemetry exporter module implements to plug into pkg/observe.
outbox
Package outbox provides a transactional outbox pattern implementation with support for external message delivery through configurable bridges.
Package outbox provides a transactional outbox pattern implementation with support for external message delivery through configurable bridges.
router
Package router provides an HTTP router for the Nucleus framework, built on top of Go's standard net/http.ServeMux (Go 1.22+).
Package router provides an HTTP router for the Nucleus framework, built on top of Go's standard net/http.ServeMux (Go 1.22+).
router/interceptor
Package interceptor is the contract a third-party request interceptor implements — and nothing else.
Package interceptor is the contract a third-party request interceptor implements — and nothing else.
signals
Package signals provides a synchronous and asynchronous event bus for the Nucleus framework.
Package signals provides a synchronous and asynchronous event bus for the Nucleus framework.
storage/provider
Package storage provides a durable, provider-agnostic file storage interface for Nucleus applications.
Package storage provides a durable, provider-agnostic file storage interface for Nucleus applications.
tasks/providers/asynq
Package tasks provides background job enqueueing and worker runtime backed by Asynq.
Package tasks provides background job enqueueing and worker runtime backed by Asynq.
validate
Package validate provides struct validation powered by go-playground/validator, with automatic conversion of validation errors to Nucleus DomainErrors.
Package validate provides struct validation powered by go-playground/validator, with automatic conversion of validation errors to Nucleus DomainErrors.
providers
ldap module
secrets-aws module
storage-azure module
storage-gcs module
storage-s3 module
scripts
website/bodycheck command
Command bodycheck is the automated CI guard for the §9 anti-falsehood discipline (see CLAUDE.md §9).
Command bodycheck is the automated CI guard for the §9 anti-falsehood discipline (see CLAUDE.md §9).
website/gen-config-reference command
Command gen-config-reference renders the public Configuration reference page (website/docs/reference/configuration.md) from the configuration key registry (docs/reference/CONFIG_KEY_REGISTRY.md).
Command gen-config-reference renders the public Configuration reference page (website/docs/reference/configuration.md) from the configuration key registry (docs/reference/CONFIG_KEY_REGISTRY.md).

Jump to

Keyboard shortcuts

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