hyrule

module
v0.102.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT

README

Português

hyrule

Go Reference codecov

A Go framework for scaffolding microservices fast, and testing their flows just as fast: describe a resource (schema, methods, lookups) — in a YAML file, no Go at all, or in Go when it needs its own logic — and get a running REST API with:

  • Full CRUD, validation and pagination from a schema, no hand-written handler.
  • ETags/If-Match built in — optimistic concurrency, not something you wire up yourself.
  • Mongo or Postgres, same HTTP contract — the YAML path stays Mongo-only for now; a hand-written resource picks either backend through rest.Adapter (restpostgres for Postgres, see the Adapter reference below) for CRUD, validation, ETags and querying.
  • A transactional outbox (a write and the event it causes commit together, in the same transaction, or neither does), testkit (isolated database + HTTP client per test) and dry run (a whole service against real traffic, every write rolled back). Transactional outbox and dry run support both backends. YAML and the testkit database provisioner remain Mongo-specific; HTTP/token helpers work with Postgres through app.Build as well.

Under the hood it keeps the HTTP contract of Eve (Python) (rest), which is where the project migrated from.

📖 Full documentation: https://gui-rondon.github.io/hyrule/ — a guided Learn path plus a complete Reference.

Mongo and Postgres integration

Both backends use app.Main/app.Build, the same HTTP resource contract and transactional event hooks. Start with the Mongo and Postgres integration guide: complete Go services, connection settings, schema/index setup, tests and opt-ins. The integration review records compatibility changes and gate evidence against main. Use a commit/release containing this integration; changing a backend does not migrate data.

Mongo Postgres
Resource Store: env.Store("items") Adapter: restpostgres.NewAdapter(...)
Bootstrap app.BackendMongo (default) app.BackendPostgres
Outbox outbox outboxpostgres
Running example posts-api comments-api

Mongo quickstart: a resource with no Go

# resources.yaml
resources:
  - name: tags
    collection: tags
    additional_lookup: {field: slug, pattern: '^[\w-]+$'}
    resource_methods: [get, post]
    item_methods: [get, patch, put]
    schema:
      name: {type: string, required: true}
      slug: {type: string, required: true, unique: true}
      enabled: {type: boolean, default: true}
make env-up    # Mongo (27018), Postgres (5433), Pub/Sub (8085), Redis (6380)
echo '{"auth": {"enable": "false"}}' > config.json
RESOURCES_FILE=resources.yaml CONFIG_FILE=config.json \
  MONGO_CONNECTION_STRING='mongodb://localhost:27018/demo?directConnection=true' \
  PORT=8080 go run ./cmd/hyrule-serve
curl -X POST localhost:8080/tags -d '{"name":"Go","slug":"go"}'
curl localhost:8080/tags/go

That's cmd/hyrule-serve + declarative — it covers the common case. A resource with its own logic (hooks, custom endpoints, conditional validation) stays a small Go binary with app.Main, like the 5 examples in examples/blog-apis/ — both paths register resources the same way and coexist in the same process. The Learn guide walks through building both kinds, step by step.

examples/standalone-tags-api/ is the same quickstart as above, but as its own Go module (own go.mod) that depends on this one — the proof that an external repository can really go get this framework, not just import it from inside this monorepo.

Postgres quickstart: Go resource with transactional events

The comments service uses app.BackendPostgres, UUID/version CAS, JSONB, explicit migrations and a transactional outbox. From this checkout:

make env-up
curl -sf -X PUT http://localhost:8085/v1/projects/local-dev/topics/comments-to-publish
POSTGRES_CONNECTION_STRING='postgres://postgres:postgres@localhost:5433/postgres?sslmode=disable' \
  make comments-migrate MIGRATE_ARGS='-action prepare'
make build SERVICE=comments-api
printf '%s\n' '{"auth":{"enable":false},"pubsub":{"project_id":"local-dev","to_publish":"comments-to-publish"}}' > .local/comments-api.json
POSTGRES_CONNECTION_STRING='postgres://postgres:postgres@localhost:5433/postgres?sslmode=disable' \
  PUBSUB_EMULATOR_HOST=localhost:8085 CONFIG_FILE=.local/comments-api.json \
  PORT=8082 .local/comments-api
curl -X POST localhost:8082/comments -H 'Content-Type: application/json' \
  -d '{"post_id":"post-1","author_name":"Link","body":"Hello","status":"published"}'
curl -G localhost:8082/comments --data-urlencode 'where={"post_id":"post-1"}'

See the example runbook for Pub/Sub delivery and schema rollout. The backend guide shows a minimal Postgres service without the example's Pub/Sub dependency.

Platform: scaffolding a multi-service project

go install github.com/Gui-Rondon/hyrule/cmd/hyrule@main

hyrule new my-platform
cd my-platform
go get github.com/Gui-Rondon/hyrule@main
hyrule service create articles

make env-up
make build SERVICE=articles
make run SERVICE=articles

hyrule new/hyrule service create are the only two commands today (ADR-0004) — scaffolding, not a build/deploy orchestrator. The generated project has its own go.mod, Makefile, and docker-compose.yml, in the same shape as this repo's own; dev/build --affected/deploy subcommands are future work (see the roadmap). The Platform guide walks through this step by step, including copying examples/blog-apis's affected-build CI and deploy pattern into a generated project.

Documentation

The full docs are at https://gui-rondon.github.io/hyrule/:

Learn a guided, step-by-step path through the framework, building up examples/blog-apis one concept at a time
Platform hyrule new/hyrule service create, and copying the affected-build CI and deploy pattern into a generated project
Reference → Store the Store interface: what it decouples (and what it doesn't yet)
Reference → Outbox the transactional outbox, and the conditional primitive that fires an event straight from the write
Reference → resources.yaml full reference of the resource YAML
Reference → Dry run running in dry run: everything runs, the transaction always rolls back
Reference → Testkit testing a resource (isolated Mongo, HTTP client, tokens)
Reference → Architecture the services → behaviors → rest → platform layering, and why it exists
Reference → Querying the where=/sort/projection query language and how it's parsed
Reference → Adapter rest.Adapter, the seam a Postgres-backed resource (restpostgres) registers instead of Store
Reference → Postgres backend (historical) the original design record for the Postgres backend, superseded by the Adapter reference above

Layout

app/                           shared bootstrap (app.Main / app.Build)
behaviors/                     reusable hooks: searchsync (ES), audit, events (outbox on write)
rest/                          the HTTP contract: Service (rules, no HTTP) + API (HTTP) + Adapter (storage seam, Store for Mongo)
restpostgres/                  rest.Adapter over platform/postgres — the Postgres-backed resource path
outbox/                        transactional outbox, the Pub/Sub relay and the conditional primitive
declarative/                   loads a Resource/Schema from YAML (cmd/hyrule-serve), Mongo only today
platform/                      config, mongodb, postgres, auth, search, health, server, pubsub, redis
testkit/                       per-test isolated Mongo, ES recorder, tokens
internal/domain/               the one package that stays internal (slug generation)
cmd/hyrule-serve/              generic binary: registers the resources of a YAML, no domain Go
cmd/hyrule/                    the Platform CLI: hyrule new, hyrule service create
ci/                            ci/affected (picks the services a diff affects)
examples/blog-apis/            a real use of the framework (see that directory's README)
examples/standalone-tags-api/  an external Go module (own go.mod) depending on this one
website/                       source of https://gui-rondon.github.io/hyrule/ (Docusaurus)

Development

Requires Go 1.27 and Docker.

make env-up               # generic infra: Mongo (27018), Postgres (5433), Pub/Sub (8085), Redis (6380)
make test                 # every test (uses real Mongo/Postgres from env-up)
make unit                 # only the ones that need no external service
make cover                # framework coverage, fails below 95%
make cover-all            # historical aggregate (framework + examples/tools), minimum 85%
make build SERVICE=tags-api
make run SERVICE=tags-api  # :8081, auth disabled

To run the blog-apis example (which also needs Elasticsearch): see examples/blog-apis/README.md.

Coverage uses all normal package tests (./...) with real MongoDB and PostgreSQL. make cover measures the runtime framework (app, behaviors, declarative, outbox, outboxpostgres, platform, rest, restpostgres); example services, CLI/manual HA tools and testkit do not enter its denominator. Tests for those packages still execute. make cover-all writes the historical aggregate scope separately to .local/coverage-all.out; the framework profile remains .local/coverage.out. Run these commands sequentially, after make env-up.

License

MIT — © 2026 Guilherme Rondon.

Directories

Path Synopsis
Package app is the bootstrap shared by the services: configuration, Mongo or Postgres (Spec.Backend), authentication, the Eve API, /status and /healthcheck.
Package app is the bootstrap shared by the services: configuration, Mongo or Postgres (Spec.Backend), authentication, the Eve API, /status and /healthcheck.
behaviors
audit
Package audit records who created and last changed a document: _created_user and _updated_user with the username of the request token (nil when authentication is disabled).
Package audit records who created and last changed a document: _created_user and _updated_user with the username of the request token (nil when authentication is disabled).
events
Package events records outbox events in the transaction of a resource write (D-23).
Package events records outbox events in the transaction of a resource write (D-23).
searchsync
Package searchsync keeps an Elasticsearch index in sync with a resource, as the resource_callbacks.py of the Eve APIs do: every write indexes the stored document (without _id) and a delete removes it.
Package searchsync keeps an Elasticsearch index in sync with a resource, as the resource_callbacks.py of the Eve APIs do: every write indexes the stored document (without _id) and a delete removes it.
ci
affected command
Command affected prints the services whose binary changed between two commits, one per line, for the CI "detect services" job.
Command affected prints the services whose binary changed between two commits, one per line, for the CI "detect services" job.
cmd
hyrule command
Command hyrule is Hyrule's Platform CLI.
Command hyrule is Hyrule's Platform CLI.
hyrule-serve command
Command hyrule-serve registers the resources declared in a YAML file (declarative) and serves them — no domain-specific Go code at all for the common case the loader covers.
Command hyrule-serve registers the resources declared in a YAML file (declarative) and serves them — no domain-specific Go code at all for the common case the loader covers.
Package declarative builds rest.Resource/Schema values from YAML, for the common case — a resource with no custom hooks or business logic (see rest/service.go: settings-api, tags-api, authors-api in examples/blog-apis are entirely this shape already, hand-written).
Package declarative builds rest.Resource/Schema values from YAML, for the common case — a resource with no custom hooks or business logic (see rest/service.go: settings-api, tags-api, authors-api in examples/blog-apis are entirely this shape already, hand-written).
examples
blog-apis/cmd/comments-migrate command
Command comments-migrate performs explicit comments-api schema operations.
Command comments-migrate performs explicit comments-api schema operations.
blog-apis/e2e/check-results command
Command check-results makes JMeter assertion failures fail the harness.
Command check-results makes JMeter assertion failures fail the harness.
blog-apis/e2e/mint command
Command mint signs an RS256 JWT with the e2e harness's generated legacy key, for exercising platform/auth's legacy fallback from JMeter (which has no RS256 JWT signer out of the box).
Command mint signs an RS256 JWT with the e2e harness's generated legacy key, for exercising platform/auth's legacy fallback from JMeter (which has no RS256 JWT signer out of the box).
blog-apis/internal/commentsschema
Package commentsschema owns comments-api's versioned table schema.
Package commentsschema owns comments-api's versioned table schema.
blog-apis/services/authors-api command
Command authors-api is the simplest example of the blog-apis suite: a resource described entirely by its schema, with zero business-specific Go code — a candidate to become a plain YAML definition once the framework's declarative resource loader exists.
Command authors-api is the simplest example of the blog-apis suite: a resource described entirely by its schema, with zero business-specific Go code — a candidate to become a plain YAML definition once the framework's declarative resource loader exists.
blog-apis/services/categories-api command
Command categories-api demonstrates a hierarchical resource: a materialized path kept up to date on every write, and a custom GET /categories/tree endpoint built straight from the Store interface (no raw *mongo.Collection in sight).
Command categories-api demonstrates a hierarchical resource: a materialized path kept up to date on every write, and a custom GET /categories/tree endpoint built straight from the Store interface (no raw *mongo.Collection in sight).
blog-apis/services/comments-api command
Command comments-api is Fase 7's end-to-end proof for the Postgres path: a real resource (blog comments) served over real HTTP by a real binary, backed by platform/postgres+restpostgres instead of Mongo.
Command comments-api is Fase 7's end-to-end proof for the Postgres path: a real resource (blog comments) served over real HTTP by a real binary, backed by platform/postgres+restpostgres instead of Mongo.
blog-apis/services/posts-api command
Command posts-api is the richest example of the blog-apis suite: a resource with relations to authors-api/categories-api/tags-api, custom publish/schedule endpoints, outbox events, a Redis-backed scheduling index and Elasticsearch indexing.
Command posts-api is the richest example of the blog-apis suite: a resource with relations to authors-api/categories-api/tags-api, custom publish/schedule endpoints, outbox events, a Redis-backed scheduling index and Elasticsearch indexing.
blog-apis/services/tags-api command
Command tags-api is another zero-business-logic example: a resource with a Unique field and a slug lookup, nothing else.
Command tags-api is another zero-business-logic example: a resource with a Unique field and a slug lookup, nothing else.
internal
domain/slug
Package slug is python-slugify's default slugify, used by the APIs and workers that turn tag names into {slug, name}.
Package slug is python-slugify's default slugify, used by the APIs and workers that turn tag names into {slug, name}.
pgexplain
Package pgexplain supports manual local integration gates.
Package pgexplain supports manual local integration gates.
Package outbox implements the transactional outbox (D-10, D-23): a write stores its events in the outbox collection in the same Mongo transaction, and the Relay publishes them after the commit.
Package outbox implements the transactional outbox (D-10, D-23): a write stores its events in the outbox collection in the same Mongo transaction, and the Relay publishes them after the commit.
Package outboxpostgres is the Postgres counterpart to outbox's Mongo-backed Outbox/Relay -- the same pattern platform/postgres and restpostgres already follow relative to platform/mongodb and rest: a separate package per backend, never a type switch inside the original one.
Package outboxpostgres is the Postgres counterpart to outbox's Mongo-backed Outbox/Relay -- the same pattern platform/postgres and restpostgres already follow relative to platform/mongodb and rest: a separate package per backend, never a type switch inside the original one.
platform
auth
Package auth validates requests: an Azure AD token is tried first and, when the token isn't an Azure one (no kid, unknown kid), it falls back to a static RS256 key — for a secondary issuer, service-to-service tokens, or any other static key a deployment wants to trust alongside Azure AD.
Package auth validates requests: an Azure AD token is tried first and, when the token isn't an Azure one (no kid, unknown kid), it falls back to a static RS256 key — for a secondary issuer, service-to-service tokens, or any other static key a deployment wants to trust alongside Azure AD.
config
Package config loads the service configuration from properties-api, the Spring Cloud Config Server that serves the config-files repository.
Package config loads the service configuration from properties-api, the Spring Cloud Config Server that serves the config-files repository.
health
Package health serves /status and /healthcheck with the bodies of the Eve APIs (endpoints/status.py and eve-healthcheck), which monitoring and the Kubernetes probes already read.
Package health serves /status and /healthcheck with the bodies of the Eve APIs (endpoints/status.py and eve-healthcheck), which monitoring and the Kubernetes probes already read.
httppath
Package httppath contains the path operations shared by Hyrule's HTTP router and REST helpers.
Package httppath contains the path operations shared by Hyrule's HTTP router and REST helpers.
lease
Package lease elects one active replica through a document in Mongo, as the outbox relay does: the holder renews the lease before it expires, and another replica takes it only after it expires or is released.
Package lease elects one active replica through a document in Mongo, as the outbox relay does: the holder renews the lease before it expires, and another replica takes it only after it expires or is released.
metrics
Package metrics exposes the Prometheus metrics of an API at /metrics: the duration and the response size of every request by method, route and status, plus the Go runtime and the process.
Package metrics exposes the Prometheus metrics of an API at /metrics: the duration and the response size of every request by method, route and status, plus the Go runtime and the process.
mongodb
Package mongodb connects to Mongo with the settings read by the Eve APIs.
Package mongodb connects to Mongo with the settings read by the Eve APIs.
mongodb/mongotest
Package mongotest prepares the Mongo of the tests: a server started with --replSet but not initiated yet (a CI service container) is initiated as a single node replica set, and every caller waits until it has a primary.
Package mongotest prepares the Mongo of the tests: a server started with --replSet but not initiated yet (a CI service container) is initiated as a single node replica set, and every caller waits until it has a primary.
postgres
Package postgres is the Postgres counterpart to platform/mongodb: Store here follows the same pattern platform/mongodb.Store does (its own types, not an implementation of rest.Store), but stays deliberately narrow -- an equality-only Filter over flat columns (see Filter's own doc comment below).
Package postgres is the Postgres counterpart to platform/mongodb: Store here follows the same pattern platform/mongodb.Store does (its own types, not an implementation of rest.Store), but stays deliberately narrow -- an equality-only Filter over flat columns (see Filter's own doc comment below).
pubsub
Package pubsub connects to Google Pub/Sub with the settings read from config.Config.
Package pubsub connects to Google Pub/Sub with the settings read from config.Config.
redis
Package redis connects to Redis with the settings read from config.Config:
Package redis connects to Redis with the settings read from config.Config:
search
Package search writes to Elasticsearch through its REST API (PUT/POST/DELETE /{index}/_doc|_update/{id}), which is what the Python client 7.x used by the Eve APIs and workers does, so no client library is needed.
Package search writes to Elasticsearch through its REST API (PUT/POST/DELETE /{index}/_doc|_update/{id}), which is what the Python client 7.x used by the Eve APIs and workers does, so no client library is needed.
server
Package server holds the bootstrap shared by the services: logging, the HTTP server and graceful shutdown.
Package server holds the bootstrap shared by the services: logging, the HTTP server and graceful shutdown.
Package rest serves Mongo collections with the HTTP contract of Python Eve, so the gateways that call the Eve APIs keep working unchanged: where/sort/projection/page/max_results, the _items/_links/_meta envelope, If-Match/ETag, Eve's error envelope and Cerberus validation messages.
Package rest serves Mongo collections with the HTTP contract of Python Eve, so the gateways that call the Eve APIs keep working unchanged: where/sort/projection/page/max_results, the _items/_links/_meta envelope, If-Match/ETag, Eve's error envelope and Cerberus validation messages.
Package restpostgres implements a rest.Resource's storage contract against Postgres: the first (and, for now, only) package that imports both rest and platform/postgres, so neither of those needs to know the other exists.
Package restpostgres implements a rest.Resource's storage contract against Postgres: the first (and, for now, only) package that imports both rest and platform/postgres, so neither of those needs to know the other exists.
Package testkit has the helpers shared by the service tests: an isolated Mongo database, an Elasticsearch recorder, token signing and an HTTP client for handlers.
Package testkit has the helpers shared by the service tests: an isolated Mongo database, an Elasticsearch recorder, token signing and an HTTP client for handlers.

Jump to

Keyboard shortcuts

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