feat(core): initial implementation — launcher, logz, xerrors, valid
Introduces `code.nochebuena.dev/einherjar/core` — the foundational implementation module of the Einherjar framework. Provides four sub-packages that together cover every service's baseline needs: lifecycle management, structured logging, typed errors, and struct validation. - launcher: Launcher interface — three-phase managed lifecycle (OnInit → BeforeStart hooks → OnStart → OS signal wait → OnStop in reverse). Accepts lifecycle.Component and logging.Logger from contracts. Prints an ASCII art banner at startup (EINHERJAR_BANNER=off to suppress). Banner includes core version via runtime/debug.ReadBuildInfo() and a loaded-module list for every registered component that implements observability.Identifiable. Config struct with EINHERJAR_COMPONENT_STOP_TIMEOUT env tag (caarlos0/env syntax, default 15s). - logz: Logger implementation backed by log/slog. Returns contracts/logging.Logger. Detects errs.CodedError and errs.ContextualError (from contracts/errs) to enrich log records automatically — replaces the private duck-typed bridge from micro-lib. Context helpers: WithRequestID, WithField, WithFields, GetRequestID. Config struct with EINHERJAR_LOG_LEVEL (default INFO) and EINHERJAR_LOG_JSON (default false) env tags (caarlos0/env syntax); programmatic-only fields StaticArgs and Writer carry no tags. - xerrors: Typed error codes with context enrichment. Complete gRPC canonical set (16 codes) plus HTTP 410 ErrGone. Adds ErrOutOfRange, ErrAborted, ErrDataLoss over micro-lib. One convenience constructor per code. *Err declares compile-time satisfaction of errs.CodedError and errs.ContextualError. - valid: Struct validation wrapping go-playground/validator/v10. Validator interface + MessageProvider interface with full built-in tag coverage (~150 tags) in both DefaultMessages (English) and SpanishMessages (Spanish). Backend fully hidden; returns *xerrors.Err with ErrInvalidInput or ErrInternal. FieldLevel interface abstracts the backend's field-level access for custom validators. WithCustomValidator registers custom validation tags at construction time; OverrideProvider chains a tag→handler map with a fallback MessageProvider for custom tag messages without re-implementing built-ins. Compliance test enforces CT-6 (at most one exported TypeSpec per file via AST) and verifies behavioural correctness of all four sub-packages, including custom validator registration and OverrideProvider composition. Compile-time var _ assertions prove interface satisfaction. docs: ADR-001 (core module composition), ADR-002 (logz contracts/errs adoption), ADR-003 (Config naming convention and caarlos0/env tag standard)
This commit is contained in:
1
.gitea/CODEOWNERS
Normal file
1
.gitea/CODEOWNERS
Normal file
@@ -0,0 +1 @@
|
|||||||
|
* @einherjar/CoreDevelopers @einherjar/Agents
|
||||||
70
.gitea/pull_request_template.md
Normal file
70
.gitea/pull_request_template.md
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
## Summary
|
||||||
|
|
||||||
|
<!-- One or two sentences: what does this PR do and why? -->
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Type of change
|
||||||
|
|
||||||
|
- [ ] Bug fix — non-breaking change that resolves an issue
|
||||||
|
- [ ] New feature — non-breaking addition of functionality
|
||||||
|
- [ ] Breaking change — alters existing behavior or public API
|
||||||
|
- [ ] Documentation update
|
||||||
|
- [ ] Refactor — no functional change, no new API surface
|
||||||
|
- [ ] Test improvement
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Provide enough context for a reviewer who was not in the room:
|
||||||
|
- What problem does this solve?
|
||||||
|
- What approach did you choose, and why?
|
||||||
|
- Were there alternatives you considered and rejected?
|
||||||
|
- Any known limitations or follow-up work?
|
||||||
|
-->
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
- [ ] I added or updated tests that cover my changes
|
||||||
|
- [ ] All tests pass locally — `go test ./...`
|
||||||
|
- [ ] No formatting issues — `gofmt -l .` produces no output
|
||||||
|
- [ ] No vet warnings — `go vet ./...` is clean
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
|
||||||
|
- [ ] At most one exported type per non-test `.go` file (CT-6)
|
||||||
|
- [ ] No new external dependencies added without prior discussion in an issue
|
||||||
|
- [ ] Public API changes are reflected in `CHANGELOG.md`
|
||||||
|
- [ ] Breaking changes include a migration note in the PR description above
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contributor License Agreement
|
||||||
|
|
||||||
|
> **This PR will not be merged until the CLA comment is present.**
|
||||||
|
|
||||||
|
Before a Maintainer reviews your code, you must post the following text **as a comment on this PR** — not here in the description. PR description checkboxes can be silently toggled by anyone; a comment is a timestamped, author-attributed record that cannot be quietly removed.
|
||||||
|
|
||||||
|
**Copy and post this exact text as a PR comment:**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> I have read the Einherjar Contributor License Agreement (CLA.md) and I agree to all its terms.
|
||||||
|
> I confirm this Contribution is my original work. I grant the Maintainers the rights described
|
||||||
|
> therein, including the right to relicense, and I retain ownership of my copyright.
|
||||||
|
> This agreement covers all future Contributions I submit to any Einherjar repository under
|
||||||
|
> this account.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
First time contributing? Read [CLA.md](../CLA.md) for the full agreement before posting the comment.
|
||||||
|
|
||||||
|
If you are contributing on behalf of a company, an authorized representative of that company must post the comment.
|
||||||
|
|
||||||
|
<!-- Thank you for contributing to Einherjar. For those who come after. -->
|
||||||
38
.gitignore
vendored
Normal file
38
.gitignore
vendored
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# ── Release workflow helpers ──────────────────────────────────────────────────
|
||||||
|
COMMIT.md
|
||||||
|
PR.md
|
||||||
|
RELEASE.md
|
||||||
|
|
||||||
|
# ── Go build artifacts ────────────────────────────────────────────────────────
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
*.test
|
||||||
|
*.out
|
||||||
|
/dist/
|
||||||
|
/bin/
|
||||||
|
|
||||||
|
# ── Go workspace (local development only) ────────────────────────────────────
|
||||||
|
go.work
|
||||||
|
go.work.sum
|
||||||
|
|
||||||
|
# ── Dependency vendor directory ───────────────────────────────────────────────
|
||||||
|
vendor/
|
||||||
|
|
||||||
|
# ── Coverage output ───────────────────────────────────────────────────────────
|
||||||
|
coverage.out
|
||||||
|
coverage.html
|
||||||
|
*.coverprofile
|
||||||
|
|
||||||
|
# ── OS artifacts ─────────────────────────────────────────────────────────────
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# ── Editor artifacts ──────────────────────────────────────────────────────────
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
108
CHANGELOG.md
Normal file
108
CHANGELOG.md
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
# Changelog — einherjar/core
|
||||||
|
|
||||||
|
All notable changes to this module are documented here.
|
||||||
|
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||||
|
This module adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [1.0.0] — 2026-05-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
#### `launcher`
|
||||||
|
|
||||||
|
- `Launcher` interface — `Append`, `BeforeStart`, `Run`, `Shutdown`
|
||||||
|
- `New(logger logging.Logger, opts ...Options) Launcher` — constructs the lifecycle
|
||||||
|
orchestrator; takes `contracts/logging.Logger` (not the concrete `logz` type)
|
||||||
|
- `Hook` type (`func() error`) — assembly-phase callback registered via `BeforeStart`
|
||||||
|
- `Config` struct — `ComponentStopTimeout time.Duration` with `env:"EINHERJAR_COMPONENT_STOP_TIMEOUT" envDefault:"15s"` (`caarlos0/env` syntax)
|
||||||
|
- Startup banner — printed to stdout before any slog output; disabled via
|
||||||
|
`EINHERJAR_BANNER=off` or `EINHERJAR_BANNER=false`
|
||||||
|
- Components accepted as `lifecycle.Component` from `contracts` — not a locally
|
||||||
|
defined interface; any type that satisfies `contracts/lifecycle.Component` is
|
||||||
|
directly compatible
|
||||||
|
|
||||||
|
#### `logz`
|
||||||
|
|
||||||
|
- `Config` struct — `Level slog.Level`, `JSON bool`, `StaticArgs []any`, `Writer io.Writer`
|
||||||
|
- `Level` and `JSON` carry `env` and `envDefault` tags (`caarlos0/env` syntax); `StaticArgs` and `Writer` are programmatic-only fields without tags
|
||||||
|
- Env vars: `EINHERJAR_LOG_LEVEL` (default `INFO`), `EINHERJAR_LOG_JSON` (default `false`)
|
||||||
|
- `New(cfg Config) logging.Logger` — returns `contracts/logging.Logger`; the
|
||||||
|
concrete `slogLogger` struct is unexported
|
||||||
|
- Error enrichment — when the error passed to `Logger.Error` satisfies
|
||||||
|
`errs.CodedError` or `errs.ContextualError` (from `contracts/errs`), the
|
||||||
|
corresponding `error_code` field and context key-value pairs are automatically
|
||||||
|
appended to the log record; this replaces the private duck-typed bridge used in
|
||||||
|
micro-lib's `logz`
|
||||||
|
- Context helpers — `WithRequestID`, `GetRequestID`, `WithField`, `WithFields`
|
||||||
|
- `Logger.WithContext(ctx)` — extracts `request_id` and extra fields from context
|
||||||
|
and attaches them to every subsequent log record
|
||||||
|
|
||||||
|
#### `xerrors`
|
||||||
|
|
||||||
|
- `Code` type (stable string wire values, gRPC-aligned)
|
||||||
|
- **16 error code constants** — complete gRPC canonical set plus `ErrGone` (HTTP 410)
|
||||||
|
- New over micro-lib: `ErrOutOfRange` (gRPC OUT_OF_RANGE, HTTP 400),
|
||||||
|
`ErrAborted` (gRPC ABORTED, HTTP 409), `ErrDataLoss` (gRPC DATA_LOSS, HTTP 500)
|
||||||
|
- `Code.Description()` — human-readable description for each code
|
||||||
|
- `Err` struct — `code`, `message`, `err` (cause), `fields` (context), `platformCode`
|
||||||
|
- Base constructors: `New(code, message)`, `Wrap(code, message, err)`
|
||||||
|
- **16 convenience constructors** (one per code): `InvalidInput`, `OutOfRange`,
|
||||||
|
`Unauthorized`, `PermissionDenied`, `NotFound`, `AlreadyExists`, `Aborted`,
|
||||||
|
`Gone`, `PreconditionFailed`, `RateLimited`, `Cancelled`, `Internal`, `DataLoss`,
|
||||||
|
`NotImplemented`, `Unavailable`, `DeadlineExceeded`
|
||||||
|
- Builder methods: `WithContext`, `WithError`, `WithPlatformCode`
|
||||||
|
- Accessors: `Code()`, `Message()`, `Fields()`, `PlatformCode()`, `Detailed()`
|
||||||
|
- Standard interfaces: `error`, `Unwrap`, `json.Marshaler`
|
||||||
|
- Compile-time assertions: `var _ errs.CodedError = (*Err)(nil)` and
|
||||||
|
`var _ errs.ContextualError = (*Err)(nil)` — formalises the duck-type bridge
|
||||||
|
from micro-lib into an explicit, verifiable contract
|
||||||
|
|
||||||
|
#### `valid`
|
||||||
|
|
||||||
|
- `Validator` interface — `Struct(v any) error`
|
||||||
|
- `New(opts ...Option) Validator` — constructs a validator backed by
|
||||||
|
`go-playground/validator/v10` (backend is hidden; never exposed in the public API)
|
||||||
|
- `MessageProvider` interface — `Message(field, tag, param string) string`
|
||||||
|
- `DefaultMessages` — built-in English message provider
|
||||||
|
- `SpanishMessages` — opt-in Spanish message provider
|
||||||
|
- `Option` type and `WithMessageProvider(mp MessageProvider) Option`
|
||||||
|
- `FieldLevel` interface — passed to custom validator functions; exposes `Field() reflect.Value`, `Param() string`, `FieldName() string`; go-playground backend never visible
|
||||||
|
- `WithCustomValidator(tag string, fn func(FieldLevel) bool) Option` — registers a custom validation tag at construction time; panics on empty or conflicting tag
|
||||||
|
- `OverrideProvider(handlers map[string]func(field, param string) string, base MessageProvider) MessageProvider` — composes a tag→message handler map with a fallback; use for custom tag messages without re-implementing built-ins
|
||||||
|
- **Full built-in tag coverage** in `DefaultMessages` and `SpanishMessages` — all go-playground/validator tags have specific messages (fields, network, strings, format, comparisons, other; ~150 tags total)
|
||||||
|
- Field names in error context prefer the json struct tag, falling back to the Go
|
||||||
|
field name
|
||||||
|
- Error codes: `ErrInvalidInput` for constraint failures, `ErrInternal` for
|
||||||
|
non-struct arguments — both returned as `*xerrors.Err`
|
||||||
|
|
||||||
|
### Design Notes
|
||||||
|
|
||||||
|
1. **Contracts as the source of truth.** `launcher` accepts `lifecycle.Component`
|
||||||
|
and `logging.Logger` from `contracts`. It does not define its own lifecycle
|
||||||
|
interface. Any type that satisfies the contracts interface is directly compatible —
|
||||||
|
no adapters needed.
|
||||||
|
|
||||||
|
2. **Duck typing replaced by explicit interfaces.** micro-lib's `logz` detected
|
||||||
|
enrichable errors via private `errorWithCode`/`errorWithContext` interfaces.
|
||||||
|
`core/logz` detects them via `contracts/errs.CodedError` and `contracts/errs.ContextualError`.
|
||||||
|
The decoupling (logz does not import xerrors) is preserved; the contract is now
|
||||||
|
visible. See [ADR-002](docs/adr/ADR-002-logz-contracts-errs.md).
|
||||||
|
|
||||||
|
3. **Complete gRPC error code set.** micro-lib's `xerrors` had 13 codes. `core/xerrors`
|
||||||
|
adds the three missing gRPC codes (`OUT_OF_RANGE`, `ABORTED`, `DATA_LOSS`) and
|
||||||
|
provides a named convenience constructor for every code — `New()` and `Wrap()` are
|
||||||
|
reserved for edge cases.
|
||||||
|
|
||||||
|
4. **One module, four sub-packages.** The consolidation eliminates four-way version
|
||||||
|
coordination for a set of packages that always ship and upgrade together.
|
||||||
|
See [ADR-001](docs/adr/ADR-001-core-module-composition.md).
|
||||||
|
|
||||||
|
5. **Startup banner.** The launcher prints an ASCII art banner to stdout before any
|
||||||
|
structured log output. It is disabled via `EINHERJAR_BANNER=off`, not via code
|
||||||
|
changes, so production deployments can suppress it without modifying the service.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
[1.0.0]: https://code.nochebuena.dev/einherjar/core/releases/tag/v1.0.0
|
||||||
90
CLA.md
Normal file
90
CLA.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# Contributor License Agreement
|
||||||
|
|
||||||
|
By contributing to any Einherjar repository, you agree to the terms of this Contributor License Agreement ("Agreement"). Please read it carefully before submitting your first Pull Request.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Definitions
|
||||||
|
|
||||||
|
| Term | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| **You** | The individual or legal entity submitting a Contribution |
|
||||||
|
| **Contribution** | Any original work — source code, documentation, tests, configuration — submitted to an Einherjar repository |
|
||||||
|
| **Project** | The Einherjar framework and all repositories under `code.nochebuena.dev/einherjar/` |
|
||||||
|
| **Maintainers** | The individuals responsible for maintaining the Project |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. You Retain Ownership
|
||||||
|
|
||||||
|
This Agreement does **not** transfer your copyright to the Maintainers. You remain the legal owner of your Contribution. What you grant here is a broad license to use it — not ownership of it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Copyright License Grant
|
||||||
|
|
||||||
|
You grant the Maintainers and all recipients of the Project a **perpetual, worldwide, non-exclusive, royalty-free, irrevocable** license to:
|
||||||
|
|
||||||
|
- Reproduce, modify, and create derivative works of your Contribution
|
||||||
|
- Publicly display and perform your Contribution
|
||||||
|
- Distribute your Contribution and derivative works, in source or compiled form, under any terms
|
||||||
|
- Sublicense the above rights to third parties
|
||||||
|
- **Relicense** your Contribution under a different open-source or commercial license at the Maintainers' sole discretion
|
||||||
|
|
||||||
|
The Maintainers commit to keeping the Project available under at least one OSI-approved open-source license at all times.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Patent License Grant
|
||||||
|
|
||||||
|
You grant the Maintainers and all recipients of the Project a **perpetual, worldwide, non-exclusive, royalty-free, irrevocable** patent license to make, use, sell, offer for sale, import, and distribute your Contribution — limited to patent claims you own or control that are necessarily infringed by your Contribution alone, or in combination with the Project to which you submitted it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Your Representations
|
||||||
|
|
||||||
|
By submitting a Contribution, you confirm that:
|
||||||
|
|
||||||
|
1. **Original work.** The Contribution is your original work, or you have the legal right to submit it under these terms.
|
||||||
|
2. **No infringement.** To your knowledge, the Contribution does not infringe any third-party intellectual property rights, including patents, copyrights, and trade secrets.
|
||||||
|
3. **Employer rights.** If your employer holds rights over intellectual property you create, you have obtained written permission to submit the Contribution on behalf of that employer, or your employer has explicitly waived such rights for contributions to open-source projects.
|
||||||
|
4. **No warranty implied.** You understand that your Contribution may or may not be included in the Project, and the Maintainers are under no obligation to use it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. No Support Obligation
|
||||||
|
|
||||||
|
You are not required to provide maintenance, support, or updates for your Contributions. They are accepted **"as-is"**, without any warranty of fitness for a particular purpose or correctness.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. How to Sign
|
||||||
|
|
||||||
|
Consent is given by **posting a comment** on your Pull Request with the following exact text:
|
||||||
|
|
||||||
|
```
|
||||||
|
I have read the Einherjar Contributor License Agreement (CLA.md) and I agree to all its terms.
|
||||||
|
I confirm this Contribution is my original work. I grant the Maintainers the rights described
|
||||||
|
therein, including the right to relicense, and I retain ownership of my copyright.
|
||||||
|
This agreement covers all future Contributions I submit to any Einherjar repository under
|
||||||
|
this account.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why a comment and not a checkbox?**
|
||||||
|
PR description checkboxes can be silently toggled on and off by anyone with write access to the branch at any time. A comment creates a timestamped, author-attributed record in the PR activity log — it cannot be quietly retracted. If a comment is deleted, the deletion itself is visible in the activity log.
|
||||||
|
|
||||||
|
No handwritten or electronic signature is required beyond the comment above. A Maintainer will verify the comment before merging. PRs without the comment will not be merged.
|
||||||
|
|
||||||
|
If you are contributing on behalf of a company or organization, ensure that an authorized representative of that entity has reviewed and accepted these terms before submitting. The comment must be posted by the account that owns the Contribution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Governing Terms
|
||||||
|
|
||||||
|
This Agreement is intended to be simple and broadly fair. It follows the model established by widely adopted CLAs from the Apache Software Foundation, Google, and MongoDB — granting the Project the flexibility to evolve while fully preserving your ownership of what you wrote.
|
||||||
|
|
||||||
|
If any provision of this Agreement is found unenforceable, the remaining provisions continue in full effect.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*For those who come after. — The Einherjar Maintainers*
|
||||||
247
CONTRIBUTING.md
Normal file
247
CONTRIBUTING.md
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
# Contributing to Einherjar
|
||||||
|
|
||||||
|
Thank you for your interest in contributing to Einherjar. This document explains everything you need to know before sending your first Pull Request.
|
||||||
|
|
||||||
|
Einherjar is developed and maintained by **NOCHEBUENADEV**, the trade name of its founder operating as a *Persona Física con Actividad Empresarial* (PFAE) under Mexican law. Contributions are welcome and valued — but they are accepted under the terms described here, so please read this document fully before you begin.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Before You Start](#1-before-you-start)
|
||||||
|
2. [Legal: CLA and Copyright](#2-legal-cla-and-copyright)
|
||||||
|
3. [Development Setup](#3-development-setup)
|
||||||
|
4. [Code Standards](#4-code-standards)
|
||||||
|
5. [Commit Messages](#5-commit-messages)
|
||||||
|
6. [Submitting a Pull Request](#6-submitting-a-pull-request)
|
||||||
|
7. [Reporting Bugs](#7-reporting-bugs)
|
||||||
|
8. [Requesting Features](#8-requesting-features)
|
||||||
|
9. [What Gets Accepted](#9-what-gets-accepted)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Before You Start
|
||||||
|
|
||||||
|
**Open an issue first for anything non-trivial.**
|
||||||
|
|
||||||
|
Before you write a line of code, open an issue describing what you want to change and why. This protects your time: a change that seems straightforward may conflict with a planned refactor, an architectural decision, or the project's direction. Getting alignment before coding means your PR will not be rejected for reasons unrelated to its quality.
|
||||||
|
|
||||||
|
Exceptions where you can skip the issue:
|
||||||
|
- Typo or documentation-only fix
|
||||||
|
- Test coverage improvement for existing behavior
|
||||||
|
- Trivially obvious bug with a clear, contained fix
|
||||||
|
|
||||||
|
**Do not submit a PR that changes the public API of any module without prior discussion.** Every Einherjar module has a stability contract. Breaking changes require a major version bump and coordinated updates across dependent modules.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Legal: CLA and Copyright
|
||||||
|
|
||||||
|
### Contributor License Agreement
|
||||||
|
|
||||||
|
Before your first PR can be merged, you must sign the Contributor License Agreement by **posting a specific comment** on your Pull Request. The required comment text and full instructions are in [CLA.md](CLA.md).
|
||||||
|
|
||||||
|
> Checkboxes in PR descriptions are not used for CLA consent — they can be silently toggled by anyone. A comment is a timestamped, author-attributed record.
|
||||||
|
|
||||||
|
### Copyright
|
||||||
|
|
||||||
|
All original code in Einherjar is copyright **NOCHEBUENADEV**. NOCHEBUENADEV is the registered trade name of its founder, a natural person operating under the Mexican *Persona Física con Actividad Empresarial* (PFAE) regime.
|
||||||
|
|
||||||
|
When you contribute, you retain ownership of what you wrote. By signing the CLA you grant NOCHEBUENADEV a perpetual, irrevocable, worldwide license to use, modify, sublicense, and redistribute your Contribution — including the right to relicense it. See [CLA.md](CLA.md) for the full terms.
|
||||||
|
|
||||||
|
### License
|
||||||
|
|
||||||
|
Einherjar is licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0). Your Contributions will be distributed under the same license unless the Maintainers exercise their relicensing rights under the CLA.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Development Setup
|
||||||
|
|
||||||
|
Einherjar uses a Go workspace (`go.work`) that spans all modules. You do not need to `go get` anything — local replacements are wired automatically.
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Go 1.26+
|
||||||
|
- Git
|
||||||
|
|
||||||
|
### Clone and initialize
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://code.nochebuena.dev/einherjar/<module-name>
|
||||||
|
cd <module-name>
|
||||||
|
|
||||||
|
# If working across multiple modules, clone the workspace root instead
|
||||||
|
# and all modules will resolve from disk via go.work.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Verify your setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build ./... # must compile clean
|
||||||
|
go vet ./... # no warnings
|
||||||
|
go test ./... # all tests pass
|
||||||
|
gofmt -l . # no output (no unformatted files)
|
||||||
|
```
|
||||||
|
|
||||||
|
All four commands must produce clean output before a PR will be reviewed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Code Standards
|
||||||
|
|
||||||
|
These are non-negotiable. Every PR is checked against them.
|
||||||
|
|
||||||
|
### One exported type per file (CT-6)
|
||||||
|
|
||||||
|
Each non-test `.go` file may contain **at most one exported TypeSpec** (type, struct, or interface declaration). Unexported helpers, constants, and functions may coexist in the same file. `_test.go` files are exempt.
|
||||||
|
|
||||||
|
This rule exists to keep the codebase navigable: a developer who knows the type name can immediately predict the file name.
|
||||||
|
|
||||||
|
```
|
||||||
|
provider.go ← type Provider interface { ... } ✓ one exported type
|
||||||
|
component.go ← type Component interface { ... } ✓ one exported type
|
||||||
|
new.go ← func New(...) + unexported impl ✓ zero exported types
|
||||||
|
```
|
||||||
|
|
||||||
|
### Formatting
|
||||||
|
|
||||||
|
All code must be formatted with `gofmt`. No exceptions. If `gofmt -l .` produces output, the PR will not be merged.
|
||||||
|
|
||||||
|
Do not configure your editor to use `goimports` as a replacement — it may add import groups that diverge from the project style. Use `gofmt` + manual import management.
|
||||||
|
|
||||||
|
### Naming conventions
|
||||||
|
|
||||||
|
- Follow standard Go naming: `CamelCase` for exported, `camelCase` for unexported.
|
||||||
|
- Interfaces that represent a capability are named with an agent noun: `Provider`, `Sender`, `Checkable`.
|
||||||
|
- Interfaces that represent a full component are named `Component`.
|
||||||
|
- Config structs are named `Config`. One config struct per module root.
|
||||||
|
- Constructors are named `New` (main) or `NewXxx` (adapters and variants).
|
||||||
|
|
||||||
|
### Error handling
|
||||||
|
|
||||||
|
- Use `core/xerrors` for all errors returned from public API. Never return raw `errors.New` or `fmt.Errorf` from exported functions.
|
||||||
|
- Error codes must map to the gRPC canonical set defined in `xerrors`. If you need a new code, open an issue first.
|
||||||
|
- Do not swallow errors silently. Log at the appropriate level or return them.
|
||||||
|
|
||||||
|
### No comments unless necessary
|
||||||
|
|
||||||
|
Do not add comments that restate what the code already says. Only add a comment when the **why** is non-obvious: a hidden constraint, a subtle invariant, a workaround for a known upstream bug. If removing the comment would not confuse a future reader, do not write it.
|
||||||
|
|
||||||
|
### Dependencies
|
||||||
|
|
||||||
|
Do not add new external dependencies without opening an issue and getting explicit approval first. Einherjar modules are deliberately lean. Every new dependency increases the blast radius for downstream consumers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Commit Messages
|
||||||
|
|
||||||
|
Follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:
|
||||||
|
|
||||||
|
```
|
||||||
|
<type>(<scope>): <short description>
|
||||||
|
|
||||||
|
[optional body]
|
||||||
|
```
|
||||||
|
|
||||||
|
| Type | When to use |
|
||||||
|
|---|---|
|
||||||
|
| `feat` | New exported function, type, or behavior |
|
||||||
|
| `fix` | Bug fix in existing behavior |
|
||||||
|
| `docs` | Documentation only |
|
||||||
|
| `test` | Tests only, no production code change |
|
||||||
|
| `refactor` | Code restructure with no behavior change |
|
||||||
|
| `chore` | Build system, CI, dependency updates |
|
||||||
|
|
||||||
|
**Scope** is the module name without the `einherjar/` prefix: `core`, `web`, `db-postgres`, `cache-valkey`, etc.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
```
|
||||||
|
feat(cache-valkey): add IncrWithTTL for atomic fixed-window counters
|
||||||
|
fix(db-postgres): handle pgconn deadline exceeded as ErrDeadlineExceeded
|
||||||
|
docs(web): document rate limiter fail-open behavior
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep the subject line under 72 characters. Write in the imperative mood ("add", "fix", "remove" — not "added", "fixes", "removed").
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Submitting a Pull Request
|
||||||
|
|
||||||
|
1. **Open an issue first** (see §1) unless the change is trivial.
|
||||||
|
2. Fork the repository and create a branch from `main`:
|
||||||
|
```bash
|
||||||
|
git checkout -b feat/your-feature-name
|
||||||
|
```
|
||||||
|
3. Make your changes following the standards in §4.
|
||||||
|
4. Ensure all verification commands pass (§3).
|
||||||
|
5. Open the PR against `main` using the provided PR template.
|
||||||
|
6. **Post the CLA comment** on the PR before requesting review (see §2 and [CLA.md](CLA.md)).
|
||||||
|
7. Respond to review feedback. Keep the review cycle short by addressing all comments before re-requesting review.
|
||||||
|
|
||||||
|
### Branch naming
|
||||||
|
|
||||||
|
| Prefix | Use for |
|
||||||
|
|---|---|
|
||||||
|
| `feat/` | New features |
|
||||||
|
| `fix/` | Bug fixes |
|
||||||
|
| `docs/` | Documentation changes |
|
||||||
|
| `test/` | Test additions or improvements |
|
||||||
|
| `refactor/` | Refactors without behavior change |
|
||||||
|
|
||||||
|
### PR size
|
||||||
|
|
||||||
|
Keep PRs focused. A PR that does one thing is easier to review, faster to merge, and safer to revert if needed. If your change naturally spans multiple concerns, split it into multiple PRs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Reporting Bugs
|
||||||
|
|
||||||
|
Open an issue with the following information:
|
||||||
|
|
||||||
|
- **Module** affected (`einherjar/db-postgres`, `einherjar/web`, etc.)
|
||||||
|
- **Go version** (`go version`)
|
||||||
|
- **Minimal reproduction** — the smallest code snippet that demonstrates the problem
|
||||||
|
- **Expected behavior** vs **actual behavior**
|
||||||
|
- **Error output** if applicable (sanitize any credentials or sensitive data)
|
||||||
|
|
||||||
|
Do not open a PR to fix a bug without first opening an issue. The bug may be intentional behavior, already fixed on `main`, or caused by something outside the module.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Requesting Features
|
||||||
|
|
||||||
|
Open an issue with:
|
||||||
|
|
||||||
|
- **What** you want to add and **why** it belongs in the framework (not in application code)
|
||||||
|
- **Which module** it affects, or whether it requires a new module
|
||||||
|
- **API sketch** — what the interface, function signature, or config field would look like
|
||||||
|
- **Alternative approaches** you considered
|
||||||
|
|
||||||
|
Feature requests that add a new external dependency, change a public interface, or cross module boundaries require longer discussion before approval.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. What Gets Accepted
|
||||||
|
|
||||||
|
Einherjar is a **focused framework**. It covers a specific, well-defined set of infrastructure concerns. Contributions that fall outside that scope — however well-written — will not be merged.
|
||||||
|
|
||||||
|
What fits:
|
||||||
|
- Bug fixes in existing behavior
|
||||||
|
- Performance improvements with benchmarks
|
||||||
|
- Missing error mappings for existing drivers
|
||||||
|
- Documentation improvements and example corrections
|
||||||
|
- Test coverage for untested edge cases
|
||||||
|
|
||||||
|
What does not fit without prior architectural agreement:
|
||||||
|
- New modules (open an issue first)
|
||||||
|
- New external dependencies
|
||||||
|
- Changes to public interfaces in any module
|
||||||
|
- Features that belong in application code rather than the framework
|
||||||
|
|
||||||
|
If you are unsure, open an issue and ask. It costs nothing and saves everyone time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Einherjar was built for those who come after. Contributions that hold to that standard — clear, documented, tested, designed for the developer who was never in the room — are always welcome.*
|
||||||
|
|
||||||
|
— **NOCHEBUENADEV**
|
||||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published
|
||||||
|
by the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
245
README.md
Normal file
245
README.md
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
# einherjar/core
|
||||||
|
|
||||||
|
[](https://code.nochebuena.dev/einherjar/core)
|
||||||
|
[](LICENSE)
|
||||||
|
[](https://go.dev)
|
||||||
|
|
||||||
|
> The chosen warriors do not choose their weapons. They forge them.
|
||||||
|
|
||||||
|
`code.nochebuena.dev/einherjar/core` is the foundational implementation module of the
|
||||||
|
Einherjar framework. It sits directly above `contracts` in the dependency graph and
|
||||||
|
provides the concrete tools every service needs before anything else can start:
|
||||||
|
a lifecycle runner, a structured logger, typed errors, and struct validation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What Is Einherjar?
|
||||||
|
|
||||||
|
In Norse mythology, the Einherjar are the chosen warriors of Valhalla — selected not
|
||||||
|
for glory, but to be ready for what comes after. They train. They prepare. They build
|
||||||
|
the capability that others will rely on.
|
||||||
|
|
||||||
|
This framework is named for that purpose. Every module is a piece of that preparation:
|
||||||
|
built carefully, documented for those who were never in the room, and designed to hold
|
||||||
|
under pressure.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sub-packages
|
||||||
|
|
||||||
|
| Package | Import path | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `launcher` | `.../core/launcher` | Application lifecycle — init, start, shutdown |
|
||||||
|
| `logz` | `.../core/logz` | Structured, leveled logging via `log/slog` |
|
||||||
|
| `xerrors` | `.../core/xerrors` | Typed error codes with context enrichment |
|
||||||
|
| `valid` | `.../core/valid` | Struct validation with pluggable i18n messages |
|
||||||
|
|
||||||
|
All four are in one module because they ship together in every Einherjar service.
|
||||||
|
See [ADR-001](docs/adr/ADR-001-core-module-composition.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Launcher
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"code.nochebuena.dev/einherjar/core/launcher"
|
||||||
|
"code.nochebuena.dev/einherjar/core/logz"
|
||||||
|
)
|
||||||
|
|
||||||
|
logger := logz.New(logz.Config{JSON: true, StaticArgs: []any{"service", "api"}})
|
||||||
|
|
||||||
|
lc := launcher.New(logger)
|
||||||
|
lc.Append(db, cache, server)
|
||||||
|
lc.BeforeStart(func() error {
|
||||||
|
return server.RegisterRoutes(db, cache)
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := lc.Run(); err != nil {
|
||||||
|
logger.Error("launcher failed", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Environment variables (uses `caarlos0/env` tag syntax — application supplies the loader):
|
||||||
|
|
||||||
|
| Variable | Default | Effect |
|
||||||
|
|---|---|---|
|
||||||
|
| `EINHERJAR_BANNER` | _(on)_ | Set to `off` or `false` to suppress the startup banner |
|
||||||
|
| `EINHERJAR_COMPONENT_STOP_TIMEOUT` | `15s` | Maximum time per component `OnStop` |
|
||||||
|
|
||||||
|
### Logger
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "code.nochebuena.dev/einherjar/core/logz"
|
||||||
|
|
||||||
|
logger := logz.New(logz.Config{Level: slog.LevelDebug, JSON: true})
|
||||||
|
|
||||||
|
// Attach request context in middleware
|
||||||
|
ctx = logz.WithRequestID(ctx, requestID)
|
||||||
|
ctx = logz.WithField(ctx, "user_id", userID)
|
||||||
|
|
||||||
|
// Enrich logger from context in handlers
|
||||||
|
reqLogger := logger.WithContext(ctx)
|
||||||
|
reqLogger.Info("handling request", "path", r.URL.Path)
|
||||||
|
|
||||||
|
// Error enrichment is automatic — no extra code needed
|
||||||
|
reqLogger.Error("query failed", err) // appends error_code and context fields
|
||||||
|
```
|
||||||
|
|
||||||
|
Environment variables:
|
||||||
|
|
||||||
|
| Variable | Default | Effect |
|
||||||
|
|---|---|---|
|
||||||
|
| `EINHERJAR_LOG_LEVEL` | `INFO` | Minimum log level (`DEBUG`, `INFO`, `WARN`, `ERROR`) |
|
||||||
|
| `EINHERJAR_LOG_JSON` | `false` | JSON output when `true` |
|
||||||
|
|
||||||
|
### Errors
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "code.nochebuena.dev/einherjar/core/xerrors"
|
||||||
|
|
||||||
|
// Named constructors for common cases
|
||||||
|
err := xerrors.NotFound("user %s not found", userID)
|
||||||
|
err := xerrors.InvalidInput("email is required")
|
||||||
|
err := xerrors.Aborted("order modified by another session")
|
||||||
|
|
||||||
|
// Builder pattern for structured context
|
||||||
|
err := xerrors.New(xerrors.ErrInvalidInput, "validation failed").
|
||||||
|
WithContext("field", "email").
|
||||||
|
WithContext("rule", "required").
|
||||||
|
WithError(cause)
|
||||||
|
|
||||||
|
// Inspecting errors
|
||||||
|
var e *xerrors.Err
|
||||||
|
if errors.As(err, &e) {
|
||||||
|
switch e.Code() {
|
||||||
|
case xerrors.ErrNotFound: // HTTP 404
|
||||||
|
case xerrors.ErrUnauthorized: // HTTP 401
|
||||||
|
case xerrors.ErrInvalidInput: // HTTP 400
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Validation
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "code.nochebuena.dev/einherjar/core/valid"
|
||||||
|
|
||||||
|
type CreateUserReq struct {
|
||||||
|
Email string `json:"email" validate:"required,email"`
|
||||||
|
Age int `json:"age" validate:"gte=18"`
|
||||||
|
}
|
||||||
|
|
||||||
|
v := valid.New() // English messages
|
||||||
|
// v := valid.New(valid.WithMessageProvider(valid.SpanishMessages))
|
||||||
|
|
||||||
|
if err := v.Struct(req); err != nil {
|
||||||
|
var xe *xerrors.Err
|
||||||
|
errors.As(err, &xe)
|
||||||
|
// xe.Code() == xerrors.ErrInvalidInput
|
||||||
|
// xe.Fields() == {"field": "email", "tag": "required"}
|
||||||
|
// xe.Message() == "field 'email' is required"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
All go-playground/validator built-in tags have specific messages in both `DefaultMessages`
|
||||||
|
and `SpanishMessages`. The generic fallback only fires for unknown tags.
|
||||||
|
|
||||||
|
#### Custom validators
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
v := valid.New(
|
||||||
|
valid.WithCustomValidator("nohttp", func(fl valid.FieldLevel) bool {
|
||||||
|
return !strings.HasPrefix(fl.Field().String(), "http://")
|
||||||
|
}),
|
||||||
|
valid.WithMessageProvider(valid.OverrideProvider(
|
||||||
|
map[string]func(field, param string) string{
|
||||||
|
"nohttp": func(field, _ string) string {
|
||||||
|
return fmt.Sprintf("field '%s' must not use http://", field)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
valid.DefaultMessages,
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
`OverrideProvider` chains a tag→message map with a fallback provider, so custom tag
|
||||||
|
messages are handled without re-implementing all built-ins.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error Codes
|
||||||
|
|
||||||
|
`xerrors` provides the full gRPC canonical error code set plus HTTP 410 (`ErrGone`):
|
||||||
|
|
||||||
|
| Constant | Wire value | HTTP | When to use |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `ErrInvalidInput` | `INVALID_ARGUMENT` | 400 | Malformed or invalid request data |
|
||||||
|
| `ErrOutOfRange` | `OUT_OF_RANGE` | 400 | Valid value but outside accepted bounds |
|
||||||
|
| `ErrUnauthorized` | `UNAUTHENTICATED` | 401 | Missing or invalid credentials |
|
||||||
|
| `ErrPermissionDenied` | `PERMISSION_DENIED` | 403 | Authenticated but not authorised |
|
||||||
|
| `ErrNotFound` | `NOT_FOUND` | 404 | Resource does not exist |
|
||||||
|
| `ErrAlreadyExists` | `ALREADY_EXISTS` | 409 | Creation conflict (duplicate) |
|
||||||
|
| `ErrAborted` | `ABORTED` | 409 | Concurrent modification; retry may succeed |
|
||||||
|
| `ErrGone` | `GONE` | 410 | Resource permanently deleted |
|
||||||
|
| `ErrPreconditionFailed` | `FAILED_PRECONDITION` | 412 | Business rule blocks the operation |
|
||||||
|
| `ErrRateLimited` | `RESOURCE_EXHAUSTED` | 429 | Rate limit or quota exceeded |
|
||||||
|
| `ErrCancelled` | `CANCELLED` | 499 | Request cancelled by the caller |
|
||||||
|
| `ErrInternal` | `INTERNAL` | 500 | Unexpected server-side failure |
|
||||||
|
| `ErrDataLoss` | `DATA_LOSS` | 500 | Unrecoverable data corruption |
|
||||||
|
| `ErrNotImplemented` | `UNIMPLEMENTED` | 501 | Operation not implemented |
|
||||||
|
| `ErrUnavailable` | `UNAVAILABLE` | 503 | Service temporarily unavailable |
|
||||||
|
| `ErrDeadlineExceeded` | `DEADLINE_EXCEEDED` | 504 | Operation timed out |
|
||||||
|
|
||||||
|
Wire values are stable across versions and safe to persist, send over the network,
|
||||||
|
or switch on in client code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependency Rules
|
||||||
|
|
||||||
|
```
|
||||||
|
contracts (zero dependencies)
|
||||||
|
↑
|
||||||
|
core (depends on contracts only)
|
||||||
|
↑
|
||||||
|
starters (depend on core + contracts)
|
||||||
|
↑
|
||||||
|
your app
|
||||||
|
```
|
||||||
|
|
||||||
|
`core` imports `contracts`. Nothing above `core` in this chain may import `core`
|
||||||
|
directly — they depend on starters, which compose core's sub-packages behind
|
||||||
|
framework-specific APIs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd core/
|
||||||
|
go build ./... # must compile clean
|
||||||
|
go vet ./... # no warnings
|
||||||
|
go test ./... # structural + behavioural compliance passes
|
||||||
|
gofmt -l . # no output
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Decisions
|
||||||
|
|
||||||
|
| ADR | Title |
|
||||||
|
|---|---|
|
||||||
|
| [ADR-001](docs/adr/ADR-001-core-module-composition.md) | Four sub-packages in one Go module |
|
||||||
|
| [ADR-002](docs/adr/ADR-002-logz-contracts-errs.md) | logz adopts contracts/errs instead of private duck typing |
|
||||||
|
| [ADR-003](docs/adr/ADR-003-config-env-tags.md) | Config naming convention and caarlos0/env tag standard |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> *They were not chosen because they were the strongest.*
|
||||||
|
> *They were chosen because they understood what they were building toward.*
|
||||||
371
compliance_test.go
Normal file
371
compliance_test.go
Normal file
@@ -0,0 +1,371 @@
|
|||||||
|
package core_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/errs"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/lifecycle"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||||
|
"code.nochebuena.dev/einherjar/core/launcher"
|
||||||
|
"code.nochebuena.dev/einherjar/core/logz"
|
||||||
|
"code.nochebuena.dev/einherjar/core/valid"
|
||||||
|
"code.nochebuena.dev/einherjar/core/xerrors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ── Compile-time interface satisfaction ──────────────────────────────────────
|
||||||
|
|
||||||
|
var _ logging.Logger = logz.New(logz.Config{})
|
||||||
|
var _ errs.CodedError = (*xerrors.Err)(nil)
|
||||||
|
var _ errs.ContextualError = (*xerrors.Err)(nil)
|
||||||
|
var _ valid.Validator = valid.New()
|
||||||
|
var _ valid.MessageProvider = valid.DefaultMessages
|
||||||
|
var _ valid.MessageProvider = valid.SpanishMessages
|
||||||
|
|
||||||
|
// ── Structural: at most one exported TypeSpec per file ────────────────────────
|
||||||
|
|
||||||
|
func TestAtMostOneExportedTypePerFile(t *testing.T) {
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
err := filepath.WalkDir(".", func(path string, d os.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if d.IsDir() && (d.Name() == ".git" || d.Name() == "vendor") {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(path, ".go") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(path, "_test.go") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if filepath.Base(path) == "doc.go" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
f, parseErr := parser.ParseFile(fset, path, nil, 0)
|
||||||
|
if parseErr != nil {
|
||||||
|
t.Errorf("%s: parse error: %v", path, parseErr)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
count := countExportedTypes(f)
|
||||||
|
if count > 1 {
|
||||||
|
t.Errorf("%s: has %d exported type declarations; want at most 1", path, count)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("walk error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func countExportedTypes(f *ast.File) int {
|
||||||
|
count := 0
|
||||||
|
for _, decl := range f.Decls {
|
||||||
|
genDecl, ok := decl.(*ast.GenDecl)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, spec := range genDecl.Specs {
|
||||||
|
ts, ok := spec.(*ast.TypeSpec)
|
||||||
|
if ok && ts.Name.IsExported() {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── launcher ─────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
type mockComponent struct {
|
||||||
|
initCalls *[]string
|
||||||
|
startCalls *[]string
|
||||||
|
stopCalls *[]string
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockComponent) OnInit() error { *m.initCalls = append(*m.initCalls, m.name); return nil }
|
||||||
|
func (m *mockComponent) OnStart() error { *m.startCalls = append(*m.startCalls, m.name); return nil }
|
||||||
|
func (m *mockComponent) OnStop() error { *m.stopCalls = append(*m.stopCalls, m.name); return nil }
|
||||||
|
|
||||||
|
var _ lifecycle.Component = (*mockComponent)(nil)
|
||||||
|
|
||||||
|
func TestLauncherLifecycleOrder(t *testing.T) {
|
||||||
|
var inits, starts, stops []string
|
||||||
|
|
||||||
|
c1 := &mockComponent{initCalls: &inits, startCalls: &starts, stopCalls: &stops, name: "c1"}
|
||||||
|
c2 := &mockComponent{initCalls: &inits, startCalls: &starts, stopCalls: &stops, name: "c2"}
|
||||||
|
|
||||||
|
logger := logz.New(logz.Config{Writer: &bytes.Buffer{}})
|
||||||
|
lc := launcher.New(logger)
|
||||||
|
lc.Append(c1, c2)
|
||||||
|
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- lc.Run() }()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 3e9)
|
||||||
|
defer cancel()
|
||||||
|
if err := lc.Shutdown(ctx); err != nil {
|
||||||
|
t.Fatalf("Shutdown: %v", err)
|
||||||
|
}
|
||||||
|
if err := <-done; err != nil {
|
||||||
|
t.Fatalf("Run: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(inits) != 2 || inits[0] != "c1" || inits[1] != "c2" {
|
||||||
|
t.Errorf("OnInit order: got %v, want [c1 c2]", inits)
|
||||||
|
}
|
||||||
|
if len(starts) != 2 || starts[0] != "c1" || starts[1] != "c2" {
|
||||||
|
t.Errorf("OnStart order: got %v, want [c1 c2]", starts)
|
||||||
|
}
|
||||||
|
// OnStop must run in reverse order
|
||||||
|
if len(stops) != 2 || stops[0] != "c2" || stops[1] != "c1" {
|
||||||
|
t.Errorf("OnStop order: got %v, want [c2 c1]", stops)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── logz ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestLogzErrorEnrichment(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
logger := logz.New(logz.Config{JSON: true, Writer: &buf})
|
||||||
|
|
||||||
|
err := xerrors.New(xerrors.ErrNotFound, "thing missing").
|
||||||
|
WithContext("id", "abc123")
|
||||||
|
|
||||||
|
logger.Error("lookup failed", err)
|
||||||
|
|
||||||
|
out := buf.String()
|
||||||
|
if !strings.Contains(out, "NOT_FOUND") {
|
||||||
|
t.Errorf("expected error_code=NOT_FOUND in output: %s", out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "abc123") {
|
||||||
|
t.Errorf("expected context field id=abc123 in output: %s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogzContextEnrichment(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
logger := logz.New(logz.Config{JSON: true, Writer: &buf})
|
||||||
|
|
||||||
|
ctx := logz.WithRequestID(context.Background(), "req-xyz")
|
||||||
|
ctx = logz.WithField(ctx, "user_id", "u-001")
|
||||||
|
|
||||||
|
logger.WithContext(ctx).Info("handling request")
|
||||||
|
|
||||||
|
out := buf.String()
|
||||||
|
if !strings.Contains(out, "req-xyz") {
|
||||||
|
t.Errorf("expected request_id=req-xyz in output: %s", out)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "u-001") {
|
||||||
|
t.Errorf("expected user_id=u-001 in output: %s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── xerrors ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestXerrorsCodeRoundtrip(t *testing.T) {
|
||||||
|
err := xerrors.New(xerrors.ErrNotFound, "user not found")
|
||||||
|
if err.Code() != xerrors.ErrNotFound {
|
||||||
|
t.Errorf("Code(): got %s, want %s", err.Code(), xerrors.ErrNotFound)
|
||||||
|
}
|
||||||
|
if err.Message() != "user not found" {
|
||||||
|
t.Errorf("Message(): got %s", err.Message())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestXerrorsContextRoundtrip(t *testing.T) {
|
||||||
|
err := xerrors.New(xerrors.ErrInvalidInput, "bad").
|
||||||
|
WithContext("field", "email").
|
||||||
|
WithContext("rule", "required")
|
||||||
|
|
||||||
|
f := err.Fields()
|
||||||
|
if f["field"] != "email" {
|
||||||
|
t.Errorf("Fields()[field]: got %v", f["field"])
|
||||||
|
}
|
||||||
|
if f["rule"] != "required" {
|
||||||
|
t.Errorf("Fields()[rule]: got %v", f["rule"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestXerrorsWrapUnwrap(t *testing.T) {
|
||||||
|
cause := errors.New("db connection refused")
|
||||||
|
err := xerrors.Wrap(xerrors.ErrInternal, "query failed", cause)
|
||||||
|
|
||||||
|
if !errors.Is(err, cause) {
|
||||||
|
t.Error("errors.Is should find the wrapped cause")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestXerrorsMarshalJSON(t *testing.T) {
|
||||||
|
err := xerrors.New(xerrors.ErrNotFound, "thing missing").
|
||||||
|
WithPlatformCode("THING_NOT_FOUND")
|
||||||
|
|
||||||
|
b, jsonErr := json.Marshal(err)
|
||||||
|
if jsonErr != nil {
|
||||||
|
t.Fatalf("MarshalJSON: %v", jsonErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
var m map[string]any
|
||||||
|
if err2 := json.Unmarshal(b, &m); err2 != nil {
|
||||||
|
t.Fatalf("Unmarshal: %v", err2)
|
||||||
|
}
|
||||||
|
if m["code"] != "NOT_FOUND" {
|
||||||
|
t.Errorf("JSON code: got %v", m["code"])
|
||||||
|
}
|
||||||
|
if m["platform_code"] != "THING_NOT_FOUND" {
|
||||||
|
t.Errorf("JSON platform_code: got %v", m["platform_code"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestXerrorsConvenienceConstructors(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
err *xerrors.Err
|
||||||
|
code xerrors.Code
|
||||||
|
}{
|
||||||
|
{xerrors.InvalidInput("bad"), xerrors.ErrInvalidInput},
|
||||||
|
{xerrors.OutOfRange("over"), xerrors.ErrOutOfRange},
|
||||||
|
{xerrors.Unauthorized("auth"), xerrors.ErrUnauthorized},
|
||||||
|
{xerrors.PermissionDenied("denied"), xerrors.ErrPermissionDenied},
|
||||||
|
{xerrors.NotFound("missing"), xerrors.ErrNotFound},
|
||||||
|
{xerrors.AlreadyExists("dup"), xerrors.ErrAlreadyExists},
|
||||||
|
{xerrors.Aborted("conflict"), xerrors.ErrAborted},
|
||||||
|
{xerrors.Gone("deleted"), xerrors.ErrGone},
|
||||||
|
{xerrors.PreconditionFailed("rule"), xerrors.ErrPreconditionFailed},
|
||||||
|
{xerrors.RateLimited("slow down"), xerrors.ErrRateLimited},
|
||||||
|
{xerrors.Cancelled("cancelled"), xerrors.ErrCancelled},
|
||||||
|
{xerrors.Internal("oops"), xerrors.ErrInternal},
|
||||||
|
{xerrors.DataLoss("corrupted"), xerrors.ErrDataLoss},
|
||||||
|
{xerrors.NotImplemented("todo"), xerrors.ErrNotImplemented},
|
||||||
|
{xerrors.Unavailable("down"), xerrors.ErrUnavailable},
|
||||||
|
{xerrors.DeadlineExceeded("timeout"), xerrors.ErrDeadlineExceeded},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if tc.err.Code() != tc.code {
|
||||||
|
t.Errorf("%s constructor: Code() = %s, want %s", tc.code, tc.err.Code(), tc.code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── valid ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
func TestValidValidStruct(t *testing.T) {
|
||||||
|
type req struct {
|
||||||
|
Email string `json:"email" validate:"required,email"`
|
||||||
|
}
|
||||||
|
v := valid.New()
|
||||||
|
if err := v.Struct(req{Email: "user@example.com"}); err != nil {
|
||||||
|
t.Errorf("expected nil for valid struct, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidRequiredFieldMissing(t *testing.T) {
|
||||||
|
type req struct {
|
||||||
|
Email string `json:"email" validate:"required"`
|
||||||
|
}
|
||||||
|
v := valid.New()
|
||||||
|
err := v.Struct(req{})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for missing required field")
|
||||||
|
}
|
||||||
|
var xe *xerrors.Err
|
||||||
|
if !errors.As(err, &xe) {
|
||||||
|
t.Fatalf("expected *xerrors.Err, got %T", err)
|
||||||
|
}
|
||||||
|
if xe.Code() != xerrors.ErrInvalidInput {
|
||||||
|
t.Errorf("Code(): got %s, want %s", xe.Code(), xerrors.ErrInvalidInput)
|
||||||
|
}
|
||||||
|
if xe.Fields()["field"] != "email" {
|
||||||
|
t.Errorf("Fields()[field]: got %v", xe.Fields()["field"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidNonStructReturnsInternal(t *testing.T) {
|
||||||
|
v := valid.New()
|
||||||
|
err := v.Struct("not a struct")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for non-struct")
|
||||||
|
}
|
||||||
|
var xe *xerrors.Err
|
||||||
|
if !errors.As(err, &xe) {
|
||||||
|
t.Fatalf("expected *xerrors.Err, got %T", err)
|
||||||
|
}
|
||||||
|
if xe.Code() != xerrors.ErrInternal {
|
||||||
|
t.Errorf("Code(): got %s, want %s", xe.Code(), xerrors.ErrInternal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidSpanishMessages(t *testing.T) {
|
||||||
|
type req struct {
|
||||||
|
Email string `json:"email" validate:"required"`
|
||||||
|
}
|
||||||
|
v := valid.New(valid.WithMessageProvider(valid.SpanishMessages))
|
||||||
|
err := v.Struct(req{})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error")
|
||||||
|
}
|
||||||
|
var xe *xerrors.Err
|
||||||
|
errors.As(err, &xe)
|
||||||
|
if !strings.Contains(xe.Message(), "obligatorio") {
|
||||||
|
t.Errorf("expected Spanish message, got: %s", xe.Message())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidCustomValidator(t *testing.T) {
|
||||||
|
type req struct {
|
||||||
|
Website string `json:"website" validate:"nohttp"`
|
||||||
|
}
|
||||||
|
v := valid.New(
|
||||||
|
valid.WithCustomValidator("nohttp", func(fl valid.FieldLevel) bool {
|
||||||
|
return !strings.HasPrefix(fl.Field().String(), "http://")
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
if err := v.Struct(req{Website: "example.com"}); err != nil {
|
||||||
|
t.Errorf("expected nil for valid value, got %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := v.Struct(req{Website: "http://example.com"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error for http:// value")
|
||||||
|
}
|
||||||
|
var xe *xerrors.Err
|
||||||
|
if !errors.As(err, &xe) {
|
||||||
|
t.Fatalf("expected *xerrors.Err, got %T", err)
|
||||||
|
}
|
||||||
|
if xe.Code() != xerrors.ErrInvalidInput {
|
||||||
|
t.Errorf("Code(): got %s, want %s", xe.Code(), xerrors.ErrInvalidInput)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidOverrideProvider(t *testing.T) {
|
||||||
|
p := valid.OverrideProvider(
|
||||||
|
map[string]func(field, param string) string{
|
||||||
|
"nohttp": func(field, _ string) string {
|
||||||
|
return "field '" + field + "' must not use http://"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
valid.DefaultMessages,
|
||||||
|
)
|
||||||
|
|
||||||
|
msg := p.Message("website", "nohttp", "")
|
||||||
|
if msg != "field 'website' must not use http://" {
|
||||||
|
t.Errorf("custom tag message: got %q", msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
fallback := p.Message("email", "required", "")
|
||||||
|
if !strings.Contains(fallback, "is required") {
|
||||||
|
t.Errorf("built-in tag should fall through to DefaultMessages, got: %q", fallback)
|
||||||
|
}
|
||||||
|
}
|
||||||
10
doc.go
Normal file
10
doc.go
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
// Package core provides the foundational implementations of the Einherjar
|
||||||
|
// framework contracts: lifecycle management, structured logging, structured
|
||||||
|
// errors, and struct validation.
|
||||||
|
//
|
||||||
|
// Sub-packages:
|
||||||
|
// - launcher — application lifecycle orchestration (init → start → shutdown)
|
||||||
|
// - logz — structured, leveled logging backed by log/slog
|
||||||
|
// - xerrors — typed error codes with context enrichment
|
||||||
|
// - valid — struct validation with pluggable i18n messages
|
||||||
|
package core
|
||||||
64
docs/adr/ADR-001-core-module-composition.md
Normal file
64
docs/adr/ADR-001-core-module-composition.md
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
# ADR-001: core module composition — four sub-packages in one Go module
|
||||||
|
|
||||||
|
- **Date:** 2026-05-28
|
||||||
|
- **Module:** `code.nochebuena.dev/einherjar/core`
|
||||||
|
- **Status:** Accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
In micro-lib, the four packages that become `core` are independent Go modules:
|
||||||
|
|
||||||
|
- `code.nochebuena.dev/go/launcher`
|
||||||
|
- `code.nochebuena.dev/go/logz`
|
||||||
|
- `code.nochebuena.dev/go/xerrors`
|
||||||
|
- `code.nochebuena.dev/go/valid`
|
||||||
|
|
||||||
|
Each has its own `go.mod`, version tag, and release cycle. A dependency update to
|
||||||
|
`xerrors` requires a version bump on `xerrors`, then updating `valid` to consume the
|
||||||
|
new version, then informing all callers of both. Four packages → four coordinated
|
||||||
|
version bumps per change.
|
||||||
|
|
||||||
|
In the Einherjar module structure, each entry in the module inventory is one
|
||||||
|
independently versionable unit. The Spring Boot starter model places the
|
||||||
|
distribution boundary at the starter level (`db-postgres`, `cache-valkey`, `auth`),
|
||||||
|
not at the foundational implementation level.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
`launcher`, `logz`, `xerrors`, and `valid` are sub-packages of a single
|
||||||
|
`code.nochebuena.dev/einherjar/core` Go module.
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
**They always ship together.** Every Einherjar service needs all four:
|
||||||
|
- `launcher` requires a `logging.Logger` — it calls `logz.New` in the same main function
|
||||||
|
- `valid` returns `*xerrors.Err` — they are semantically coupled at the type level
|
||||||
|
- No known use case requires `logz` without `xerrors`, or `launcher` without `logz`
|
||||||
|
|
||||||
|
**Version coordination cost is real.** With four separate modules, a one-line fix to
|
||||||
|
`xerrors` becomes four coordinated operations: tag xerrors, update valid's go.mod,
|
||||||
|
tag valid, inform consumers. With one module, it is one operation.
|
||||||
|
|
||||||
|
**The Spring Boot analogy holds at the right level.** Spring Boot's parent POM bundles
|
||||||
|
dozens of interdependent libraries into a single versioned unit. Starters (`spring-boot-starter-data-jpa`) are the distribution boundary, not the individual `spring-data-commons` jar inside them. Einherjar's `core` is the parent; the starters are the distribution units.
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
|
||||||
|
**Four separate modules (`core-launcher`, `core-logz`, etc.).** Rejected — over-engineering at the foundational layer. There is no consumer that needs `logz` but not `xerrors`, or `launcher` but not `logz`. The additional version coordination overhead has no compensating benefit.
|
||||||
|
|
||||||
|
**One flat `core` package (no sub-packages).** Rejected — importing `core` would pull all four concerns into any module that only needs errors or validation. Sub-packages preserve the ability to import only what is needed.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
**Easier:** A single `go get code.nochebuena.dev/einherjar/core@v1.x.x` installs
|
||||||
|
everything. A single version bump covers all four sub-packages. Dependency graph for
|
||||||
|
downstream starters stays simple.
|
||||||
|
|
||||||
|
**Harder:** A change to any sub-package bumps the entire `core` version, even if the
|
||||||
|
change is isolated to `valid`. This is the accepted trade-off — the coupling is real;
|
||||||
|
the version increment reflects it.
|
||||||
|
|
||||||
|
**New obligations:** Sub-packages within `core` may import each other in one direction:
|
||||||
|
`valid` may import `xerrors`; nothing else crosses package boundaries within `core`.
|
||||||
|
Circular imports between sub-packages are prohibited. `launcher` uses
|
||||||
|
`contracts/logging` — not `core/logz` directly — to preserve the contracts layer.
|
||||||
115
docs/adr/ADR-002-logz-contracts-errs.md
Normal file
115
docs/adr/ADR-002-logz-contracts-errs.md
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
# ADR-002: logz adopts contracts/errs instead of private duck typing
|
||||||
|
|
||||||
|
- **Date:** 2026-05-28
|
||||||
|
- **Module:** `code.nochebuena.dev/einherjar/core`
|
||||||
|
- **Status:** Accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
In micro-lib, `logz` enriches log records when the error passed to `Logger.Error`
|
||||||
|
carries a machine-readable code or structured fields. It detects this at runtime
|
||||||
|
using two private interfaces defined inside `logz`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// inside logz — never exported
|
||||||
|
type errorWithCode interface {
|
||||||
|
ErrorCode() string
|
||||||
|
}
|
||||||
|
type errorWithContext interface {
|
||||||
|
ErrorContext() map[string]any
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`xerrors.Err` implements both via its `ErrorCode()` and `ErrorContext()` methods.
|
||||||
|
`logz` detects this with `errors.As` — without importing `xerrors`. The decoupling
|
||||||
|
is preserved. But the contract is invisible: a developer who wants their custom error
|
||||||
|
type to receive log enrichment must read `logz`'s internal source to discover what
|
||||||
|
methods are required.
|
||||||
|
|
||||||
|
This approach is acceptable in micro-lib (single team, single repository, total
|
||||||
|
visibility). In a framework distributed to third-party authors, it is a maintenance
|
||||||
|
trap.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
`core/logz` imports `contracts/errs` and checks `errs.CodedError` and
|
||||||
|
`errs.ContextualError` instead of defining private duck-typed equivalents.
|
||||||
|
|
||||||
|
```go
|
||||||
|
// core/logz/logger.go
|
||||||
|
var ec errs.CodedError
|
||||||
|
if errors.As(err, &ec) {
|
||||||
|
attrs = append(attrs, "error_code", ec.ErrorCode())
|
||||||
|
}
|
||||||
|
var ectx errs.ContextualError
|
||||||
|
if errors.As(err, &ectx) {
|
||||||
|
for k, v := range ectx.ErrorContext() {
|
||||||
|
attrs = append(attrs, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`core/xerrors` declares compile-time satisfaction:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// core/xerrors/err.go
|
||||||
|
var _ errs.CodedError = (*Err)(nil)
|
||||||
|
var _ errs.ContextualError = (*Err)(nil)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Why the `contracts/errs` Sub-package Exists
|
||||||
|
|
||||||
|
`contracts` is the only Einherjar module guaranteed to have zero dependencies.
|
||||||
|
If `CodedError` and `ContextualError` lived in `core/xerrors`, any module
|
||||||
|
implementing a custom error type would be forced to import `core` — pulling the
|
||||||
|
launcher, logger, and validator into its dependency graph. That defeats the
|
||||||
|
Separated Interface pattern.
|
||||||
|
|
||||||
|
`contracts/errs` is a zero-dependency home for these two 1-method interfaces.
|
||||||
|
Any module can implement them without taking on any Einherjar dependencies.
|
||||||
|
|
||||||
|
## Clean Separation Preserved
|
||||||
|
|
||||||
|
`logz` still does not import `xerrors`. Both import `contracts/errs`. The
|
||||||
|
decoupling is maintained; the contract is now visible.
|
||||||
|
|
||||||
|
```
|
||||||
|
contracts/errs (zero deps)
|
||||||
|
↑ ↑
|
||||||
|
core/logz core/xerrors
|
||||||
|
(imports) (implements)
|
||||||
|
```
|
||||||
|
|
||||||
|
A third-party error type implements `errs.CodedError` by satisfying one interface
|
||||||
|
from `contracts` — a zero-dependency import. It receives full log enrichment
|
||||||
|
automatically, without any wiring code.
|
||||||
|
|
||||||
|
## Alternatives Considered
|
||||||
|
|
||||||
|
**Keep private duck typing.** Rejected — invisible to third-party implementors.
|
||||||
|
A framework that requires developers to read its internal source code to understand
|
||||||
|
what their types must implement is hostile to the developers it serves.
|
||||||
|
|
||||||
|
**Export the interfaces from `core/logz`.** Rejected — would force custom error
|
||||||
|
types to import `core`, violating the Separated Interface pattern. An error type
|
||||||
|
should not need to know about logging infrastructure.
|
||||||
|
|
||||||
|
**One combined `RichError` interface.** Rejected — ISP. An error may carry a
|
||||||
|
machine-readable code without structured fields, or structured fields without a code.
|
||||||
|
Forcing both into one interface imposes unnecessary constraints on implementors.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
**Easier:** Third-party error types have a clear, discoverable interface to implement:
|
||||||
|
`go doc code.nochebuena.dev/einherjar/contracts/errs`. Compile-time verification
|
||||||
|
replaces runtime discovery. The framework's own `*xerrors.Err` is provably correct
|
||||||
|
at compile time.
|
||||||
|
|
||||||
|
**Harder:** `logz` now imports `contracts`, adding one dependency to its import
|
||||||
|
graph. This dependency is zero-cost in practice — `contracts` has no external
|
||||||
|
dependencies and will not change its interfaces without a major version bump.
|
||||||
|
|
||||||
|
**New obligations:** The `errs.CodedError.ErrorCode()` and
|
||||||
|
`errs.ContextualError.ErrorContext()` signatures are permanent from `contracts v1.0.0`.
|
||||||
|
Any implementor of these interfaces is guaranteed that the signatures will not change
|
||||||
|
without a major version bump on `contracts`.
|
||||||
71
docs/adr/ADR-003-config-env-tags.md
Normal file
71
docs/adr/ADR-003-config-env-tags.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
# ADR-003 — Config naming convention and caarlos0/env tag standard
|
||||||
|
|
||||||
|
**Status:** Accepted
|
||||||
|
**Date:** 2026-05-28
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
`launcher` and `logz` originally followed micro-lib's `Options` naming for their
|
||||||
|
configuration structs. `Options` has no env tags, so there is no standard way for
|
||||||
|
applications to populate framework configuration from environment variables without
|
||||||
|
hardcoding field assignments.
|
||||||
|
|
||||||
|
The project requires a consistent, library-agnostic approach to environment-based
|
||||||
|
configuration across all Einherjar modules.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
1. **Naming:** Every package that accepts external configuration exposes a `Config`
|
||||||
|
struct. `Options` is not used for configuration types in Einherjar — it is reserved
|
||||||
|
for functional options patterns if ever needed.
|
||||||
|
|
||||||
|
2. **Tag standard:** `Config` struct fields that can be sourced from environment
|
||||||
|
variables carry `env` and `envDefault` struct tags following the `caarlos0/env`
|
||||||
|
library's syntax:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type Config struct {
|
||||||
|
Level slog.Level `env:"EINHERJAR_LOG_LEVEL" envDefault:"INFO"`
|
||||||
|
JSON bool `env:"EINHERJAR_LOG_JSON" envDefault:"false"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **No library import:** Modules do not import `caarlos0/env` or any other env
|
||||||
|
loader. The tags are metadata only. Applications choose their own loader and call
|
||||||
|
it against the `Config` struct before passing it to `New()`.
|
||||||
|
|
||||||
|
4. **Env var prefix:** All Einherjar-owned variables use the `EINHERJAR_` prefix,
|
||||||
|
consistent with the existing `EINHERJAR_BANNER` convention.
|
||||||
|
|
||||||
|
5. **Programmatic-only fields:** Fields that cannot be sourced from environment
|
||||||
|
variables (e.g. `io.Writer`, `[]any`) are included in `Config` without tags.
|
||||||
|
They default to sensible zero-value behaviour and are set directly by the caller.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
- **Library-agnostic:** Different applications use different env loaders (`caarlos0/env`,
|
||||||
|
`sethvargo/go-envconfig`, `kelseyhightower/envconfig`, YAML via Viper, etc.).
|
||||||
|
Carrying only tags means no dependency is forced.
|
||||||
|
- **Consistent with the project:** micro-lib starters (`firebase`, `postgres`,
|
||||||
|
`mysql`, `sqlite`, `httpserver`, etc.) already use this pattern.
|
||||||
|
- **Discoverable defaults:** `envDefault` values are readable in the struct definition
|
||||||
|
itself — no need to trace through constructor logic to find what defaults are applied.
|
||||||
|
- **Zero cost when not used:** An application that populates `Config` directly in code
|
||||||
|
pays no overhead for the tags.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- All future Einherjar packages with external config must follow this convention.
|
||||||
|
- Starter packages (`db-postgres`, `cache-valkey`, etc.) will expose `Config` structs
|
||||||
|
with env tags when they are implemented.
|
||||||
|
- The `defaultComponentStopTimeout` constant in `launcher` is kept alongside
|
||||||
|
`Config.envDefault` so the programmatic default (used when zero `time.Duration` is
|
||||||
|
passed) remains explicit in code.
|
||||||
12
docs/adr/index.md
Normal file
12
docs/adr/index.md
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
# ADR Index — core
|
||||||
|
|
||||||
|
Module-level architecture decisions for `code.nochebuena.dev/einherjar/core`.
|
||||||
|
|
||||||
|
For framework-wide decisions see the
|
||||||
|
[Einherjar docs repository](https://code.nochebuena.dev/einherjar/docs).
|
||||||
|
|
||||||
|
| ADR | Title | Status |
|
||||||
|
|---|---|---|
|
||||||
|
| [ADR-001](ADR-001-core-module-composition.md) | core module composition — four sub-packages in one Go module | Accepted |
|
||||||
|
| [ADR-002](ADR-002-logz-contracts-errs.md) | logz adopts contracts/errs instead of private duck typing | Accepted |
|
||||||
|
| [ADR-003](ADR-003-config-env-tags.md) | Config naming convention and caarlos0/env tag standard | Accepted |
|
||||||
18
go.mod
Normal file
18
go.mod
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
module code.nochebuena.dev/einherjar/core
|
||||||
|
|
||||||
|
go 1.26
|
||||||
|
|
||||||
|
require (
|
||||||
|
code.nochebuena.dev/einherjar/contracts v1.0.0
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||||
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
golang.org/x/crypto v0.46.0 // indirect
|
||||||
|
golang.org/x/sys v0.39.0 // indirect
|
||||||
|
golang.org/x/text v0.32.0 // indirect
|
||||||
|
)
|
||||||
28
go.sum
Normal file
28
go.sum
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
code.nochebuena.dev/einherjar/contracts v1.0.0 h1:hRudEtOIqU7vwedYLsCh8+9q5dCnKb61qX+zibqImRU=
|
||||||
|
code.nochebuena.dev/einherjar/contracts v1.0.0/go.mod h1:ccltUtrFb5+MEJdkx2VVEUL+xC5pupVlVVsMM8AlCWI=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||||
|
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||||
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||||
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||||
|
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||||
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||||
|
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
51
launcher/banner.go
Normal file
51
launcher/banner.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package launcher
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/observability"
|
||||||
|
)
|
||||||
|
|
||||||
|
func printBanner(identifiables []observability.Identifiable) {
|
||||||
|
v := strings.ToLower(os.Getenv("EINHERJAR_BANNER"))
|
||||||
|
if v == "off" || v == "false" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stdout, bannerText, coreVersion())
|
||||||
|
for _, id := range identifiables {
|
||||||
|
path := strings.TrimPrefix(id.ModulePath(), "code.nochebuena.dev/")
|
||||||
|
fmt.Fprintf(os.Stdout, " · %-25s %s\n", path, id.ModuleVersion())
|
||||||
|
}
|
||||||
|
if len(identifiables) > 0 {
|
||||||
|
fmt.Fprintln(os.Stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func coreVersion() string {
|
||||||
|
const path = "code.nochebuena.dev/einherjar/core"
|
||||||
|
if info, ok := debug.ReadBuildInfo(); ok {
|
||||||
|
for _, dep := range info.Deps {
|
||||||
|
if dep.Path == path {
|
||||||
|
return dep.Version
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if info.Main.Path == path {
|
||||||
|
return info.Main.Version
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "(devel)"
|
||||||
|
}
|
||||||
|
|
||||||
|
const bannerText = `
|
||||||
|
███████╗██╗███╗ ██╗██╗ ██╗███████╗██████╗ ██╗ █████╗ ██████╗
|
||||||
|
██╔════╝██║████╗ ██║██║ ██║██╔════╝██╔══██╗ ██║██╔══██╗██╔══██╗
|
||||||
|
█████╗ ██║██╔██╗ ██║███████║█████╗ ██████╔╝ ██║███████║██████╔╝
|
||||||
|
██╔══╝ ██║██║╚██╗██║██╔══██║██╔══╝ ██╔══██╗██ ██║██╔══██║██╔══██╗
|
||||||
|
███████╗██║██║ ╚████║██║ ██║███████╗██║ ██║╚█████╔╝██║ ██║██║ ██║
|
||||||
|
╚══════╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚════╝ ╚═╝ ╚═╝╚═╝ ╚═╝
|
||||||
|
code.nochebuena.dev/einherjar · Chosen warriors. Not for themselves. · %s
|
||||||
|
|
||||||
|
`
|
||||||
13
launcher/config.go
Normal file
13
launcher/config.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package launcher
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// Config configures a Launcher instance.
|
||||||
|
// The zero value is valid: 15-second component stop timeout.
|
||||||
|
type Config struct {
|
||||||
|
// ComponentStopTimeout is the maximum time allowed for each component's OnStop.
|
||||||
|
// Default: 15 seconds.
|
||||||
|
ComponentStopTimeout time.Duration `env:"EINHERJAR_COMPONENT_STOP_TIMEOUT" envDefault:"15s"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultComponentStopTimeout = 15 * time.Second
|
||||||
27
launcher/doc.go
Normal file
27
launcher/doc.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
// Package launcher orchestrates the application lifecycle.
|
||||||
|
//
|
||||||
|
// A Launcher manages infrastructure components through three ordered phases:
|
||||||
|
//
|
||||||
|
// 1. OnInit — all components initialize in registration order
|
||||||
|
// 2. BeforeStart hooks — dependency injection wiring runs
|
||||||
|
// 3. OnStart — all components start in registration order
|
||||||
|
//
|
||||||
|
// On shutdown (OS signal or programmatic Shutdown call), OnStop is called for
|
||||||
|
// every component in reverse registration order, ensuring dependents stop
|
||||||
|
// before their dependencies.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
//
|
||||||
|
// logger := logz.New(logz.Options{JSON: true})
|
||||||
|
// lc := launcher.New(logger)
|
||||||
|
//
|
||||||
|
// lc.Append(db, cache, server)
|
||||||
|
// lc.BeforeStart(func() error {
|
||||||
|
// return server.RegisterRoutes(db, cache)
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// if err := lc.Run(); err != nil {
|
||||||
|
// logger.Error("launcher failed", err)
|
||||||
|
// os.Exit(1)
|
||||||
|
// }
|
||||||
|
package launcher
|
||||||
6
launcher/hook.go
Normal file
6
launcher/hook.go
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
package launcher
|
||||||
|
|
||||||
|
// Hook is a function executed during the assembly phase — after all OnInit calls
|
||||||
|
// and before all OnStart calls. Use hooks for dependency injection wiring that
|
||||||
|
// requires every component to be initialized before connections are established.
|
||||||
|
type Hook func() error
|
||||||
162
launcher/launcher.go
Normal file
162
launcher/launcher.go
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
package launcher
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/lifecycle"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/observability"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Launcher manages the application lifecycle: init → assemble → start → wait → shutdown.
|
||||||
|
type Launcher interface {
|
||||||
|
// Append adds one or more components. Registered in the order they are appended;
|
||||||
|
// shutdown runs in reverse order.
|
||||||
|
Append(components ...lifecycle.Component)
|
||||||
|
// BeforeStart registers hooks that run after all OnInit calls and before all OnStart
|
||||||
|
// calls. Use for dependency injection wiring.
|
||||||
|
BeforeStart(hooks ...Hook)
|
||||||
|
// Run executes the full application lifecycle. Blocks until an OS shutdown signal is
|
||||||
|
// received or Shutdown is called. Returns an error if any lifecycle step fails.
|
||||||
|
// The caller is responsible for calling os.Exit(1) when needed.
|
||||||
|
Run() error
|
||||||
|
// Shutdown triggers a graceful shutdown and waits for Run to return.
|
||||||
|
// ctx controls the caller-side wait timeout — it does NOT override
|
||||||
|
// Config.ComponentStopTimeout for individual components.
|
||||||
|
// Safe to call multiple times (idempotent).
|
||||||
|
Shutdown(ctx context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ Launcher = (*launcher)(nil)
|
||||||
|
|
||||||
|
// New returns a Launcher configured by opts. The zero value of Config is valid.
|
||||||
|
func New(logger logging.Logger, opts ...Config) Launcher {
|
||||||
|
o := Config{ComponentStopTimeout: defaultComponentStopTimeout}
|
||||||
|
if len(opts) > 0 {
|
||||||
|
if opts[0].ComponentStopTimeout > 0 {
|
||||||
|
o.ComponentStopTimeout = opts[0].ComponentStopTimeout
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &launcher{
|
||||||
|
logger: logger,
|
||||||
|
opts: o,
|
||||||
|
components: make([]lifecycle.Component, 0),
|
||||||
|
shutdownCh: make(chan struct{}),
|
||||||
|
doneCh: make(chan struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type launcher struct {
|
||||||
|
logger logging.Logger
|
||||||
|
opts Config
|
||||||
|
components []lifecycle.Component
|
||||||
|
beforeStart []Hook
|
||||||
|
shutdownCh chan struct{}
|
||||||
|
doneCh chan struct{}
|
||||||
|
shutdownOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *launcher) Append(components ...lifecycle.Component) {
|
||||||
|
l.components = append(l.components, components...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *launcher) BeforeStart(hooks ...Hook) {
|
||||||
|
l.beforeStart = append(l.beforeStart, hooks...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run executes the full application lifecycle:
|
||||||
|
// 1. Prints the startup banner (unless EINHERJAR_BANNER=off).
|
||||||
|
// 2. OnInit for all components (in registration order).
|
||||||
|
// 3. BeforeStart hooks (in registration order).
|
||||||
|
// 4. OnStart for all components (in registration order).
|
||||||
|
// 5. Blocks until an OS signal or Shutdown() is called.
|
||||||
|
// 6. stopAll — OnStop for all components (in reverse order).
|
||||||
|
func (l *launcher) Run() error {
|
||||||
|
var ids []observability.Identifiable
|
||||||
|
for _, c := range l.components {
|
||||||
|
if id, ok := c.(observability.Identifiable); ok {
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printBanner(ids)
|
||||||
|
defer close(l.doneCh)
|
||||||
|
|
||||||
|
l.logger.Info("launcher: starting init phase (OnInit)")
|
||||||
|
for _, c := range l.components {
|
||||||
|
if err := c.OnInit(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
l.logger.Info("launcher: running assembly hooks (BeforeStart)")
|
||||||
|
for _, hook := range l.beforeStart {
|
||||||
|
if err := hook(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
l.logger.Info("launcher: starting components (OnStart)")
|
||||||
|
for _, c := range l.components {
|
||||||
|
if err := c.OnStart(); err != nil {
|
||||||
|
l.logger.Error("launcher: OnStart failed, triggering shutdown", err)
|
||||||
|
l.stopAll()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
l.logger.Info("launcher: application ready")
|
||||||
|
|
||||||
|
quit := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer signal.Stop(quit)
|
||||||
|
|
||||||
|
select {
|
||||||
|
case s := <-quit:
|
||||||
|
l.logger.Info("launcher: termination signal received", "signal", s.String())
|
||||||
|
case <-l.shutdownCh:
|
||||||
|
l.logger.Info("launcher: programmatic shutdown requested")
|
||||||
|
}
|
||||||
|
|
||||||
|
l.stopAll()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *launcher) Shutdown(ctx context.Context) error {
|
||||||
|
l.shutdownOnce.Do(func() {
|
||||||
|
close(l.shutdownCh)
|
||||||
|
})
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-l.doneCh:
|
||||||
|
return nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *launcher) stopAll() {
|
||||||
|
l.logger.Info("launcher: stopping all components")
|
||||||
|
|
||||||
|
for i := len(l.components) - 1; i >= 0; i-- {
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func(c lifecycle.Component) {
|
||||||
|
if err := c.OnStop(); err != nil {
|
||||||
|
l.logger.Error("launcher: error during OnStop", err)
|
||||||
|
}
|
||||||
|
close(done)
|
||||||
|
}(l.components[i])
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(l.opts.ComponentStopTimeout):
|
||||||
|
l.logger.Error("launcher: component OnStop timed out", nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
l.logger.Info("launcher: all components stopped")
|
||||||
|
}
|
||||||
20
logz/config.go
Normal file
20
logz/config.go
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
package logz
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config configures a Logger instance.
|
||||||
|
// The zero value is valid: INFO level, text output, os.Stdout, no static args.
|
||||||
|
type Config struct {
|
||||||
|
// Level is the minimum log level. Default: slog.LevelInfo (zero value).
|
||||||
|
Level slog.Level `env:"EINHERJAR_LOG_LEVEL" envDefault:"INFO"`
|
||||||
|
// JSON enables JSON output. Default: false (text output).
|
||||||
|
JSON bool `env:"EINHERJAR_LOG_JSON" envDefault:"false"`
|
||||||
|
// StaticArgs are key-value pairs attached to every log record.
|
||||||
|
StaticArgs []any
|
||||||
|
// Writer is the output destination. Defaults to os.Stdout when nil.
|
||||||
|
// Accepts any io.Writer: *os.File, bytes.Buffer, io.MultiWriter, etc.
|
||||||
|
Writer io.Writer
|
||||||
|
}
|
||||||
40
logz/context.go
Normal file
40
logz/context.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package logz
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type ctxRequestIDKey struct{}
|
||||||
|
type ctxExtraFieldsKey struct{}
|
||||||
|
|
||||||
|
// WithRequestID adds a request correlation ID to the context.
|
||||||
|
func WithRequestID(ctx context.Context, id string) context.Context {
|
||||||
|
return context.WithValue(ctx, ctxRequestIDKey{}, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRequestID retrieves the correlation ID from the context.
|
||||||
|
// Returns "" if not present or if ctx is nil.
|
||||||
|
func GetRequestID(ctx context.Context) string {
|
||||||
|
if ctx == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
id, _ := ctx.Value(ctxRequestIDKey{}).(string)
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithField adds a single key-value pair to the context for logging.
|
||||||
|
func WithField(ctx context.Context, key string, value any) context.Context {
|
||||||
|
return WithFields(ctx, map[string]any{key: value})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithFields adds multiple key-value pairs to the context for logging.
|
||||||
|
// Merges with any existing fields — does not overwrite the whole map.
|
||||||
|
func WithFields(ctx context.Context, fields map[string]any) context.Context {
|
||||||
|
existing, _ := ctx.Value(ctxExtraFieldsKey{}).(map[string]any)
|
||||||
|
newMap := make(map[string]any, len(existing)+len(fields))
|
||||||
|
for k, v := range existing {
|
||||||
|
newMap[k] = v
|
||||||
|
}
|
||||||
|
for k, v := range fields {
|
||||||
|
newMap[k] = v
|
||||||
|
}
|
||||||
|
return context.WithValue(ctx, ctxExtraFieldsKey{}, newMap)
|
||||||
|
}
|
||||||
27
logz/doc.go
Normal file
27
logz/doc.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
// Package logz provides a structured, leveled logger backed by the standard
|
||||||
|
// library's log/slog package.
|
||||||
|
//
|
||||||
|
// logz.New returns a logging.Logger (from contracts). No concrete type is
|
||||||
|
// exported — callers depend on the interface, not the implementation.
|
||||||
|
//
|
||||||
|
// Error enrichment: when an error passed to Logger.Error implements
|
||||||
|
// errs.CodedError or errs.ContextualError (from contracts/errs), the
|
||||||
|
// corresponding fields are automatically appended to the log record without
|
||||||
|
// either package importing the other.
|
||||||
|
//
|
||||||
|
// Context enrichment: WithRequestID, WithField, and WithFields store values
|
||||||
|
// in context.Context. Logger.WithContext reads them back and attaches
|
||||||
|
// request_id and any extra fields to every subsequent log record.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
//
|
||||||
|
// logger := logz.New(logz.Options{
|
||||||
|
// Level: slog.LevelDebug,
|
||||||
|
// JSON: true,
|
||||||
|
// StaticArgs: []any{"service", "api"},
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// ctx = logz.WithRequestID(ctx, requestID)
|
||||||
|
// reqLogger := logger.WithContext(ctx)
|
||||||
|
// reqLogger.Info("handling request", "path", r.URL.Path)
|
||||||
|
package logz
|
||||||
103
logz/logger.go
Normal file
103
logz/logger.go
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
package logz
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/errs"
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ logging.Logger = (*slogLogger)(nil)
|
||||||
|
|
||||||
|
// New returns a Logger configured by cfg.
|
||||||
|
func New(cfg Config) logging.Logger {
|
||||||
|
w := cfg.Writer
|
||||||
|
if w == nil {
|
||||||
|
w = os.Stdout
|
||||||
|
}
|
||||||
|
|
||||||
|
handlerOpts := &slog.HandlerOptions{Level: cfg.Level}
|
||||||
|
var handler slog.Handler
|
||||||
|
if cfg.JSON {
|
||||||
|
handler = slog.NewJSONHandler(w, handlerOpts)
|
||||||
|
} else {
|
||||||
|
handler = slog.NewTextHandler(w, handlerOpts)
|
||||||
|
}
|
||||||
|
|
||||||
|
base := slog.New(handler)
|
||||||
|
if len(cfg.StaticArgs) > 0 {
|
||||||
|
base = base.With(cfg.StaticArgs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &slogLogger{logger: base}
|
||||||
|
}
|
||||||
|
|
||||||
|
type slogLogger struct {
|
||||||
|
logger *slog.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *slogLogger) Debug(msg string, args ...any) { l.logger.Debug(msg, args...) }
|
||||||
|
func (l *slogLogger) Info(msg string, args ...any) { l.logger.Info(msg, args...) }
|
||||||
|
func (l *slogLogger) Warn(msg string, args ...any) { l.logger.Warn(msg, args...) }
|
||||||
|
|
||||||
|
func (l *slogLogger) Error(msg string, err error, args ...any) {
|
||||||
|
args = enrichErrorAttrs(err, args)
|
||||||
|
if err != nil {
|
||||||
|
args = append(args, slog.Any("error", err))
|
||||||
|
}
|
||||||
|
l.logger.Error(msg, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *slogLogger) With(args ...any) logging.Logger {
|
||||||
|
return &slogLogger{logger: l.logger.With(args...)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *slogLogger) WithContext(ctx context.Context) logging.Logger {
|
||||||
|
if ctx == nil {
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
newLogger := l.logger
|
||||||
|
modified := false
|
||||||
|
|
||||||
|
if id, ok := ctx.Value(ctxRequestIDKey{}).(string); ok && id != "" {
|
||||||
|
newLogger = newLogger.With(slog.String("request_id", id))
|
||||||
|
modified = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if fields, ok := ctx.Value(ctxExtraFieldsKey{}).(map[string]any); ok {
|
||||||
|
for k, v := range fields {
|
||||||
|
newLogger = newLogger.With(k, v)
|
||||||
|
}
|
||||||
|
modified = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if !modified {
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
return &slogLogger{logger: newLogger}
|
||||||
|
}
|
||||||
|
|
||||||
|
// enrichErrorAttrs appends error_code and context fields from err when err
|
||||||
|
// satisfies errs.CodedError or errs.ContextualError from contracts.
|
||||||
|
// Returns attrs unchanged if err is nil or satisfies neither interface.
|
||||||
|
func enrichErrorAttrs(err error, attrs []any) []any {
|
||||||
|
if err == nil {
|
||||||
|
return attrs
|
||||||
|
}
|
||||||
|
var ec errs.CodedError
|
||||||
|
if errors.As(err, &ec) {
|
||||||
|
attrs = append(attrs, "error_code", ec.ErrorCode())
|
||||||
|
}
|
||||||
|
var ectx errs.ContextualError
|
||||||
|
if errors.As(err, &ectx) {
|
||||||
|
for k, v := range ectx.ErrorContext() {
|
||||||
|
attrs = append(attrs, k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return attrs
|
||||||
|
}
|
||||||
24
valid/doc.go
Normal file
24
valid/doc.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
// Package valid wraps github.com/go-playground/validator/v10 behind a minimal
|
||||||
|
// Validator interface, returning xerrors-typed errors with stable codes.
|
||||||
|
//
|
||||||
|
// The backend library is fully hidden — callers interact only with Validator
|
||||||
|
// and *xerrors.Err. Swapping the backend in the future requires no API changes.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
//
|
||||||
|
// v := valid.New()
|
||||||
|
// if err := v.Struct(req); err != nil {
|
||||||
|
// // err is *xerrors.Err with Code() == xerrors.ErrInvalidInput
|
||||||
|
// // err.Fields()["field"] contains the failing field name
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // Spanish messages
|
||||||
|
// v := valid.New(valid.WithMessageProvider(valid.SpanishMessages))
|
||||||
|
//
|
||||||
|
// Struct tags follow go-playground/validator conventions:
|
||||||
|
//
|
||||||
|
// type CreateUserReq struct {
|
||||||
|
// Email string `json:"email" validate:"required,email"`
|
||||||
|
// Age int `json:"age" validate:"min=18"`
|
||||||
|
// }
|
||||||
|
package valid
|
||||||
15
valid/field_level.go
Normal file
15
valid/field_level.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package valid
|
||||||
|
|
||||||
|
import "reflect"
|
||||||
|
|
||||||
|
// FieldLevel provides access to the field being validated.
|
||||||
|
// It is passed to custom validator functions registered via WithCustomValidator.
|
||||||
|
type FieldLevel interface {
|
||||||
|
// Field returns the reflect.Value of the field being validated.
|
||||||
|
Field() reflect.Value
|
||||||
|
// Param returns the tag parameter, if any.
|
||||||
|
// For validate:"mytag=value", Param() returns "value"; otherwise "".
|
||||||
|
Param() string
|
||||||
|
// FieldName returns the field name used for error messages (json tag or Go name).
|
||||||
|
FieldName() string
|
||||||
|
}
|
||||||
750
valid/message_provider.go
Normal file
750
valid/message_provider.go
Normal file
@@ -0,0 +1,750 @@
|
|||||||
|
package valid
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// MessageProvider maps a validation failure to a human-readable message.
|
||||||
|
//
|
||||||
|
// - field: the struct field name (e.g. "Email")
|
||||||
|
// - tag: the failing validation rule (e.g. "required", "email", "min")
|
||||||
|
// - param: the rule parameter if any (e.g. "18" for min=18), or "" if none
|
||||||
|
type MessageProvider interface {
|
||||||
|
Message(field, tag, param string) string
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultMessages is the built-in English message provider.
|
||||||
|
// Used automatically when no WithMessageProvider option is given.
|
||||||
|
var DefaultMessages MessageProvider = defaultMessages{}
|
||||||
|
|
||||||
|
// SpanishMessages is an opt-in Spanish message provider.
|
||||||
|
var SpanishMessages MessageProvider = spanishMessages{}
|
||||||
|
|
||||||
|
// OverrideProvider returns a MessageProvider that resolves messages from handlers
|
||||||
|
// for specific tags, delegating to base for any tag not in handlers.
|
||||||
|
//
|
||||||
|
// Use it to supply messages for custom validators or to override individual tags:
|
||||||
|
//
|
||||||
|
// p := valid.OverrideProvider(
|
||||||
|
// map[string]func(field, param string) string{
|
||||||
|
// "strongpassword": func(field, _ string) string {
|
||||||
|
// return fmt.Sprintf("field '%s' must contain a letter, digit, and symbol", field)
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
// valid.DefaultMessages,
|
||||||
|
// )
|
||||||
|
func OverrideProvider(handlers map[string]func(field, param string) string, base MessageProvider) MessageProvider {
|
||||||
|
return &overrideProvider{handlers: handlers, base: base}
|
||||||
|
}
|
||||||
|
|
||||||
|
type overrideProvider struct {
|
||||||
|
handlers map[string]func(field, param string) string
|
||||||
|
base MessageProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *overrideProvider) Message(field, tag, param string) string {
|
||||||
|
if fn, ok := p.handlers[tag]; ok {
|
||||||
|
return fn(field, param)
|
||||||
|
}
|
||||||
|
return p.base.Message(field, tag, param)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// English (default)
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
|
||||||
|
type defaultMessages struct{}
|
||||||
|
|
||||||
|
func (defaultMessages) Message(field, tag, param string) string {
|
||||||
|
switch tag {
|
||||||
|
// Required
|
||||||
|
case "required":
|
||||||
|
return fmt.Sprintf("field '%s' is required", field)
|
||||||
|
case "required_if", "required_unless":
|
||||||
|
return fmt.Sprintf("field '%s' is required", field)
|
||||||
|
case "required_with":
|
||||||
|
return fmt.Sprintf("field '%s' is required when %s is present", field, param)
|
||||||
|
case "required_with_all":
|
||||||
|
return fmt.Sprintf("field '%s' is required when all of [%s] are present", field, param)
|
||||||
|
case "required_without":
|
||||||
|
return fmt.Sprintf("field '%s' is required when %s is absent", field, param)
|
||||||
|
case "required_without_all":
|
||||||
|
return fmt.Sprintf("field '%s' is required when all of [%s] are absent", field, param)
|
||||||
|
// Excluded
|
||||||
|
case "excluded_if", "excluded_unless":
|
||||||
|
return fmt.Sprintf("field '%s' must not be set in this context", field)
|
||||||
|
case "excluded_with":
|
||||||
|
return fmt.Sprintf("field '%s' must not be set when %s is present", field, param)
|
||||||
|
case "excluded_with_all":
|
||||||
|
return fmt.Sprintf("field '%s' must not be set when all of [%s] are present", field, param)
|
||||||
|
case "excluded_without":
|
||||||
|
return fmt.Sprintf("field '%s' must not be set when %s is absent", field, param)
|
||||||
|
case "excluded_without_all":
|
||||||
|
return fmt.Sprintf("field '%s' must not be set when all of [%s] are absent", field, param)
|
||||||
|
// Size / value
|
||||||
|
case "len":
|
||||||
|
return fmt.Sprintf("field '%s' must be exactly %s characters long", field, param)
|
||||||
|
case "min":
|
||||||
|
return fmt.Sprintf("field '%s' is too short (minimum %s)", field, param)
|
||||||
|
case "max":
|
||||||
|
return fmt.Sprintf("field '%s' is too long (maximum %s)", field, param)
|
||||||
|
case "eq":
|
||||||
|
return fmt.Sprintf("field '%s' must equal %s", field, param)
|
||||||
|
case "eq_ignore_case":
|
||||||
|
return fmt.Sprintf("field '%s' must equal %s (case-insensitive)", field, param)
|
||||||
|
case "ne":
|
||||||
|
return fmt.Sprintf("field '%s' must not equal %s", field, param)
|
||||||
|
case "ne_ignore_case":
|
||||||
|
return fmt.Sprintf("field '%s' must not equal %s (case-insensitive)", field, param)
|
||||||
|
case "gt":
|
||||||
|
return fmt.Sprintf("field '%s' must be greater than %s", field, param)
|
||||||
|
case "gte":
|
||||||
|
return fmt.Sprintf("field '%s' must be greater than or equal to %s", field, param)
|
||||||
|
case "lt":
|
||||||
|
return fmt.Sprintf("field '%s' must be less than %s", field, param)
|
||||||
|
case "lte":
|
||||||
|
return fmt.Sprintf("field '%s' must be less than or equal to %s", field, param)
|
||||||
|
case "oneof":
|
||||||
|
return fmt.Sprintf("field '%s' must be one of [%s]", field, param)
|
||||||
|
case "noneof":
|
||||||
|
return fmt.Sprintf("field '%s' must not be any of [%s]", field, param)
|
||||||
|
case "unique":
|
||||||
|
return fmt.Sprintf("field '%s' must contain unique values", field)
|
||||||
|
case "isdefault":
|
||||||
|
return fmt.Sprintf("field '%s' must be the default (zero) value", field)
|
||||||
|
case "validateFn":
|
||||||
|
return fmt.Sprintf("field '%s' failed custom validation", field)
|
||||||
|
// Cross-field comparisons
|
||||||
|
case "eqfield", "eqcsfield":
|
||||||
|
return fmt.Sprintf("field '%s' must equal %s", field, param)
|
||||||
|
case "nefield", "necsfield":
|
||||||
|
return fmt.Sprintf("field '%s' must not equal %s", field, param)
|
||||||
|
case "gtfield", "gtcsfield":
|
||||||
|
return fmt.Sprintf("field '%s' must be greater than %s", field, param)
|
||||||
|
case "gtefield", "gtecsfield":
|
||||||
|
return fmt.Sprintf("field '%s' must be greater than or equal to %s", field, param)
|
||||||
|
case "ltfield", "ltcsfield":
|
||||||
|
return fmt.Sprintf("field '%s' must be less than %s", field, param)
|
||||||
|
case "ltefield", "ltecsfield":
|
||||||
|
return fmt.Sprintf("field '%s' must be less than or equal to %s", field, param)
|
||||||
|
case "fieldcontains":
|
||||||
|
return fmt.Sprintf("field '%s' must contain '%s'", field, param)
|
||||||
|
case "fieldexcludes":
|
||||||
|
return fmt.Sprintf("field '%s' must not contain '%s'", field, param)
|
||||||
|
// String format
|
||||||
|
case "alpha":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only letters", field)
|
||||||
|
case "alphaspace":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only letters and spaces", field)
|
||||||
|
case "alphanum":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only letters and digits", field)
|
||||||
|
case "alphanumspace":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only letters, digits, and spaces", field)
|
||||||
|
case "alphanumunicode":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only unicode letters and digits", field)
|
||||||
|
case "alphaunicode":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only unicode letters", field)
|
||||||
|
case "ascii":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only ASCII characters", field)
|
||||||
|
case "printascii":
|
||||||
|
return fmt.Sprintf("field '%s' must contain only printable ASCII characters", field)
|
||||||
|
case "multibyte":
|
||||||
|
return fmt.Sprintf("field '%s' must contain multi-byte characters", field)
|
||||||
|
case "boolean":
|
||||||
|
return fmt.Sprintf("field '%s' must be a boolean value", field)
|
||||||
|
case "number":
|
||||||
|
return fmt.Sprintf("field '%s' must be a number", field)
|
||||||
|
case "numeric":
|
||||||
|
return fmt.Sprintf("field '%s' must be a numeric string", field)
|
||||||
|
case "lowercase":
|
||||||
|
return fmt.Sprintf("field '%s' must be lowercase", field)
|
||||||
|
case "uppercase":
|
||||||
|
return fmt.Sprintf("field '%s' must be uppercase", field)
|
||||||
|
// String content
|
||||||
|
case "contains":
|
||||||
|
return fmt.Sprintf("field '%s' must contain '%s'", field, param)
|
||||||
|
case "containsany":
|
||||||
|
return fmt.Sprintf("field '%s' must contain at least one of '%s'", field, param)
|
||||||
|
case "containsrune":
|
||||||
|
return fmt.Sprintf("field '%s' must contain the character '%s'", field, param)
|
||||||
|
case "excludes":
|
||||||
|
return fmt.Sprintf("field '%s' must not contain '%s'", field, param)
|
||||||
|
case "excludesall":
|
||||||
|
return fmt.Sprintf("field '%s' must not contain any of '%s'", field, param)
|
||||||
|
case "excludesrune":
|
||||||
|
return fmt.Sprintf("field '%s' must not contain the character '%s'", field, param)
|
||||||
|
case "startswith":
|
||||||
|
return fmt.Sprintf("field '%s' must start with '%s'", field, param)
|
||||||
|
case "startsnotwith":
|
||||||
|
return fmt.Sprintf("field '%s' must not start with '%s'", field, param)
|
||||||
|
case "endswith":
|
||||||
|
return fmt.Sprintf("field '%s' must end with '%s'", field, param)
|
||||||
|
case "endsnotwith":
|
||||||
|
return fmt.Sprintf("field '%s' must not end with '%s'", field, param)
|
||||||
|
// Network
|
||||||
|
case "ip", "ip_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid IP address", field)
|
||||||
|
case "ipv4", "ip4_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid IPv4 address", field)
|
||||||
|
case "ipv6", "ip6_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid IPv6 address", field)
|
||||||
|
case "cidr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid CIDR notation address", field)
|
||||||
|
case "cidrv4":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid IPv4 CIDR notation address", field)
|
||||||
|
case "cidrv6":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid IPv6 CIDR notation address", field)
|
||||||
|
case "mac":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid MAC address", field)
|
||||||
|
case "hostname":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RFC 952 hostname", field)
|
||||||
|
case "hostname_rfc1123":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RFC 1123 hostname", field)
|
||||||
|
case "hostname_port":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid host:port pair", field)
|
||||||
|
case "port":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid port number", field)
|
||||||
|
case "fqdn":
|
||||||
|
return fmt.Sprintf("field '%s' must be a fully qualified domain name", field)
|
||||||
|
case "tcp4_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid TCPv4 address", field)
|
||||||
|
case "tcp6_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid TCPv6 address", field)
|
||||||
|
case "tcp_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid TCP address", field)
|
||||||
|
case "udp4_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid UDPv4 address", field)
|
||||||
|
case "udp6_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid UDPv6 address", field)
|
||||||
|
case "udp_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid UDP address", field)
|
||||||
|
case "unix_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid Unix domain socket address", field)
|
||||||
|
case "uds_exists":
|
||||||
|
return fmt.Sprintf("field '%s' must be an existing Unix domain socket", field)
|
||||||
|
case "uri":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid URI", field)
|
||||||
|
case "url":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid URL", field)
|
||||||
|
case "http_url":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid HTTP or HTTPS URL", field)
|
||||||
|
case "https_url":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid HTTPS URL", field)
|
||||||
|
case "url_encoded":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid URL-encoded string", field)
|
||||||
|
case "origin":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid web origin", field)
|
||||||
|
case "urn_rfc2141":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid URN (RFC 2141)", field)
|
||||||
|
case "datauri":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid data URI", field)
|
||||||
|
// Format / identity
|
||||||
|
case "email":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid email address", field)
|
||||||
|
case "uuid":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid UUID", field)
|
||||||
|
case "uuid3":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid version 3 UUID", field)
|
||||||
|
case "uuid3_rfc4122":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RFC 4122 version 3 UUID", field)
|
||||||
|
case "uuid4":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid version 4 UUID", field)
|
||||||
|
case "uuid4_rfc4122":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RFC 4122 version 4 UUID", field)
|
||||||
|
case "uuid5":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid version 5 UUID", field)
|
||||||
|
case "uuid5_rfc4122":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RFC 4122 version 5 UUID", field)
|
||||||
|
case "uuid_rfc4122":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RFC 4122 UUID", field)
|
||||||
|
case "ulid":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ULID", field)
|
||||||
|
case "e164":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid E.164 phone number", field)
|
||||||
|
case "isbn":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISBN", field)
|
||||||
|
case "isbn10":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISBN-10", field)
|
||||||
|
case "isbn13":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISBN-13", field)
|
||||||
|
case "issn":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISSN", field)
|
||||||
|
case "credit_card":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid credit card number", field)
|
||||||
|
case "ssn":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid Social Security Number", field)
|
||||||
|
case "ein":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid EIN", field)
|
||||||
|
case "latitude":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid latitude", field)
|
||||||
|
case "longitude":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid longitude", field)
|
||||||
|
case "timezone":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid IANA timezone", field)
|
||||||
|
case "datetime":
|
||||||
|
return fmt.Sprintf("field '%s' must match the datetime format '%s'", field, param)
|
||||||
|
case "json":
|
||||||
|
return fmt.Sprintf("field '%s' must be valid JSON", field)
|
||||||
|
case "jwt":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid JWT", field)
|
||||||
|
case "semver":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid semantic version", field)
|
||||||
|
case "cve":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid CVE identifier", field)
|
||||||
|
case "cron":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid cron expression", field)
|
||||||
|
case "spicedb":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid SpiceDB identifier", field)
|
||||||
|
// Encoding / hash
|
||||||
|
case "base64":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid base64-encoded string", field)
|
||||||
|
case "base64url":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid base64url-encoded string", field)
|
||||||
|
case "base64rawurl":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid base64rawurl-encoded string", field)
|
||||||
|
case "hexadecimal":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid hexadecimal string", field)
|
||||||
|
case "md4":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid MD4 hash", field)
|
||||||
|
case "md5":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid MD5 hash", field)
|
||||||
|
case "sha256":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid SHA-256 hash", field)
|
||||||
|
case "sha384":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid SHA-384 hash", field)
|
||||||
|
case "sha512":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid SHA-512 hash", field)
|
||||||
|
case "ripemd128":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RIPEMD-128 hash", field)
|
||||||
|
case "ripemd160":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RIPEMD-160 hash", field)
|
||||||
|
case "tiger128":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid TIGER-128 hash", field)
|
||||||
|
case "tiger160":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid TIGER-160 hash", field)
|
||||||
|
case "tiger192":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid TIGER-192 hash", field)
|
||||||
|
case "luhn_checksum":
|
||||||
|
return fmt.Sprintf("field '%s' must pass the Luhn checksum", field)
|
||||||
|
// Color
|
||||||
|
case "hexcolor":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid hexadecimal color code", field)
|
||||||
|
case "rgb":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RGB color", field)
|
||||||
|
case "rgba":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid RGBA color", field)
|
||||||
|
case "hsl":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid HSL color", field)
|
||||||
|
case "hsla":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid HSLA color", field)
|
||||||
|
case "cmyk":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid CMYK color", field)
|
||||||
|
case "iscolor":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid color (hex, RGB, RGBA, HSL, HSLA, or CMYK)", field)
|
||||||
|
// HTML
|
||||||
|
case "html":
|
||||||
|
return fmt.Sprintf("field '%s' must contain valid HTML", field)
|
||||||
|
case "html_encoded":
|
||||||
|
return fmt.Sprintf("field '%s' must be HTML-encoded", field)
|
||||||
|
// International standards
|
||||||
|
case "iso3166_1_alpha2":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISO 3166-1 alpha-2 country code", field)
|
||||||
|
case "iso3166_1_alpha3":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISO 3166-1 alpha-3 country code", field)
|
||||||
|
case "iso3166_1_alpha_numeric":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISO 3166-1 numeric country code", field)
|
||||||
|
case "iso3166_2":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISO 3166-2 subdivision code", field)
|
||||||
|
case "iso4217":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISO 4217 currency code", field)
|
||||||
|
case "country_code":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid ISO 3166 country code", field)
|
||||||
|
case "bcp47_language_tag":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid BCP 47 language tag", field)
|
||||||
|
case "bcp47_strict_language_tag":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid BCP 47 language tag (RFC 5646)", field)
|
||||||
|
case "postcode_iso3166_alpha2", "postcode_iso3166_alpha2_field":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid postcode", field)
|
||||||
|
// Crypto / blockchain
|
||||||
|
case "btc_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid Bitcoin address", field)
|
||||||
|
case "btc_addr_bech32":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid Bitcoin Bech32 address", field)
|
||||||
|
case "eth_addr":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid Ethereum address", field)
|
||||||
|
// Database
|
||||||
|
case "mongodb":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid MongoDB ObjectID", field)
|
||||||
|
case "mongodb_connection_string":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid MongoDB connection string", field)
|
||||||
|
// Business identity
|
||||||
|
case "bic_iso_9362_2014":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid BIC (ISO 9362:2014)", field)
|
||||||
|
case "bic":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid BIC (ISO 9362:2022)", field)
|
||||||
|
// File system
|
||||||
|
case "dir":
|
||||||
|
return fmt.Sprintf("field '%s' must be an existing directory", field)
|
||||||
|
case "dirpath":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid directory path", field)
|
||||||
|
case "file":
|
||||||
|
return fmt.Sprintf("field '%s' must be an existing file", field)
|
||||||
|
case "filepath":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid file path", field)
|
||||||
|
case "image":
|
||||||
|
return fmt.Sprintf("field '%s' must be a valid image file", field)
|
||||||
|
case "mimetype":
|
||||||
|
return fmt.Sprintf("field '%s' must have MIME type '%s'", field, param)
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("field '%s' failed validation rule '%s'", field, tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
// Spanish (opt-in)
|
||||||
|
// ---------------------------------------------------------------
|
||||||
|
|
||||||
|
type spanishMessages struct{}
|
||||||
|
|
||||||
|
func (spanishMessages) Message(field, tag, param string) string {
|
||||||
|
switch tag {
|
||||||
|
// Required
|
||||||
|
case "required":
|
||||||
|
return fmt.Sprintf("El campo '%s' es obligatorio", field)
|
||||||
|
case "required_if", "required_unless":
|
||||||
|
return fmt.Sprintf("El campo '%s' es obligatorio", field)
|
||||||
|
case "required_with":
|
||||||
|
return fmt.Sprintf("El campo '%s' es obligatorio cuando %s está presente", field, param)
|
||||||
|
case "required_with_all":
|
||||||
|
return fmt.Sprintf("El campo '%s' es obligatorio cuando todos los [%s] están presentes", field, param)
|
||||||
|
case "required_without":
|
||||||
|
return fmt.Sprintf("El campo '%s' es obligatorio cuando %s está ausente", field, param)
|
||||||
|
case "required_without_all":
|
||||||
|
return fmt.Sprintf("El campo '%s' es obligatorio cuando todos los [%s] están ausentes", field, param)
|
||||||
|
// Excluded
|
||||||
|
case "excluded_if", "excluded_unless":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe estar definido en este contexto", field)
|
||||||
|
case "excluded_with":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe estar definido cuando %s está presente", field, param)
|
||||||
|
case "excluded_with_all":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe estar definido cuando todos los [%s] están presentes", field, param)
|
||||||
|
case "excluded_without":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe estar definido cuando %s está ausente", field, param)
|
||||||
|
case "excluded_without_all":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe estar definido cuando todos los [%s] están ausentes", field, param)
|
||||||
|
// Size / value
|
||||||
|
case "len":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe tener exactamente %s caracteres", field, param)
|
||||||
|
case "min":
|
||||||
|
return fmt.Sprintf("El campo '%s' es demasiado corto (mínimo %s)", field, param)
|
||||||
|
case "max":
|
||||||
|
return fmt.Sprintf("El campo '%s' es demasiado largo (máximo %s)", field, param)
|
||||||
|
case "eq":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser igual a %s", field, param)
|
||||||
|
case "eq_ignore_case":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser igual a %s (sin distinción de mayúsculas)", field, param)
|
||||||
|
case "ne":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe ser igual a %s", field, param)
|
||||||
|
case "ne_ignore_case":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe ser igual a %s (sin distinción de mayúsculas)", field, param)
|
||||||
|
case "gt":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser mayor que %s", field, param)
|
||||||
|
case "gte":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser mayor o igual a %s", field, param)
|
||||||
|
case "lt":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser menor que %s", field, param)
|
||||||
|
case "lte":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser menor o igual a %s", field, param)
|
||||||
|
case "oneof":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser uno de [%s]", field, param)
|
||||||
|
case "noneof":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe ser ninguno de [%s]", field, param)
|
||||||
|
case "unique":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe contener valores únicos", field)
|
||||||
|
case "isdefault":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser el valor predeterminado", field)
|
||||||
|
case "validateFn":
|
||||||
|
return fmt.Sprintf("El campo '%s' no superó la validación personalizada", field)
|
||||||
|
// Cross-field comparisons
|
||||||
|
case "eqfield", "eqcsfield":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser igual a %s", field, param)
|
||||||
|
case "nefield", "necsfield":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe ser igual a %s", field, param)
|
||||||
|
case "gtfield", "gtcsfield":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser mayor que %s", field, param)
|
||||||
|
case "gtefield", "gtecsfield":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser mayor o igual a %s", field, param)
|
||||||
|
case "ltfield", "ltcsfield":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser menor que %s", field, param)
|
||||||
|
case "ltefield", "ltecsfield":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser menor o igual a %s", field, param)
|
||||||
|
case "fieldcontains":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe contener '%s'", field, param)
|
||||||
|
case "fieldexcludes":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe contener '%s'", field, param)
|
||||||
|
// String format
|
||||||
|
case "alpha":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener letras", field)
|
||||||
|
case "alphaspace":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener letras y espacios", field)
|
||||||
|
case "alphanum":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener letras y dígitos", field)
|
||||||
|
case "alphanumspace":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener letras, dígitos y espacios", field)
|
||||||
|
case "alphanumunicode":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener letras y dígitos Unicode", field)
|
||||||
|
case "alphaunicode":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener letras Unicode", field)
|
||||||
|
case "ascii":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener caracteres ASCII", field)
|
||||||
|
case "printascii":
|
||||||
|
return fmt.Sprintf("El campo '%s' solo debe contener caracteres ASCII imprimibles", field)
|
||||||
|
case "multibyte":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe contener caracteres multibyte", field)
|
||||||
|
case "boolean":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un valor booleano", field)
|
||||||
|
case "number":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un número", field)
|
||||||
|
case "numeric":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una cadena numérica", field)
|
||||||
|
case "lowercase":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe estar en minúsculas", field)
|
||||||
|
case "uppercase":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe estar en mayúsculas", field)
|
||||||
|
// String content
|
||||||
|
case "contains":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe contener '%s'", field, param)
|
||||||
|
case "containsany":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe contener al menos uno de '%s'", field, param)
|
||||||
|
case "containsrune":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe contener el carácter '%s'", field, param)
|
||||||
|
case "excludes":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe contener '%s'", field, param)
|
||||||
|
case "excludesall":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe contener ninguno de '%s'", field, param)
|
||||||
|
case "excludesrune":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe contener el carácter '%s'", field, param)
|
||||||
|
case "startswith":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe comenzar con '%s'", field, param)
|
||||||
|
case "startsnotwith":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe comenzar con '%s'", field, param)
|
||||||
|
case "endswith":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe terminar con '%s'", field, param)
|
||||||
|
case "endsnotwith":
|
||||||
|
return fmt.Sprintf("El campo '%s' no debe terminar con '%s'", field, param)
|
||||||
|
// Network
|
||||||
|
case "ip", "ip_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección IP válida", field)
|
||||||
|
case "ipv4", "ip4_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección IPv4 válida", field)
|
||||||
|
case "ipv6", "ip6_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección IPv6 válida", field)
|
||||||
|
case "cidr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección CIDR válida", field)
|
||||||
|
case "cidrv4":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección CIDR IPv4 válida", field)
|
||||||
|
case "cidrv6":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección CIDR IPv6 válida", field)
|
||||||
|
case "mac":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección MAC válida", field)
|
||||||
|
case "hostname":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un nombre de host válido (RFC 952)", field)
|
||||||
|
case "hostname_rfc1123":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un nombre de host válido (RFC 1123)", field)
|
||||||
|
case "hostname_port":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un par host:puerto válido", field)
|
||||||
|
case "port":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un número de puerto válido", field)
|
||||||
|
case "fqdn":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un nombre de dominio completamente calificado", field)
|
||||||
|
case "tcp4_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección TCPv4 válida", field)
|
||||||
|
case "tcp6_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección TCPv6 válida", field)
|
||||||
|
case "tcp_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección TCP válida", field)
|
||||||
|
case "udp4_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección UDPv4 válida", field)
|
||||||
|
case "udp6_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección UDPv6 válida", field)
|
||||||
|
case "udp_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección UDP válida", field)
|
||||||
|
case "unix_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección de socket Unix válida", field)
|
||||||
|
case "uds_exists":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un socket de dominio Unix existente", field)
|
||||||
|
case "uri":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un URI válido", field)
|
||||||
|
case "url":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una URL válida", field)
|
||||||
|
case "http_url":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una URL HTTP o HTTPS válida", field)
|
||||||
|
case "https_url":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una URL HTTPS válida", field)
|
||||||
|
case "url_encoded":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una cadena codificada en URL válida", field)
|
||||||
|
case "origin":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un origen web válido", field)
|
||||||
|
case "urn_rfc2141":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un URN válido (RFC 2141)", field)
|
||||||
|
case "datauri":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un URI de datos válido", field)
|
||||||
|
// Format / identity
|
||||||
|
case "email":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un correo electrónico válido", field)
|
||||||
|
case "uuid":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID válido", field)
|
||||||
|
case "uuid3":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID versión 3 válido", field)
|
||||||
|
case "uuid3_rfc4122":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID RFC 4122 versión 3 válido", field)
|
||||||
|
case "uuid4":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID versión 4 válido", field)
|
||||||
|
case "uuid4_rfc4122":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID RFC 4122 versión 4 válido", field)
|
||||||
|
case "uuid5":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID versión 5 válido", field)
|
||||||
|
case "uuid5_rfc4122":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID RFC 4122 versión 5 válido", field)
|
||||||
|
case "uuid_rfc4122":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un UUID RFC 4122 válido", field)
|
||||||
|
case "ulid":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un ULID válido", field)
|
||||||
|
case "e164":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un número de teléfono E.164 válido", field)
|
||||||
|
case "isbn":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un ISBN válido", field)
|
||||||
|
case "isbn10":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un ISBN-10 válido", field)
|
||||||
|
case "isbn13":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un ISBN-13 válido", field)
|
||||||
|
case "issn":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un ISSN válido", field)
|
||||||
|
case "credit_card":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un número de tarjeta de crédito válido", field)
|
||||||
|
case "ssn":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un número de seguro social válido", field)
|
||||||
|
case "ein":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un EIN válido", field)
|
||||||
|
case "latitude":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una latitud válida", field)
|
||||||
|
case "longitude":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una longitud válida", field)
|
||||||
|
case "timezone":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una zona horaria IANA válida", field)
|
||||||
|
case "datetime":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe coincidir con el formato de fecha '%s'", field, param)
|
||||||
|
case "json":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser JSON válido", field)
|
||||||
|
case "jwt":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un JWT válido", field)
|
||||||
|
case "semver":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una versión semántica válida", field)
|
||||||
|
case "cve":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un identificador CVE válido", field)
|
||||||
|
case "cron":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una expresión cron válida", field)
|
||||||
|
case "spicedb":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un identificador SpiceDB válido", field)
|
||||||
|
// Encoding / hash
|
||||||
|
case "base64":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una cadena base64 válida", field)
|
||||||
|
case "base64url":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una cadena base64url válida", field)
|
||||||
|
case "base64rawurl":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una cadena base64rawurl válida", field)
|
||||||
|
case "hexadecimal":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una cadena hexadecimal válida", field)
|
||||||
|
case "md4":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash MD4 válido", field)
|
||||||
|
case "md5":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash MD5 válido", field)
|
||||||
|
case "sha256":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash SHA-256 válido", field)
|
||||||
|
case "sha384":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash SHA-384 válido", field)
|
||||||
|
case "sha512":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash SHA-512 válido", field)
|
||||||
|
case "ripemd128":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash RIPEMD-128 válido", field)
|
||||||
|
case "ripemd160":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash RIPEMD-160 válido", field)
|
||||||
|
case "tiger128":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash TIGER-128 válido", field)
|
||||||
|
case "tiger160":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash TIGER-160 válido", field)
|
||||||
|
case "tiger192":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un hash TIGER-192 válido", field)
|
||||||
|
case "luhn_checksum":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe pasar la suma de verificación Luhn", field)
|
||||||
|
// Color
|
||||||
|
case "hexcolor":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código de color hexadecimal válido", field)
|
||||||
|
case "rgb":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un color RGB válido", field)
|
||||||
|
case "rgba":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un color RGBA válido", field)
|
||||||
|
case "hsl":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un color HSL válido", field)
|
||||||
|
case "hsla":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un color HSLA válido", field)
|
||||||
|
case "cmyk":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un color CMYK válido", field)
|
||||||
|
case "iscolor":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un color válido (hex, RGB, RGBA, HSL, HSLA o CMYK)", field)
|
||||||
|
// HTML
|
||||||
|
case "html":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe contener HTML válido", field)
|
||||||
|
case "html_encoded":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe estar codificado en HTML", field)
|
||||||
|
// International standards
|
||||||
|
case "iso3166_1_alpha2":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código de país ISO 3166-1 alpha-2 válido", field)
|
||||||
|
case "iso3166_1_alpha3":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código de país ISO 3166-1 alpha-3 válido", field)
|
||||||
|
case "iso3166_1_alpha_numeric":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código de país ISO 3166-1 numérico válido", field)
|
||||||
|
case "iso3166_2":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código de subdivisión ISO 3166-2 válido", field)
|
||||||
|
case "iso4217":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código de moneda ISO 4217 válido", field)
|
||||||
|
case "country_code":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código de país ISO 3166 válido", field)
|
||||||
|
case "bcp47_language_tag":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una etiqueta de idioma BCP 47 válida", field)
|
||||||
|
case "bcp47_strict_language_tag":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una etiqueta de idioma BCP 47 válida (RFC 5646)", field)
|
||||||
|
case "postcode_iso3166_alpha2", "postcode_iso3166_alpha2_field":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un código postal válido", field)
|
||||||
|
// Crypto / blockchain
|
||||||
|
case "btc_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección Bitcoin válida", field)
|
||||||
|
case "btc_addr_bech32":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección Bitcoin Bech32 válida", field)
|
||||||
|
case "eth_addr":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una dirección Ethereum válida", field)
|
||||||
|
// Database
|
||||||
|
case "mongodb":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un ObjectID de MongoDB válido", field)
|
||||||
|
case "mongodb_connection_string":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una cadena de conexión de MongoDB válida", field)
|
||||||
|
// Business identity
|
||||||
|
case "bic_iso_9362_2014":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un BIC válido (ISO 9362:2014)", field)
|
||||||
|
case "bic":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un BIC válido (ISO 9362:2022)", field)
|
||||||
|
// File system
|
||||||
|
case "dir":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un directorio existente", field)
|
||||||
|
case "dirpath":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una ruta de directorio válida", field)
|
||||||
|
case "file":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un archivo existente", field)
|
||||||
|
case "filepath":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser una ruta de archivo válida", field)
|
||||||
|
case "image":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe ser un archivo de imagen válido", field)
|
||||||
|
case "mimetype":
|
||||||
|
return fmt.Sprintf("El campo '%s' debe tener el tipo MIME '%s'", field, param)
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("Error en el campo '%s': regla '%s' no cumplida", field, tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
31
valid/option.go
Normal file
31
valid/option.go
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
package valid
|
||||||
|
|
||||||
|
// Option configures a Validator.
|
||||||
|
type Option func(*config)
|
||||||
|
|
||||||
|
// WithMessageProvider sets a custom MessageProvider.
|
||||||
|
// Default: DefaultMessages (English).
|
||||||
|
func WithMessageProvider(mp MessageProvider) Option {
|
||||||
|
return func(c *config) {
|
||||||
|
c.mp = mp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithCustomValidator registers a custom validation tag and its function.
|
||||||
|
// The tag can then be used in struct tags: validate:"mytag" or validate:"mytag=param".
|
||||||
|
// Panics if registration fails (empty tag or tag that conflicts with a built-in).
|
||||||
|
func WithCustomValidator(tag string, fn func(FieldLevel) bool) Option {
|
||||||
|
return func(c *config) {
|
||||||
|
c.customValidators = append(c.customValidators, customValidator{tag: tag, fn: fn})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type customValidator struct {
|
||||||
|
tag string
|
||||||
|
fn func(FieldLevel) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type config struct {
|
||||||
|
mp MessageProvider
|
||||||
|
customValidators []customValidator
|
||||||
|
}
|
||||||
85
valid/validator.go
Normal file
85
valid/validator.go
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
package valid
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/core/xerrors"
|
||||||
|
playground "github.com/go-playground/validator/v10"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Validator validates structs using struct tags.
|
||||||
|
type Validator interface {
|
||||||
|
// Struct validates v and returns a *xerrors.Err if validation fails.
|
||||||
|
// Returns nil if v is valid.
|
||||||
|
// Returns ErrInvalidInput for field constraint failures (first error only).
|
||||||
|
// Returns ErrInternal if v is not a struct.
|
||||||
|
Struct(v any) error
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ Validator = (*validator)(nil)
|
||||||
|
|
||||||
|
// New returns a Validator. Without options, DefaultMessages (English) is used.
|
||||||
|
// Field names in error context use the json struct tag when available,
|
||||||
|
// falling back to the Go field name.
|
||||||
|
func New(opts ...Option) Validator {
|
||||||
|
cfg := &config{mp: DefaultMessages}
|
||||||
|
for _, o := range opts {
|
||||||
|
o(cfg)
|
||||||
|
}
|
||||||
|
v := playground.New()
|
||||||
|
v.RegisterTagNameFunc(func(fld reflect.StructField) string {
|
||||||
|
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
|
||||||
|
if name == "" || name == "-" {
|
||||||
|
return fld.Name
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
})
|
||||||
|
for _, cv := range cfg.customValidators {
|
||||||
|
if err := v.RegisterValidation(cv.tag, func(fl playground.FieldLevel) bool {
|
||||||
|
return cv.fn(fieldLevelAdapter{fl})
|
||||||
|
}); err != nil {
|
||||||
|
panic("valid: WithCustomValidator tag " + cv.tag + ": " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &validator{v: v, mp: cfg.mp}
|
||||||
|
}
|
||||||
|
|
||||||
|
type fieldLevelAdapter struct{ fl playground.FieldLevel }
|
||||||
|
|
||||||
|
func (a fieldLevelAdapter) Field() reflect.Value { return a.fl.Field() }
|
||||||
|
func (a fieldLevelAdapter) Param() string { return a.fl.Param() }
|
||||||
|
func (a fieldLevelAdapter) FieldName() string { return a.fl.FieldName() }
|
||||||
|
|
||||||
|
type validator struct {
|
||||||
|
v *playground.Validate
|
||||||
|
mp MessageProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// Struct implements Validator.
|
||||||
|
// Only the first validation error is surfaced. Apps needing all failures can
|
||||||
|
// cast errors.Unwrap(err) to playground.ValidationErrors themselves.
|
||||||
|
func (val *validator) Struct(v any) error {
|
||||||
|
err := val.v.Struct(v)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var invalidErr *playground.InvalidValidationError
|
||||||
|
if errors.As(err, &invalidErr) {
|
||||||
|
return xerrors.Wrap(xerrors.ErrInternal, "internal validation error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var validationErrs playground.ValidationErrors
|
||||||
|
if errors.As(err, &validationErrs) {
|
||||||
|
first := validationErrs[0]
|
||||||
|
msg := val.mp.Message(first.Field(), first.Tag(), first.Param())
|
||||||
|
return xerrors.New(xerrors.ErrInvalidInput, msg).
|
||||||
|
WithContext("field", first.Field()).
|
||||||
|
WithContext("tag", first.Tag()).
|
||||||
|
WithError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return xerrors.Wrap(xerrors.ErrInternal, "internal validation error", err)
|
||||||
|
}
|
||||||
124
xerrors/code.go
Normal file
124
xerrors/code.go
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
package xerrors
|
||||||
|
|
||||||
|
// Code is the machine-readable error category.
|
||||||
|
// Wire values are stable across versions and are identical to gRPC status code
|
||||||
|
// names. HTTP mapping is the responsibility of the transport layer, not this package.
|
||||||
|
type Code string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// ErrInvalidInput indicates the request contains malformed or invalid data.
|
||||||
|
// HTTP 400 / gRPC INVALID_ARGUMENT.
|
||||||
|
ErrInvalidInput Code = "INVALID_ARGUMENT"
|
||||||
|
|
||||||
|
// ErrOutOfRange indicates a parameter or index exceeds the valid bounds.
|
||||||
|
// Use when the value itself is well-formed but falls outside accepted limits
|
||||||
|
// (e.g. page number past the last page, offset past end of file).
|
||||||
|
// HTTP 400 / gRPC OUT_OF_RANGE.
|
||||||
|
ErrOutOfRange Code = "OUT_OF_RANGE"
|
||||||
|
|
||||||
|
// ErrUnauthorized indicates the request lacks valid authentication credentials.
|
||||||
|
// HTTP 401 / gRPC UNAUTHENTICATED.
|
||||||
|
ErrUnauthorized Code = "UNAUTHENTICATED"
|
||||||
|
|
||||||
|
// ErrPermissionDenied indicates the authenticated caller lacks permission for
|
||||||
|
// the operation. Authentication is not the issue.
|
||||||
|
// HTTP 403 / gRPC PERMISSION_DENIED.
|
||||||
|
ErrPermissionDenied Code = "PERMISSION_DENIED"
|
||||||
|
|
||||||
|
// ErrNotFound indicates the requested resource does not exist.
|
||||||
|
// HTTP 404 / gRPC NOT_FOUND.
|
||||||
|
ErrNotFound Code = "NOT_FOUND"
|
||||||
|
|
||||||
|
// ErrAlreadyExists indicates a resource with the same identifier already exists.
|
||||||
|
// Use for creation conflicts (e.g. duplicate email on sign-up).
|
||||||
|
// HTTP 409 / gRPC ALREADY_EXISTS.
|
||||||
|
ErrAlreadyExists Code = "ALREADY_EXISTS"
|
||||||
|
|
||||||
|
// ErrAborted indicates the operation was aborted due to a concurrent modification
|
||||||
|
// or transaction conflict. Unlike ErrAlreadyExists (creation conflict) and
|
||||||
|
// ErrPreconditionFailed (business rule), this signals the caller may retry.
|
||||||
|
// HTTP 409 / gRPC ABORTED.
|
||||||
|
ErrAborted Code = "ABORTED"
|
||||||
|
|
||||||
|
// ErrGone indicates the resource existed but has been permanently removed.
|
||||||
|
// Unlike ErrNotFound, this signals the caller should not retry.
|
||||||
|
// HTTP 410 / non-standard gRPC extension.
|
||||||
|
ErrGone Code = "GONE"
|
||||||
|
|
||||||
|
// ErrPreconditionFailed indicates a required business condition was not met.
|
||||||
|
// The input is valid but a rule blocks the action (e.g. "cannot delete an
|
||||||
|
// account with active subscriptions").
|
||||||
|
// HTTP 412 / gRPC FAILED_PRECONDITION.
|
||||||
|
ErrPreconditionFailed Code = "FAILED_PRECONDITION"
|
||||||
|
|
||||||
|
// ErrRateLimited indicates the caller has exceeded a rate limit or quota.
|
||||||
|
// HTTP 429 / gRPC RESOURCE_EXHAUSTED.
|
||||||
|
ErrRateLimited Code = "RESOURCE_EXHAUSTED"
|
||||||
|
|
||||||
|
// ErrCancelled indicates the operation was cancelled by the caller.
|
||||||
|
// HTTP 499 / gRPC CANCELLED.
|
||||||
|
ErrCancelled Code = "CANCELLED"
|
||||||
|
|
||||||
|
// ErrInternal indicates an unexpected server-side failure.
|
||||||
|
// Use a more specific code when one applies.
|
||||||
|
// HTTP 500 / gRPC INTERNAL.
|
||||||
|
ErrInternal Code = "INTERNAL"
|
||||||
|
|
||||||
|
// ErrDataLoss indicates unrecoverable data loss or corruption.
|
||||||
|
// Reserved for storage-layer integrity failures.
|
||||||
|
// HTTP 500 / gRPC DATA_LOSS.
|
||||||
|
ErrDataLoss Code = "DATA_LOSS"
|
||||||
|
|
||||||
|
// ErrNotImplemented indicates the requested operation has not been implemented.
|
||||||
|
// HTTP 501 / gRPC UNIMPLEMENTED.
|
||||||
|
ErrNotImplemented Code = "UNIMPLEMENTED"
|
||||||
|
|
||||||
|
// ErrUnavailable indicates the service is temporarily unable to handle requests.
|
||||||
|
// HTTP 503 / gRPC UNAVAILABLE.
|
||||||
|
ErrUnavailable Code = "UNAVAILABLE"
|
||||||
|
|
||||||
|
// ErrDeadlineExceeded indicates the operation timed out before completing.
|
||||||
|
// HTTP 504 / gRPC DEADLINE_EXCEEDED.
|
||||||
|
ErrDeadlineExceeded Code = "DEADLINE_EXCEEDED"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Description returns a human-readable description for the code.
|
||||||
|
// Unknown codes return their raw string value.
|
||||||
|
func (c Code) Description() string {
|
||||||
|
switch c {
|
||||||
|
case ErrInvalidInput:
|
||||||
|
return "Invalid input provided"
|
||||||
|
case ErrOutOfRange:
|
||||||
|
return "Value out of valid range"
|
||||||
|
case ErrUnauthorized:
|
||||||
|
return "Authentication required"
|
||||||
|
case ErrPermissionDenied:
|
||||||
|
return "Insufficient permissions"
|
||||||
|
case ErrNotFound:
|
||||||
|
return "Resource not found"
|
||||||
|
case ErrAlreadyExists:
|
||||||
|
return "Resource already exists"
|
||||||
|
case ErrAborted:
|
||||||
|
return "Operation aborted due to concurrent modification"
|
||||||
|
case ErrGone:
|
||||||
|
return "Resource permanently deleted"
|
||||||
|
case ErrPreconditionFailed:
|
||||||
|
return "Precondition not met"
|
||||||
|
case ErrRateLimited:
|
||||||
|
return "Rate limit exceeded"
|
||||||
|
case ErrCancelled:
|
||||||
|
return "Request cancelled"
|
||||||
|
case ErrInternal:
|
||||||
|
return "Internal error"
|
||||||
|
case ErrDataLoss:
|
||||||
|
return "Unrecoverable data loss or corruption"
|
||||||
|
case ErrNotImplemented:
|
||||||
|
return "Not implemented"
|
||||||
|
case ErrUnavailable:
|
||||||
|
return "Service unavailable"
|
||||||
|
case ErrDeadlineExceeded:
|
||||||
|
return "Deadline exceeded"
|
||||||
|
default:
|
||||||
|
return string(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
29
xerrors/doc.go
Normal file
29
xerrors/doc.go
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
// Package xerrors provides structured application errors with stable typed codes,
|
||||||
|
// cause chaining, and key-value context fields.
|
||||||
|
//
|
||||||
|
// Every error carries a machine-readable Code (gRPC-aligned wire value), a
|
||||||
|
// human-readable message, an optional cause, and optional structured fields.
|
||||||
|
// *Err implements errs.CodedError and errs.ContextualError from contracts,
|
||||||
|
// enabling logz to enrich log records automatically without importing this package.
|
||||||
|
//
|
||||||
|
// Usage:
|
||||||
|
//
|
||||||
|
// // Named constructors for common codes
|
||||||
|
// err := xerrors.NotFound("user %s not found", userID)
|
||||||
|
// err := xerrors.InvalidInput("email is required")
|
||||||
|
//
|
||||||
|
// // Builder pattern for structured context
|
||||||
|
// err := xerrors.New(xerrors.ErrInvalidInput, "validation failed").
|
||||||
|
// WithContext("field", "email").
|
||||||
|
// WithContext("rule", "required").
|
||||||
|
// WithError(cause)
|
||||||
|
//
|
||||||
|
// // Inspecting errors
|
||||||
|
// var e *xerrors.Err
|
||||||
|
// if errors.As(err, &e) {
|
||||||
|
// switch e.Code() {
|
||||||
|
// case xerrors.ErrNotFound:
|
||||||
|
// // handle 404
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
package xerrors
|
||||||
212
xerrors/err.go
Normal file
212
xerrors/err.go
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
package xerrors
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"code.nochebuena.dev/einherjar/contracts/errs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Compile-time proof that *Err satisfies the contracts interfaces consumed by logz.
|
||||||
|
var _ errs.CodedError = (*Err)(nil)
|
||||||
|
var _ errs.ContextualError = (*Err)(nil)
|
||||||
|
|
||||||
|
// Err is a structured application error carrying a Code, a human-readable
|
||||||
|
// message, an optional cause, and optional key-value context fields.
|
||||||
|
//
|
||||||
|
// It implements the standard error interface, errors.Unwrap for cause chaining,
|
||||||
|
// and json.Marshaler for API responses. It also satisfies errs.CodedError and
|
||||||
|
// errs.ContextualError from contracts, enabling logz to enrich log records
|
||||||
|
// automatically without importing this package.
|
||||||
|
//
|
||||||
|
// Use the builder methods WithContext, WithError, and WithPlatformCode to attach
|
||||||
|
// additional information after construction:
|
||||||
|
//
|
||||||
|
// err := xerrors.New(xerrors.ErrInvalidInput, "validation failed").
|
||||||
|
// WithContext("field", "email").
|
||||||
|
// WithContext("rule", "required").
|
||||||
|
// WithError(cause)
|
||||||
|
type Err struct {
|
||||||
|
code Code
|
||||||
|
message string
|
||||||
|
err error
|
||||||
|
fields map[string]any
|
||||||
|
platformCode string
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates an Err with the given code and message. No cause is set.
|
||||||
|
func New(code Code, message string) *Err {
|
||||||
|
return &Err{code: code, message: message}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap creates an Err that wraps an existing error with a code and message.
|
||||||
|
// The wrapped error is accessible via errors.Is, errors.As, and Err.Unwrap.
|
||||||
|
func Wrap(code Code, message string, err error) *Err {
|
||||||
|
return &Err{code: code, message: message, err: err}
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvalidInput creates an Err with ErrInvalidInput code.
|
||||||
|
func InvalidInput(msg string, args ...any) *Err {
|
||||||
|
return New(ErrInvalidInput, fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// OutOfRange creates an Err with ErrOutOfRange code.
|
||||||
|
func OutOfRange(msg string, args ...any) *Err { return New(ErrOutOfRange, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// Unauthorized creates an Err with ErrUnauthorized code.
|
||||||
|
func Unauthorized(msg string, args ...any) *Err {
|
||||||
|
return New(ErrUnauthorized, fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// PermissionDenied creates an Err with ErrPermissionDenied code.
|
||||||
|
func PermissionDenied(msg string, args ...any) *Err {
|
||||||
|
return New(ErrPermissionDenied, fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// NotFound creates an Err with ErrNotFound code.
|
||||||
|
func NotFound(msg string, args ...any) *Err { return New(ErrNotFound, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// AlreadyExists creates an Err with ErrAlreadyExists code.
|
||||||
|
func AlreadyExists(msg string, args ...any) *Err {
|
||||||
|
return New(ErrAlreadyExists, fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aborted creates an Err with ErrAborted code.
|
||||||
|
func Aborted(msg string, args ...any) *Err { return New(ErrAborted, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// Gone creates an Err with ErrGone code.
|
||||||
|
func Gone(msg string, args ...any) *Err { return New(ErrGone, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// PreconditionFailed creates an Err with ErrPreconditionFailed code.
|
||||||
|
func PreconditionFailed(msg string, args ...any) *Err {
|
||||||
|
return New(ErrPreconditionFailed, fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimited creates an Err with ErrRateLimited code.
|
||||||
|
func RateLimited(msg string, args ...any) *Err { return New(ErrRateLimited, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// Cancelled creates an Err with ErrCancelled code.
|
||||||
|
func Cancelled(msg string, args ...any) *Err { return New(ErrCancelled, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// Internal creates an Err with ErrInternal code.
|
||||||
|
func Internal(msg string, args ...any) *Err { return New(ErrInternal, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// DataLoss creates an Err with ErrDataLoss code.
|
||||||
|
func DataLoss(msg string, args ...any) *Err { return New(ErrDataLoss, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// NotImplemented creates an Err with ErrNotImplemented code.
|
||||||
|
func NotImplemented(msg string, args ...any) *Err {
|
||||||
|
return New(ErrNotImplemented, fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unavailable creates an Err with ErrUnavailable code.
|
||||||
|
func Unavailable(msg string, args ...any) *Err { return New(ErrUnavailable, fmt.Sprintf(msg, args...)) }
|
||||||
|
|
||||||
|
// DeadlineExceeded creates an Err with ErrDeadlineExceeded code.
|
||||||
|
func DeadlineExceeded(msg string, args ...any) *Err {
|
||||||
|
return New(ErrDeadlineExceeded, fmt.Sprintf(msg, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithContext adds a key-value pair to the error's context fields and returns
|
||||||
|
// the receiver for chaining. Calling it multiple times with the same key
|
||||||
|
// overwrites the previous value.
|
||||||
|
func (e *Err) WithContext(key string, value any) *Err {
|
||||||
|
if e.fields == nil {
|
||||||
|
e.fields = make(map[string]any)
|
||||||
|
}
|
||||||
|
e.fields[key] = value
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithError sets the underlying cause and returns the receiver for chaining.
|
||||||
|
func (e *Err) WithError(err error) *Err {
|
||||||
|
e.err = err
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithPlatformCode sets a platform-level error code and returns the receiver
|
||||||
|
// for chaining. Platform codes are domain-specific identifiers (e.g.
|
||||||
|
// "EMPLOYEE_NOT_FOUND") intended for consuming applications — such as a
|
||||||
|
// frontend — that need to map errors to localised user-facing messages.
|
||||||
|
//
|
||||||
|
// Platform codes are optional. Errors that have no user-actionable meaning
|
||||||
|
// (e.g. 500 internal errors) should not carry one.
|
||||||
|
func (e *Err) WithPlatformCode(code string) *Err {
|
||||||
|
e.platformCode = code
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// Code returns the typed error code.
|
||||||
|
func (e *Err) Code() Code { return e.code }
|
||||||
|
|
||||||
|
// Message returns the human-readable error message.
|
||||||
|
func (e *Err) Message() string { return e.message }
|
||||||
|
|
||||||
|
// PlatformCode returns the platform-level error code, or "" if none was set.
|
||||||
|
func (e *Err) PlatformCode() string { return e.platformCode }
|
||||||
|
|
||||||
|
// Fields returns a shallow copy of the context fields.
|
||||||
|
// Returns an empty (non-nil) map if no fields have been set.
|
||||||
|
func (e *Err) Fields() map[string]any {
|
||||||
|
if len(e.fields) == 0 {
|
||||||
|
return map[string]any{}
|
||||||
|
}
|
||||||
|
out := make(map[string]any, len(e.fields))
|
||||||
|
for k, v := range e.fields {
|
||||||
|
out[k] = v
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detailed returns a verbose string useful for debugging.
|
||||||
|
// Format: "code: X | message: Y | cause: Z | fields: {...}"
|
||||||
|
func (e *Err) Detailed() string {
|
||||||
|
s := fmt.Sprintf("code: %s | message: %s", e.code, e.message)
|
||||||
|
if e.err != nil {
|
||||||
|
s = fmt.Sprintf("%s | cause: %v", s, e.err)
|
||||||
|
}
|
||||||
|
if len(e.fields) > 0 {
|
||||||
|
s = fmt.Sprintf("%s | fields: %v", s, e.fields)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error implements the error interface.
|
||||||
|
// Format: "INVALID_ARGUMENT: username is required → original cause"
|
||||||
|
func (e *Err) Error() string {
|
||||||
|
base := fmt.Sprintf("%s: %s", e.code, e.message)
|
||||||
|
if e.err != nil {
|
||||||
|
base = fmt.Sprintf("%s → %v", base, e.err)
|
||||||
|
}
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap returns the underlying cause, enabling errors.Is and errors.As
|
||||||
|
// to walk the full cause chain.
|
||||||
|
func (e *Err) Unwrap() error { return e.err }
|
||||||
|
|
||||||
|
// ErrorCode satisfies errs.CodedError. logz calls this to append error_code
|
||||||
|
// to log records without importing this package.
|
||||||
|
func (e *Err) ErrorCode() string { return string(e.code) }
|
||||||
|
|
||||||
|
// ErrorContext satisfies errs.ContextualError. logz calls this to append
|
||||||
|
// context fields to log records. The returned map is read-only by logz;
|
||||||
|
// use Fields() if you need a safe copy.
|
||||||
|
func (e *Err) ErrorContext() map[string]any { return e.fields }
|
||||||
|
|
||||||
|
// MarshalJSON implements json.Marshaler.
|
||||||
|
// Output: {"code":"NOT_FOUND","platform_code":"...","message":"...","fields":{...}}
|
||||||
|
// platform_code and fields are omitted when empty.
|
||||||
|
func (e *Err) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
PlatformCode string `json:"platform_code,omitempty"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Fields map[string]any `json:"fields,omitempty"`
|
||||||
|
}{
|
||||||
|
Code: string(e.code),
|
||||||
|
PlatformCode: e.platformCode,
|
||||||
|
Message: e.message,
|
||||||
|
Fields: e.fields,
|
||||||
|
})
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user