app

package
v0.22.0 Latest Latest
Warning

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

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

Documentation

Overview

Package app provides the core application structure and lifecycle management.

Index

Constants

This section is empty.

Variables

View Source
var DefaultModuleRegistry = &MetadataRegistry{
	modules: make(map[string]ModuleInfo),
}

DefaultModuleRegistry is the global module metadata registry

View Source
var ErrNoTenantInContext = errors.New("no tenant in context")

Functions

This section is empty.

Types

type App

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

App represents the main application instance. It manages the lifecycle and coordination of all application components.

func New

func New() (*App, logger.Logger, error)

New creates a new application instance with dependencies determined by configuration. It initializes only the services that are configured, failing fast if configured services cannot connect. Returns the app instance, a logger (always available even on failure), and any error.

func NewWithConfig added in v0.4.0

func NewWithConfig(cfg *config.Config, opts *Options) (*App, logger.Logger, error)

NewWithConfig creates a new application instance with the provided config and optional overrides. This factory method allows for dependency injection while maintaining fail-fast behavior. Returns the app instance, a logger (always available even on failure), and any error.

func NewWithOptions added in v0.5.0

func NewWithOptions(opts *Options) (*App, logger.Logger, error)

NewWithOptions creates a new application instance allowing overrides for config loading and dependencies. Returns the app instance, a logger (always available even on failure), and any error.

func (*App) MessagingDeclarations added in v0.19.0

func (a *App) MessagingDeclarations() *messaging.Declarations

MessagingDeclarations returns the captured messaging declarations. This is used by tenant managers to replay infrastructure for each tenant.

func (*App) RegisterModule

func (a *App) RegisterModule(module Module) error

RegisterModule registers a new module with the application. It adds the module to the registry for initialization and route registration.

func (*App) Run

func (a *App) Run() error

Run starts the application and blocks until a shutdown signal is received. It handles graceful shutdown with a timeout.

func (*App) Shutdown

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

Shutdown gracefully shuts down the application with the given context. It closes database connections, messaging client, observability, and stops the HTTP server. Returns an aggregated error if any components fail to shut down.

type Builder added in v0.9.0

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

Builder orchestrates the step-by-step construction of an App instance using a fluent interface pattern. Each step is responsible for a single aspect of initialization, making the process clear and testable.

func NewAppBuilder added in v0.9.0

func NewAppBuilder() *Builder

NewAppBuilder creates a new app builder instance.

func (*Builder) Build added in v0.9.0

func (b *Builder) Build() (*App, logger.Logger, error)

Build returns the completed App instance, logger, or any error encountered during building. The logger is always returned, even on error, to enable proper error logging.

func (*Builder) ConfigureRuntimeHelpers added in v0.9.0

func (b *Builder) ConfigureRuntimeHelpers() *Builder

ConfigureRuntimeHelpers prepares helper components used during runtime.

func (*Builder) CreateApp added in v0.9.0

func (b *Builder) CreateApp() *Builder

CreateApp creates the core App instance with basic configuration.

func (*Builder) CreateBootstrap added in v0.9.0

func (b *Builder) CreateBootstrap() *Builder

CreateBootstrap creates the bootstrap helper for dependency resolution.

func (*Builder) CreateHealthProbes added in v0.9.0

func (b *Builder) CreateHealthProbes() *Builder

CreateHealthProbes creates health check probes for all managers.

func (*Builder) CreateLogger added in v0.9.0

func (b *Builder) CreateLogger() *Builder

CreateLogger creates and configures the application logger.

func (*Builder) Error added in v0.19.0

func (b *Builder) Error() error

Error returns any error encountered during the building process.

func (*Builder) InitializeRegistry added in v0.9.0

func (b *Builder) InitializeRegistry() *Builder

InitializeRegistry creates and configures the module registry.

func (*Builder) RegisterClosers added in v0.9.0

func (b *Builder) RegisterClosers() *Builder

RegisterClosers registers all components that need cleanup on shutdown.

func (*Builder) RegisterReadyHandler added in v0.9.0

func (b *Builder) RegisterReadyHandler() *Builder

RegisterReadyHandler registers the health check handler with the server.

func (*Builder) ResolveDependencies added in v0.9.0

func (b *Builder) ResolveDependencies() *Builder

ResolveDependencies creates and configures all application dependencies.

func (*Builder) WithConfig added in v0.9.0

func (b *Builder) WithConfig(cfg *config.Config, opts *Options) *Builder

WithConfig sets the configuration and options for the app.

type ComponentHealth added in v0.11.0

type ComponentHealth struct {
	Status   string         `json:"status"`
	Critical bool           `json:"critical"`
	Error    string         `json:"error,omitempty"`
	Details  map[string]any `json:"details"`
	LastRun  time.Time      `json:"last_run"`
	Duration string         `json:"duration"`
}

ComponentHealth contains detailed health information for a component

type ConnectionPreWarmer added in v0.9.0

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

ConnectionPreWarmer handles pre-warming of database and messaging connections for improved startup performance and health checking.

func NewConnectionPreWarmer added in v0.9.0

func NewConnectionPreWarmer(
	log logger.Logger,
	dbManager *database.DbManager,
	messagingManager *messaging.Manager,
) *ConnectionPreWarmer

NewConnectionPreWarmer creates a new connection pre-warmer.

func (*ConnectionPreWarmer) IsAvailable added in v0.9.0

func (w *ConnectionPreWarmer) IsAvailable() bool

IsAvailable returns true if both database and messaging managers are available.

func (*ConnectionPreWarmer) LogAvailability added in v0.9.0

func (w *ConnectionPreWarmer) LogAvailability()

LogAvailability logs which components are available for pre-warming.

func (*ConnectionPreWarmer) PreWarmDatabase added in v0.9.0

func (w *ConnectionPreWarmer) PreWarmDatabase(ctx context.Context, key string) error

PreWarmDatabase attempts to establish a database connection for the given key. Returns error but caller determines if it's fatal.

func (*ConnectionPreWarmer) PreWarmMessaging added in v0.9.0

func (w *ConnectionPreWarmer) PreWarmMessaging(
	ctx context.Context,
	key string,
	declarations *messaging.Declarations,
) error

PreWarmMessaging attempts to establish messaging components for the given key. This includes ensuring consumers are set up and getting a publisher. Returns error but caller determines if it's fatal.

func (*ConnectionPreWarmer) PreWarmSingleTenant added in v0.9.0

func (w *ConnectionPreWarmer) PreWarmSingleTenant(
	ctx context.Context,
	declarations *messaging.Declarations,
) error

PreWarmSingleTenant pre-warms connections for single-tenant deployments. It establishes database connections and messaging consumers/publishers upfront. Errors are logged as warnings and don't cause startup failure.

type DebugHandlers added in v0.11.0

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

DebugHandlers manages debug endpoints

func NewDebugHandlers added in v0.11.0

func NewDebugHandlers(app *App, cfg *config.DebugConfig, log logger.Logger) *DebugHandlers

NewDebugHandlers creates a new debug handlers instance

func (*DebugHandlers) RegisterDebugEndpoints added in v0.11.0

func (d *DebugHandlers) RegisterDebugEndpoints(e *echo.Echo)

RegisterDebugEndpoints registers all debug endpoints if enabled

type DebugResponse added in v0.11.0

type DebugResponse struct {
	Timestamp time.Time `json:"timestamp"`
	Duration  string    `json:"duration"`
	Data      any       `json:"data"`
	Error     string    `json:"error,omitempty"`
}

DebugResponse represents a standard debug endpoint response

type Describer added in v0.5.0

type Describer interface {
	DescribeRoutes() []server.RouteDescriptor
	DescribeModule() ModuleDescriptor
}

Describer is an optional interface that modules can implement to provide additional metadata for documentation generation and introspection.

func IsDescriber added in v0.5.0

func IsDescriber(m Module) (Describer, bool)

IsDescriber checks if a module implements the Describer interface

type FactoryResolver added in v0.9.0

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

FactoryResolver encapsulates the logic for resolving factory functions from Options, providing default implementations when not specified.

func NewFactoryResolver added in v0.9.0

func NewFactoryResolver(opts *Options) *FactoryResolver

NewFactoryResolver creates a new factory resolver with the given options.

func (*FactoryResolver) CacheConnector added in v0.18.0

func (f *FactoryResolver) CacheConnector(resourceSource TenantStore, log logger.Logger) cache.Connector

CacheConnector returns the appropriate cache connector function. If no custom connector is provided in options, returns a Redis connector that reads configuration from the resourceSource for the given tenant/key.

func (*FactoryResolver) DatabaseConnector added in v0.9.0

func (f *FactoryResolver) DatabaseConnector() database.Connector

DatabaseConnector returns the appropriate database connector function. If no custom connector is provided in options, returns the default implementation.

func (*FactoryResolver) HasCustomFactories added in v0.9.0

func (f *FactoryResolver) HasCustomFactories() bool

HasCustomFactories returns true if any custom factories are provided in options. This can be useful for logging or debugging purposes.

func (*FactoryResolver) MessagingClientFactory added in v0.9.0

func (f *FactoryResolver) MessagingClientFactory() messaging.ClientFactory

MessagingClientFactory returns the appropriate messaging client factory function. If no custom factory is provided in options, returns a factory that creates AMQPClient instances.

func (*FactoryResolver) ResourceSource added in v0.9.0

func (f *FactoryResolver) ResourceSource(cfg *config.Config) TenantStore

ResourceSource returns the appropriate tenant resource source. If no custom resource source is provided in options, creates one from config.

type GCInfo added in v0.11.0

type GCInfo struct {
	Stats       debug.GCStats `json:"stats"`
	MemBefore   uint64        `json:"mem_before"`
	MemAfter    uint64        `json:"mem_after"`
	Forced      bool          `json:"forced"`
	HeapObjects uint64        `json:"heap_objects"`
	HeapSize    uint64        `json:"heap_size"`
}

GCInfo contains garbage collection information

type GoroutineInfo added in v0.11.0

type GoroutineInfo struct {
	Count      int              `json:"count"`
	ByState    map[string]int   `json:"by_state"`
	ByFunction map[string]int   `json:"by_function"`
	Stacks     []GoroutineStack `json:"stacks,omitempty"`
	Leaks      []PotentialLeak  `json:"potential_leaks,omitempty"`
}

GoroutineInfo contains information about goroutines

type GoroutineStack added in v0.11.0

type GoroutineStack struct {
	ID       int      `json:"id"`
	State    string   `json:"state"`
	Function string   `json:"function"`
	Stack    []string `json:"stack"`
}

GoroutineStack represents a single goroutine's stack trace

type HealthDebugInfo added in v0.11.0

type HealthDebugInfo struct {
	Components map[string]ComponentHealth `json:"components"`
	Summary    HealthSummary              `json:"summary"`
	App        Info                       `json:"app"`
}

HealthDebugInfo contains enhanced health information for debugging

type HealthProbe added in v0.9.0

type HealthProbe interface {
	Run(ctx context.Context) HealthStatus
}

HealthProbe exposes a uniform interface for readiness probes.

type HealthStatus added in v0.9.0

type HealthStatus struct {
	Name     string
	Status   string
	Details  map[string]any
	Err      error
	Critical bool
}

HealthStatus captures the outcome of a readiness probe.

type HealthSummary added in v0.11.0

type HealthSummary struct {
	OverallStatus string `json:"overall_status"`
	TotalProbes   int    `json:"total_probes"`
	HealthyCount  int    `json:"healthy_count"`
	CriticalCount int    `json:"critical_count"`
	ErrorCount    int    `json:"error_count"`
}

HealthSummary provides overall health summary

type IPWhitelist added in v0.11.0

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

IPWhitelist manages a list of allowed IP networks for access control

func NewIPWhitelist added in v0.11.0

func NewIPWhitelist(ips []string, log logger.Logger) *IPWhitelist

NewIPWhitelist creates a new IP whitelist from a list of IP strings

func (*IPWhitelist) Contains added in v0.11.0

func (w *IPWhitelist) Contains(ip net.IP) bool

Contains checks if the given IP is allowed by this whitelist

type Info added in v0.11.0

type Info struct {
	Name        string    `json:"name"`
	Environment string    `json:"environment"`
	Version     string    `json:"version"`
	StartTime   time.Time `json:"start_time"`
	Uptime      string    `json:"uptime"`
	PID         int       `json:"pid"`
	Goroutines  int       `json:"goroutines"`
	MemoryUsage uint64    `json:"memory_usage"`
}

Info contains application information

type JobProvider added in v0.14.0

type JobProvider interface {
	RegisterJobs(JobRegistrar) error
}

JobProvider is an optional interface that modules can implement to register scheduled jobs. Modules implementing this interface will have RegisterJobs() called automatically after all module Init() methods have completed, making module registration order irrelevant.

Example:

type JobsModule struct{}

func (m *JobsModule) RegisterJobs(scheduler JobRegistrar) error {
    scheduler.FixedRate("cleanup", &CleanupJob{}, 30*time.Minute)
    scheduler.DailyAt("report", &ReportJob{}, scheduler.ParseTime("03:00"))
    return nil
}

The scheduler parameter is guaranteed to be non-nil when this method is called. If no SchedulerModule is registered, this method will not be called.

type JobRegistrar added in v0.14.0

type JobRegistrar interface {
	// FixedRate schedules a job to run every interval duration
	FixedRate(jobID string, job any, interval time.Duration) error

	// DailyAt schedules a job to run daily at the specified local time
	DailyAt(jobID string, job any, localTime time.Time) error

	// WeeklyAt schedules a job to run weekly on the specified day and time
	WeeklyAt(jobID string, job any, dayOfWeek time.Weekday, localTime time.Time) error

	// HourlyAt schedules a job to run hourly at the specified minute
	HourlyAt(jobID string, job any, minute int) error

	// MonthlyAt schedules a job to run monthly on the specified day and time
	MonthlyAt(jobID string, job any, dayOfMonth int, localTime time.Time) error
}

JobRegistrar defines the interface for scheduling jobs. This interface is defined here to avoid circular imports between app and scheduler packages. The scheduler package implements this interface via SchedulerModule.

type ManagerConfigBuilder added in v0.9.0

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

ManagerConfigBuilder creates configuration options for database and messaging managers based on deployment mode (single-tenant vs multi-tenant).

func NewManagerConfigBuilder added in v0.9.0

func NewManagerConfigBuilder(multiTenantEnabled bool, tenantLimit int) *ManagerConfigBuilder

NewManagerConfigBuilder creates a new manager configuration builder.

func (*ManagerConfigBuilder) BuildCacheOptions added in v0.18.0

func (b *ManagerConfigBuilder) BuildCacheOptions() cache.ManagerConfig

BuildCacheOptions creates cache manager options based on deployment mode. Multi-tenant mode uses tenant limits and shorter TTL for dynamic scaling. Single-tenant mode uses smaller fixed limits and longer TTL.

func (*ManagerConfigBuilder) BuildDatabaseOptions added in v0.9.0

func (b *ManagerConfigBuilder) BuildDatabaseOptions() database.DbManagerOptions

BuildDatabaseOptions creates database manager options based on deployment mode. Multi-tenant mode uses tenant limits and shorter TTL for dynamic scaling. Single-tenant mode uses smaller fixed limits and longer TTL for stability.

func (*ManagerConfigBuilder) BuildMessagingOptions added in v0.9.0

func (b *ManagerConfigBuilder) BuildMessagingOptions() messaging.ManagerOptions

BuildMessagingOptions creates messaging manager options based on deployment mode. Multi-tenant mode uses tenant limits and shorter TTL for dynamic scaling. Single-tenant mode uses smaller fixed limits and moderate TTL.

func (*ManagerConfigBuilder) IsMultiTenant added in v0.9.0

func (b *ManagerConfigBuilder) IsMultiTenant() bool

IsMultiTenant returns true if the builder is configured for multi-tenant mode.

func (*ManagerConfigBuilder) TenantLimit added in v0.9.0

func (b *ManagerConfigBuilder) TenantLimit() int

TenantLimit returns the configured tenant limit for multi-tenant mode.

type MessagingInitializer added in v0.9.0

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

MessagingInitializer handles messaging system initialization including declaration collection and consumer setup for different deployment modes.

func NewMessagingInitializer added in v0.9.0

func NewMessagingInitializer(
	log logger.Logger,
	manager *messaging.Manager,
	multiTenant bool,
) *MessagingInitializer

NewMessagingInitializer creates a new messaging initializer.

func (*MessagingInitializer) CollectDeclarations added in v0.9.0

func (m *MessagingInitializer) CollectDeclarations(registry *ModuleRegistry) (*messaging.Declarations, error)

CollectDeclarations collects messaging declarations from all registered modules. This builds the unified declaration store used for all tenant registries.

func (*MessagingInitializer) IsAvailable added in v0.9.0

func (m *MessagingInitializer) IsAvailable() bool

IsAvailable returns true if the messaging manager is available.

func (*MessagingInitializer) LogDeploymentMode added in v0.9.0

func (m *MessagingInitializer) LogDeploymentMode()

LogDeploymentMode logs the current deployment mode for messaging.

func (*MessagingInitializer) PrepareRuntimeConsumers added in v0.9.0

func (m *MessagingInitializer) PrepareRuntimeConsumers(
	ctx context.Context,
	declarations *messaging.Declarations,
) error

PrepareRuntimeConsumers prepares consumers based on deployment mode. For single-tenant: starts consumers immediately. For multi-tenant: logs that consumers will start on-demand.

func (*MessagingInitializer) SetupLazyConsumerInit added in v0.9.0

func (m *MessagingInitializer) SetupLazyConsumerInit(
	provider ResourceProvider,
	declarations *messaging.Declarations,
) error

SetupLazyConsumerInit modifies the resource provider's GetMessaging function to include lazy consumer initialization. This ensures consumers are started on-demand when messaging is first accessed.

type MetadataRegistry added in v0.5.0

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

MetadataRegistry tracks discovered modules for introspection

func (*MetadataRegistry) Clear added in v0.5.0

func (r *MetadataRegistry) Clear()

Clear removes all registered modules (useful for testing)

func (*MetadataRegistry) Count added in v0.5.0

func (r *MetadataRegistry) Count() int

Count returns the number of registered modules

func (*MetadataRegistry) Module added in v0.19.0

func (r *MetadataRegistry) Module(name string) (ModuleInfo, bool)

Module returns information for a specific module

func (*MetadataRegistry) Modules added in v0.19.0

func (r *MetadataRegistry) Modules() map[string]ModuleInfo

Modules returns a copy of all registered module information

func (*MetadataRegistry) RegisterModule added in v0.5.0

func (r *MetadataRegistry) RegisterModule(name string, module Module, pkg string)

RegisterModule adds a module to the metadata registry

type Module

type Module interface {
	Name() string
	Init(deps *ModuleDeps) error
	RegisterRoutes(hr *server.HandlerRegistry, r server.RouteRegistrar)
	DeclareMessaging(decls *messaging.Declarations)
	Shutdown() error
}

Module defines the interface that all application modules must implement. It provides hooks for initialization, route registration, messaging setup, and cleanup.

type ModuleDeps

type ModuleDeps struct {
	Logger logger.Logger
	Config *config.Config

	// Tracer provides distributed tracing capabilities.
	// Creates spans for tracking operations across services.
	// This is a no-op tracer if observability is disabled.
	Tracer trace.Tracer

	// MeterProvider provides metrics collection capabilities.
	// Use this to create custom meters for application-specific metrics.
	// This is a no-op provider if observability is disabled.
	MeterProvider metric.MeterProvider

	// Scheduler provides job scheduling capabilities.
	// Modules can register jobs using methods like FixedRate, DailyAt, WeeklyAt, etc.
	// This field is nil if no SchedulerModule is registered.
	// Example: deps.Scheduler.DailyAt("cleanup-job", &CleanupJob{}, time.Date(0, 0, 0, 3, 0, 0, 0, time.Local))
	Scheduler JobRegistrar

	// DB returns a database interface for the current context.
	// In single-tenant mode, returns the global database instance.
	// In multi-tenant mode, resolves tenant from context and returns tenant-specific database.
	DB func(_ context.Context) (database.Interface, error)

	// DBByName returns a named database interface for explicit database selection.
	// Use this when working with multiple databases in single-tenant mode.
	// The name must match a key in the 'databases:' config section.
	// Example: db, err := deps.DBByName(ctx, "legacy") for databases.legacy config.
	// Named databases are shared across all tenants in multi-tenant mode.
	DBByName func(ctx context.Context, name string) (database.Interface, error)

	// Messaging returns a messaging client for the current context.
	// In single-tenant mode, returns the global messaging client.
	// In multi-tenant mode, resolves tenant from context and returns tenant-specific client.
	Messaging func(_ context.Context) (messaging.AMQPClient, error)

	// Cache returns a cache instance for the current context.
	// In single-tenant mode, returns the global cache instance.
	// In multi-tenant mode, resolves tenant from context and returns tenant-specific cache.
	Cache func(_ context.Context) (cache.Cache, error)
}

ModuleDeps contains the dependencies that are injected into each module. It provides access to core services like database, logging, messaging, observability, and job scheduling. All modules must use DB() and Messaging() functions for resource access.

type ModuleDescriptor added in v0.5.0

type ModuleDescriptor struct {
	Name        string   // Module name
	Version     string   // Module version
	Description string   // Module description
	Tags        []string // Module tags for grouping
	BasePath    string   // Base path for all module routes
}

ModuleDescriptor captures module-level metadata

type ModuleInfo added in v0.5.0

type ModuleInfo struct {
	Module     Module           // The actual module instance
	Descriptor ModuleDescriptor // Module metadata
	Package    string           // Go package path
}

ModuleInfo contains both the module instance and its metadata

type ModuleRegistry

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

ModuleRegistry manages the registration and lifecycle of application modules. It handles module initialization, route registration, messaging setup, and shutdown.

func NewModuleRegistry

func NewModuleRegistry(deps *ModuleDeps) *ModuleRegistry

NewModuleRegistry creates a new module registry with the given dependencies. It initializes an empty registry ready to accept module registrations.

func (*ModuleRegistry) DeclareMessaging added in v0.9.0

func (r *ModuleRegistry) DeclareMessaging(decls *messaging.Declarations) error

DeclareMessaging calls DeclareMessaging on all registered modules to populate a shared declarations store. This method builds the declaration store that will be used for all tenant registries.

func (*ModuleRegistry) Register

func (r *ModuleRegistry) Register(module Module) error

Register adds a module to the registry and initializes it. It calls the module's Init method with the injected dependencies. Returns an error if a module with the same name is already registered. Special handling: If the module implements app.JobRegistrar, it is automatically wired into ModuleDeps.Scheduler for other modules to use.

IMPORTANT: Duplicate module errors are unrecoverable and must be handled with log.Fatal().

func (*ModuleRegistry) RegisterJobs added in v0.14.0

func (r *ModuleRegistry) RegisterJobs() error

RegisterJobs calls RegisterJobs on modules that implement JobProvider interface. This method is called after all modules have been initialized, making module registration order irrelevant for job scheduling. If no scheduler is registered, this method skips silently.

func (*ModuleRegistry) RegisterRoutes

func (r *ModuleRegistry) RegisterRoutes(registrar server.RouteRegistrar)

RegisterRoutes calls RegisterRoutes on all registered modules. It should be called after all modules have been registered.

func (*ModuleRegistry) Shutdown

func (r *ModuleRegistry) Shutdown() error

Shutdown gracefully shuts down all registered modules. It calls each module's Shutdown method and logs any errors. Messaging shutdown is handled by the messaging manager.

type MultiTenantResourceProvider added in v0.9.0

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

MultiTenantResourceProvider provides database, messaging, and cache resources for multi-tenant deployments using tenant ID from context.

func NewMultiTenantResourceProvider added in v0.9.0

func NewMultiTenantResourceProvider(
	dbManager *database.DbManager,
	messagingManager *messaging.Manager,
	cacheManager *cache.CacheManager,
	declarations *messaging.Declarations,
) *MultiTenantResourceProvider

NewMultiTenantResourceProvider creates a resource provider for multi-tenant mode.

func (*MultiTenantResourceProvider) Cache added in v0.19.0

Cache returns the cache instance for the tenant specified in context.

func (*MultiTenantResourceProvider) DB added in v0.19.0

DB returns the database interface for the tenant specified in context.

func (*MultiTenantResourceProvider) DBByName added in v0.22.0

DBByName returns a named database interface for multi-tenant mode. Named databases are shared across all tenants (tenant-agnostic configuration). Use this for explicit database selection when working with multiple databases. The name must match a key in the 'databases:' config section.

func (*MultiTenantResourceProvider) Messaging added in v0.19.0

Messaging returns the messaging client for the tenant specified in context. It ensures tenant-specific consumers are initialized before returning the publisher.

func (*MultiTenantResourceProvider) SetDeclarations added in v0.9.0

func (p *MultiTenantResourceProvider) SetDeclarations(declarations *messaging.Declarations)

SetDeclarations updates the declaration store used for ensuring consumers.

type OSSignalHandler added in v0.4.0

type OSSignalHandler struct{}

OSSignalHandler implements SignalHandler using the real OS signal package

func (*OSSignalHandler) Notify added in v0.4.0

func (osh *OSSignalHandler) Notify(c chan<- os.Signal, sig ...os.Signal)

func (*OSSignalHandler) WaitForSignal added in v0.4.0

func (osh *OSSignalHandler) WaitForSignal(c <-chan os.Signal)

type Options added in v0.4.0

type Options struct {
	Database               database.Interface
	MessagingClient        messaging.Client
	SignalHandler          SignalHandler
	TimeoutProvider        TimeoutProvider
	Server                 ServerRunner
	ConfigLoader           func() (*config.Config, error)
	DatabaseConnector      func(*config.DatabaseConfig, logger.Logger) (database.Interface, error)
	MessagingClientFactory func(string, logger.Logger) messaging.AMQPClient
	CacheConnector         cache.Connector
	ResourceSource         TenantStore
}

Options contains optional dependencies for creating an App instance

type PotentialLeak added in v0.11.0

type PotentialLeak struct {
	ID       int    `json:"id"`
	Function string `json:"function"`
	Duration string `json:"duration"`
	Reason   string `json:"reason"`
}

PotentialLeak represents a goroutine that might be leaked

type ResourceManagerFactory added in v0.9.0

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

ResourceManagerFactory creates database and messaging managers using resolved factories and configuration options.

func NewResourceManagerFactory added in v0.9.0

func NewResourceManagerFactory(
	factoryResolver *FactoryResolver,
	configBuilder *ManagerConfigBuilder,
	log logger.Logger,
) *ResourceManagerFactory

NewResourceManagerFactory creates a new resource manager factory.

func (*ResourceManagerFactory) CreateCacheManager added in v0.18.0

func (f *ResourceManagerFactory) CreateCacheManager(
	resourceSource TenantStore,
) *cache.CacheManager

CreateCacheManager creates a cache manager using the resolved factory and appropriate configuration options for the deployment mode.

func (*ResourceManagerFactory) CreateDatabaseManager added in v0.9.0

func (f *ResourceManagerFactory) CreateDatabaseManager(
	resourceSource TenantStore,
) *database.DbManager

CreateDatabaseManager creates a database manager using the resolved factory and appropriate configuration options for the deployment mode.

func (*ResourceManagerFactory) CreateMessagingManager added in v0.9.0

func (f *ResourceManagerFactory) CreateMessagingManager(
	resourceSource TenantStore,
) *messaging.Manager

CreateMessagingManager creates a messaging manager using the resolved factory and appropriate configuration options for the deployment mode.

func (*ResourceManagerFactory) LogFactoryInfo added in v0.9.0

func (f *ResourceManagerFactory) LogFactoryInfo()

LogFactoryInfo logs information about which factories are being used. This is useful for debugging and operational visibility.

type ResourceProvider added in v0.9.0

type ResourceProvider interface {
	DB(ctx context.Context) (database.Interface, error)
	DBByName(ctx context.Context, name string) (database.Interface, error)
	Messaging(ctx context.Context) (messaging.AMQPClient, error)
	Cache(ctx context.Context) (cache.Cache, error)
}

ResourceProvider abstracts database, messaging, and cache access with support for both single-tenant and multi-tenant deployment modes.

type ServerRunner added in v0.5.0

type ServerRunner interface {
	Start() error
	Shutdown(ctx context.Context) error
	Echo() *echo.Echo
	ModuleGroup() server.RouteRegistrar
	RegisterReadyHandler(handler echo.HandlerFunc)
}

ServerRunner abstracts the HTTP server to allow injecting test-friendly implementations

type SignalHandler added in v0.4.0

type SignalHandler interface {
	Notify(c chan<- os.Signal, sig ...os.Signal)
	WaitForSignal(c <-chan os.Signal)
}

SignalHandler interface allows for injectable signal handling for testing

type SingleTenantResourceProvider added in v0.9.0

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

SingleTenantResourceProvider provides database, messaging, and cache resources for single-tenant deployments using a fixed empty key.

func NewSingleTenantResourceProvider added in v0.9.0

func NewSingleTenantResourceProvider(
	dbManager *database.DbManager,
	messagingManager *messaging.Manager,
	cacheManager *cache.CacheManager,
	declarations *messaging.Declarations,
) *SingleTenantResourceProvider

NewSingleTenantResourceProvider creates a resource provider for single-tenant mode.

func (*SingleTenantResourceProvider) Cache added in v0.19.0

Cache returns the cache instance for single-tenant mode.

func (*SingleTenantResourceProvider) DB added in v0.19.0

DB returns the database interface for single-tenant mode.

func (*SingleTenantResourceProvider) DBByName added in v0.22.0

DBByName returns a named database interface for single-tenant mode. Use this for explicit database selection when working with multiple databases. The name must match a key in the 'databases:' config section.

func (*SingleTenantResourceProvider) Messaging added in v0.19.0

Messaging returns the messaging client for single-tenant mode. It ensures consumers are initialized before returning the publisher.

func (*SingleTenantResourceProvider) SetDeclarations added in v0.9.0

func (p *SingleTenantResourceProvider) SetDeclarations(declarations *messaging.Declarations)

SetDeclarations updates the declaration store used for ensuring consumers.

type StandardTimeoutProvider added in v0.4.0

type StandardTimeoutProvider struct{}

StandardTimeoutProvider implements TimeoutProvider using context.WithTimeout

func (*StandardTimeoutProvider) WithTimeout added in v0.4.0

func (stp *StandardTimeoutProvider) WithTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

type TenantStore added in v0.9.0

type TenantStore interface {
	database.TenantStore
	messaging.TenantMessagingResourceSource
	cache.TenantCacheResourceSource

	// IsDynamic returns true if this store loads tenant configurations dynamically
	// from external sources (e.g., AWS Secrets Manager, Vault). Returns false for
	// stores that use static YAML configuration. This controls pre-initialization behavior.
	IsDynamic() bool
}

TenantStore combines the interfaces required by the database, messaging, and cache managers.

type TimeoutProvider added in v0.4.0

type TimeoutProvider interface {
	WithTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc)
}

TimeoutProvider interface allows for injectable timeout creation for testing

Jump to

Keyboard shortcuts

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