engine

package
v0.0.0-...-41a30da Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package core provides the fundamental building blocks of an Astra application, including the IoC Container and the Application lifecycle manager.

Astra applications are built around the concept of Service Providers which allow for modular, decoupled growth of the framework and user applications.

Core responsibilities:

  • Container: Typed Dependency Injection and service resolution.
  • Application: Managing the startup and shutdown sequence (hooks).
  • Configuration: Unified access to environment variables and config files.
  • Logger: Standardized slog-based logging across all framework components.

Index

Constants

View Source
const (
	RequestIDKey contextKey = "request_id"
	TraceIDKey   contextKey = "trace_id"
)

Variables

This section is empty.

Functions

func WithContext

func WithContext(ctx context.Context, logger *slog.Logger) *slog.Logger

WithContext returns a logger that includes attributes from the context. It looks for request_id and trace_id.

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is the pure Lifecycle Manager of the Astra framework. It manages the application context, startup/shutdown hooks, and providers. It no longer acts as a service locator; services are explicitly injected into components via Wire.

func New

func New(
	config *config.AstraConfig,
	env *config.Config,
	logger *slog.Logger,
) *App

New creates a new Astra application kernel with minimal core dependencies.

func (*App) BaseContext

func (a *App) BaseContext() context.Context

BaseContext returns the application's base context.

func (*App) Boot

func (a *App) Boot() error

Boot initializes all registered providers in a strict three-phase sequence: Register → Boot → Ready. The Ready phase only executes once all providers have completed their Boot phase. OnStart hooks are wrapped in a 30s timeout.

func (*App) Config

func (a *App) Config() *config.AstraConfig

Config returns the application configuration.

func (*App) Env

func (a *App) Env() *config.Config

Env returns the environment variables.

func (*App) GetHealthChecks

func (a *App) GetHealthChecks() map[string]HealthProvider

GetHealthChecks returns all registered health providers. This method is thread-safe and returns a point-in-time snapshot of health checks.

func (*App) Logger

func (a *App) Logger() *slog.Logger

Logger returns the application logger.

func (*App) OnStart

func (a *App) OnStart(fn func(context.Context) error)

OnStart registers a hook to run when the app boots. This method is thread-safe and wraps hooks with context protection during execution.

func (*App) OnStop

func (a *App) OnStop(fn func(context.Context) error)

OnStop registers a shutdown hook. This method is thread-safe and hooks are executed in reverse order during shutdown.

func (*App) Recover

func (a *App) Recover()

Recover handles application panics by logging the error.

func (*App) RegisterHealthCheck

func (a *App) RegisterHealthCheck(name string, check HealthProvider)

RegisterHealthCheck registers a new health check provider. This method is thread-safe.

func (*App) RegisterProvider

func (a *App) RegisterProvider(p Provider)

RegisterProvider adds a provider to the application. This method is thread-safe.

func (*App) Run

func (a *App) Run() error

Run boots the application and blocks until a termination signal is received. It handles the full lifecycle from Boot to Graceful Shutdown.

func (*App) Shutdown

func (a *App) Shutdown() error

Shutdown gracefully stops the application. It executes onStop hooks and provider shutdown methods in reverse order of registration. Aggregates all errors encountered using errors.Join for a single cohesive return. It uses a fresh 15-second timeout context to guarantee termination.

type BaseProvider

type BaseProvider struct{}

BaseProvider provides a default implementation for Provider.

func (*BaseProvider) Boot

func (p *BaseProvider) Boot(a *App) error

func (*BaseProvider) Name

func (p *BaseProvider) Name() string

func (*BaseProvider) Ready

func (p *BaseProvider) Ready(a *App) error

func (*BaseProvider) Register

func (p *BaseProvider) Register(a *App) error

func (*BaseProvider) Shutdown

func (p *BaseProvider) Shutdown(ctx context.Context, a *App) error

type CacheStore

type CacheStore interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key string, val any, ttl time.Duration) error
}

cache

type HTTPRouter

type HTTPRouter interface {
	http.Handler
}

HTTPRouter defines the minimal interface for the application router.

type HealthCheckFunc

type HealthCheckFunc func(context.Context) error

HealthCheckFunc is a function type that implements HealthProvider.

func (HealthCheckFunc) CheckHealth

func (f HealthCheckFunc) CheckHealth(ctx context.Context) error

type HealthProvider

type HealthProvider interface {
	CheckHealth(ctx context.Context) error
}

HealthProvider defines the interface for components that can be health-checked.

type Mailer

type Mailer interface {
	Send(ctx context.Context, msg *mail.Message) error
}

mail

type Notifier

type Notifier interface {
	Notify(ctx context.Context, n any) error
}

notification

type Provider

type Provider interface {
	// Name returns the provider name for logging and debugging.
	Name() string

	// Register services in the application container.
	// Providers should use engine.Instance(a, service) or a.Container() to register
	// their managed services instead of setting fields on the App struct.
	Register(a *App) error

	// Boot the provider.
	Boot(a *App) error

	// Ready is called after all providers are booted.
	Ready(a *App) error

	// Shutdown gracefully stops the provider.
	Shutdown(ctx context.Context, a *App) error
}

Provider is the interface for Astra service providers.

type RedactingHandler

type RedactingHandler struct {
	slog.Handler
	SensitiveKeys []string
}

RedactingHandler wraps an existing slog.Handler and masks sensitive keys.

func NewRedactingHandler

func NewRedactingHandler(next slog.Handler, keys ...string) *RedactingHandler

NewRedactingHandler creates a new handler that redacts sensitive information.

func (*RedactingHandler) Enabled

func (h *RedactingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler.

func (*RedactingHandler) Handle

func (h *RedactingHandler) Handle(ctx context.Context, r slog.Record) error

Handle redacts attributes before passing them to the next handler.

func (*RedactingHandler) WithAttrs

func (h *RedactingHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.

func (*RedactingHandler) WithGroup

func (h *RedactingHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler.

type Session

type Session interface {
	Get(key string) any
	Set(key string, value any)
	Save(w http.ResponseWriter) error
}

type SessionStore

type SessionStore interface {
	Load(r *http.Request) (any, error)
	Save(w http.ResponseWriter, s any) error
}

session

type StandaloneProvider

type StandaloneProvider interface {
	// isStandalone is unexported to prevent accidental implementation.
	// Its presence on this interface is intentional: satisfy it only via embedding.
	Provider
}

StandaloneProvider is a marker interface for service packages that are designed to be used both as Astra providers (via app.Use) AND as standalone libraries in standard net/http projects without importing engine.App.

A package satisfies the standalone contract when:

  1. It exposes a NewXxx(cfg XxxConfig) constructor that does NOT accept *App.
  2. Its Register() method simply calls its own constructor and calls app.Register(name, service) — no deep App coupling.
  3. It can be compiled with only its own dependencies (no circular core import).

Current standalone packages:

  • github.com/shauryagautam/Astra/pkg/database → orm.NewStandalone(cfg)
  • github.com/shauryagautam/Astra/pkg/cache → cache.NewRedisStandalone(addr, pass, db)
  • github.com/shauryagautam/Astra/pkg/auth → auth.NewJWTStandalone(secret, opts...)

To mark your provider as standalone, embed StandaloneProvider in its doc comment or implement this interface (it has no methods — it is purely a documentation tag).

type Storage

type Storage interface {
	Put(ctx context.Context, path string, data []byte) error
	Get(ctx context.Context, path string) ([]byte, error)
}

storage

type Translator

type Translator interface {
	T(locale, key string, args ...any) string
}

i18n

type Validator

type Validator interface {
	Validate(any) error
	BindAndValidate(r *http.Request, v any) error
}

validate

type ViewEngine

type ViewEngine interface {
	Render(wr io.Writer, name string, data any) error
}

ViewEngine defines the interface for template rendering. This is defined here to avoid circular dependency with the http package.

Directories

Path Synopsis
Package config provides typed configuration loading for Astra applications.
Package config provides typed configuration loading for Astra applications.
Package events provides a lightweight, thread-safe, in-process event emitter for decoupling controllers from side-effects (emails, audit logs, etc.).
Package events provides a lightweight, thread-safe, in-process event emitter for decoupling controllers from side-effects (emails, audit logs, etc.).
Package middleware provides chaos engineering primitives for Astra.
Package middleware provides chaos engineering primitives for Astra.

Jump to

Keyboard shortcuts

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