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:
2026-05-29 15:45:12 +00:00
commit 38a415c2ab
33 changed files with 3868 additions and 0 deletions

124
xerrors/code.go Normal file
View 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
View 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
View 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,
})
}