bootstrap

package
v1.67.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 29 Imported by: 2

README

Package bootstrap

Пакет bootstrap предназначен для инициализации инфраструктуры приложения и настройки основных компонентов.

Types

Bootstrap

Центральная структура, которая предоставляет функциональность для инициализации и настройки модуля приложения, включая динамическую конфигурацию, логирование, трейсинг, запуск инфраструктурного http-сервера (метрики, healthchecks), подключение к кластеру сервисов и интеграцию с sentry для обработки ошибок. Другими словами, объект структуры Bootstrap управляет жизненным циклом приложения.

Методы:

(b *BaseBootstrap) Fatal(err error)

Обработать критические ошибки с уведомлением в Sentry

New(moduleVersion string, remoteConfig any, endpoints []cluster.EndpointDescriptor, transport string) *Bootstrap

Конструктор с параметрами:

  • moduleVersion - версия модуля
  • remoteConfig - структура для динамической конфигурации
  • endpoints - список эндпоинтов модуля, для транспорта http у каждого endpoint'а должен быть указан HttpMethod
  • transport - тип сервера, grpc, http или empty
NewStandalone(moduleVersion string) *StandaloneBootstrap

Конструктор с параметрами:

  • moduleVersion - версия модуля
func (b *StandaloneBootstrap) ReadConfig(destPtr any) error

Прочитать локальную json конфигурацию, путь до конфигурации определяется настройкой в локальном конфиге remoteConfigPath, по умолчанию путь ./conf/config.json (либо относительно бинарника, если запуск не в dev режиме)

Конфигурация

Файлы конфигурации по умолчанию:

  • conf/config_dev.yml для разработки
  • config.yml рядом с бинарником для production

Переменные окружения:

  • APP_MODE=dev — режим разработки
  • APP_CONFIG_PATH — кастомный путь к конфигу
  • APP_CONFIG_ENV_PREFIX — префикс для env variables
  • CLUSTER_MODE=offline — режим, при котором будет использоваться заглушка для конфиг сервиса

Инфраструктурные эндпоинты

По умолчанию доступны:

  • /internal/metrics — prometheus метрики
  • /internal/metrics/descriptions — описание метрик
  • /internal/health — healthcheck статус
  • /internal/debug/pprof/ — профилирование

Usage

Default usage flow for clustered
package main

import (
	"log"

	"github.com/txix-open/isp-kit/bootstrap"
	"github.com/txix-open/isp-kit/cluster"
	"github.com/txix-open/isp-kit/shutdown"
)

type remoteConfig struct {
	Foo string `validate:"required"`
	Bar int
}

func noopHandler() {}

func main() {
	endpoints := []cluster.EndpointDescriptor{{
		Path:    "/api/service/private",
		Inner:   true,
		Handler: noopHandler,
	}, {
		Path:    "/api/service/public",
		Inner:   false,
		Handler: noopHandler,
	}}
	boot := bootstrap.New("1.0.0", remoteConfig{}, endpoints, cluster.GrpcTransport)

	shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
		log.Println("shutting down...")
		boot.App.Shutdown()
		log.Println("shutdown completed")
	})

	err := boot.App.Run()
	if err != nil {
		boot.Fatal(err)
	}
}

Default usage flow for standalone
package main

import (
	"log"

	"github.com/txix-open/isp-kit/bootstrap"
	"github.com/txix-open/isp-kit/cluster"
	"github.com/txix-open/isp-kit/shutdown"
)

type config struct {
	Foo string `validate:"required"`
	Bar int
}

func main() {
	boot := bootstrap.NewStandalone("1.0.0")

	shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
		log.Println("shutting down...")
		boot.App.Shutdown()
		log.Println("shutdown completed")
	})

	cfg := config{}
	err := boot.ReadConfig(&cfg)
	if err != nil {
		boot.Fatal(err)
	}

	err = boot.App.Run()
	if err != nil {
		boot.Fatal(err)
	}
}

Documentation

Overview

Package bootstrap provides a unified initialization framework for isp-kit applications.

The bootstrap package handles application setup including configuration management, logging, observability (Sentry and tracing), cluster coordination, and infrastructure server initialization. It supports both clustered and standalone deployment modes.

Usage

For clustered applications:

boot := bootstrap.New(
    "1.0.0",                                    // module version
    &RemoteConfig{},                            // remote config struct
    []cluster.EndpointDescriptor{},             // service endpoints
    cluster.HttpTransport,                      // transport type
)

For standalone applications:

boot := bootstrap.NewStandalone("1.0.0")
var cfg MyConfig
if err := boot.ReadConfig(&cfg); err != nil {
    // handle error
}

The package automatically initializes:

  • Application context and lifecycle management
  • Logging with optional file output and sampling
  • Sentry error reporting and tracing
  • Health check endpoints
  • Metrics endpoints
  • Cluster client (for clustered mode)
  • Remote configuration management (for clustered mode)

Environment Variables

The following environment variables are supported:

  • APP_MODE: Set to "dev" to enable development mode (affects logging level and file paths)
  • CLUSTER_MODE: Set to "offline" to enable offline cluster mode
  • APP_CONFIG_PATH: Custom path to the application configuration file
  • APP_CONFIG_ENV_PREFIX: Prefix for environment variable configuration keys

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseBootstrap added in v1.62.0

type BaseBootstrap struct {
	App                 *app.Application
	MetricsRegistry     *metrics.Registry
	InfraServer         *infra.Server
	HealthcheckRegistry *healthcheck.Registry
	BindingAddress      string
	MigrationsDir       string
	ModuleName          string
	SentryHub           sentry.Hub
	TracingProvider     tracing.Provider
}

BaseBootstrap provides the core initialization context for all application types. It contains shared functionality for application lifecycle, metrics, infrastructure, observability, and health checking.

Fields:

  • App: Application instance for lifecycle management and context
  • MetricsRegistry: Registry for application metrics
  • InfraServer: Infrastructure server for internal endpoints (metrics, health, pprof)
  • HealthcheckRegistry: Registry for health check endpoints
  • BindingAddress: inner binding address (host:port)
  • MigrationsDir: Path to database migrations directory
  • ModuleName: Name of the module
  • SentryHub: Sentry error reporting hub
  • TracingProvider: OpenTelemetry tracing provider

Create a BaseBootstrap through New() or NewStandalone() functions.

func (*BaseBootstrap) Fatal added in v1.62.0

func (b *BaseBootstrap) Fatal(err error)

Fatal logs a fatal error, reports it to Sentry, and terminates the application.

This method performs the following steps:

  1. Reports the error to Sentry with fatal level
  2. Closes the application and all registered closers
  3. Waits for post-shutdown operations (500ms)
  4. Logs the fatal error and terminates the process

This method does not return and should only be used for unrecoverable errors.

type Bootstrap

type Bootstrap struct {
	*BaseBootstrap

	ClusterCli   ClusterClient
	RemoteConfig *rc.Config
}

Bootstrap represents the main initialization context for clustered applications. It embeds BaseBootstrap and adds cluster-specific functionality including cluster client management and remote configuration.

The Bootstrap instance provides access to:

  • Application lifecycle management (via BaseBootstrap)
  • Cluster coordination through ClusterCli
  • Remote configuration via RemoteConfig

Create a Bootstrap instance using the New() function.

func New

func New(
	moduleVersion string,
	remoteConfig any,
	endpoints []cluster.EndpointDescriptor,
	transport string,
) *Bootstrap

New creates and initializes a new Bootstrap instance for clustered applications.

Parameters:

  • moduleVersion: Version string of the module (e.g., "1.0.0")
  • remoteConfig: Pointer to a struct defining the remote configuration schema
  • endpoints: List of service endpoint descriptors for cluster discovery
  • transport: Transport type (e.g., cluster.HttpTransport or cluster.GrpcTransport)

Returns a fully initialized Bootstrap instance with:

  • Application context and logging
  • Sentry error reporting
  • Cluster client for coordination
  • Remote configuration management
  • Infrastructure server with metrics and health endpoints

The function automatically detects the deployment mode (dev/offline) and configures the application accordingly. In case of initialization errors, the function logs a fatal error and terminates the application.

Example:

boot := bootstrap.New(
    "1.2.3",
    &MyRemoteConfig{},
    []cluster.EndpointDescriptor{
        {Path: "/api/v1", HttpMethod: "GET"},
    },
    cluster.HttpTransport,
)

type ClusterClient added in v1.62.0

type ClusterClient interface {
	Run(ctx context.Context, eventHandler *cluster.EventHandler) error
	Close() error
}

ClusterClient defines the interface for cluster coordination operations.

type ClusteredLocalConfig added in v1.62.0

type ClusteredLocalConfig struct {
	LocalConfig

	ConfigServiceAddress        ConfigServiceAddr
	DefaultRemoteConfigPath     string
	RemoteConfigReceiverTimeout time.Duration
	MetricsAutodiscovery        MetricsAutodiscovery
}

ClusteredLocalConfig extends LocalConfig with additional configuration for clustered applications.

Embedded:

  • LocalConfig: All fields from LocalConfig

Additional fields:

  • ConfigServiceAddress: Address of the config service for cluster coordination (IP;Port format, required)
  • DefaultRemoteConfigPath: Custom path for default remote configuration file (optional)
  • RemoteConfigReceiverTimeout: Timeout for receiving remote configuration updates
  • MetricsAutodiscovery: Configuration for Prometheus metrics auto-discovery

type ConfigServiceAddr

type ConfigServiceAddr struct {
	IP   string `validate:"required"`
	Port string `validate:"required"`
}

ConfigServiceAddr defines the address configuration for the cluster config service.

Fields:

  • IP: Comma-separated list of config service host IPs
  • Port: Comma-separated list of config service ports (must match length of IP)

Multiple addresses can be specified using semicolon separation (e.g., "host1;host2" and "port1;port2")

type GrpcInnerAddr

type GrpcInnerAddr struct {
	IP   string `validate:"required"`
	Port int    `validate:"required"`
}

GrpcInnerAddr defines the internal gRPC address configuration.

Fields:

  • IP: Internal IP address (required)
  • Port: Internal gRPC port (required)

type GrpcOuterAddr

type GrpcOuterAddr struct {
	IP   string
	Port int `validate:"required"`
}

GrpcOuterAddr defines the external gRPC address configuration.

Fields:

  • IP: External IP address (can be empty for standalone)
  • Port: External gRPC port (required)

type LocalConfig

type LocalConfig struct {
	GrpcOuterAddress          GrpcOuterAddr
	GrpcInnerAddress          GrpcInnerAddr
	ModuleName                string `validate:"required"`
	MigrationsDirPath         string
	RemoteConfigOverride      string
	LogFile                   LogFile
	Logs                      Logs
	Observability             Observability
	InfraServerPort           int
	HealthcheckHandlerTimeout time.Duration
	// Path to the application configuration
	RemoteConfigPath string
}

LocalConfig defines the local configuration structure for standalone applications.

Fields:

  • GrpcOuterAddress: External address configuration (IP and port)
  • GrpcInnerAddress: Internal address configuration (IP and port, required)
  • ModuleName: Unique name of the module/application (required)
  • MigrationsDirPath: Path to database migrations directory (optional)
  • RemoteConfigOverride: Override content for remote configuration (optional)
  • LogFile: File-based logging configuration
  • Logs: Log sampling and rate limiting configuration
  • Observability: Sentry and tracing configuration
  • InfraServerPort: Custom port for infrastructure server (optional, defaults to GrpcInnerAddress.Port + 1)
  • HealthcheckHandlerTimeout: Timeout for health check requests
  • RemoteConfigPath: Path to application configuration file (optional)

type LogFile

type LogFile struct {
	Path       string
	MaxSizeMb  int
	MaxBackups int
	Compress   bool
}

LogFile configures file-based logging output.

Fields:

  • Path: Path to the log file
  • MaxSizeMb: Maximum file size in megabytes before rotation (default: 512)
  • MaxBackups: Maximum number of backup files to keep (default: 4)
  • Compress: Whether to compress rotated log files (default: true)

type Logs

type Logs struct {
	Sampling struct {
		Enable       bool
		MaxPerSecond int
		PassEvery    int
	}
}

Logs configures log sampling and rate limiting.

Fields:

  • Sampling.Enable: Enable log sampling to prevent log flooding
  • Sampling.MaxPerSecond: Maximum log entries per second when sampling is enabled
  • Sampling.PassEvery: Number of log entries to pass before sampling again

type MetricsAutodiscovery added in v1.52.0

type MetricsAutodiscovery struct {
	Enable           bool
	Address          string
	AdditionalLabels map[string]string
}

MetricsAutodiscovery configures Prometheus metrics auto-discovery.

Fields:

  • Enable: Enable metrics auto-discovery
  • Address: Metrics endpoint address (optional, defaults to infra server address)
  • AdditionalLabels: Additional labels to attach to metrics

type Observability

type Observability struct {
	Sentry  Sentry
	Tracing Tracing
}

Observability configures observability features including Sentry and tracing.

Fields:

  • Sentry: Error reporting configuration
  • Tracing: Distributed tracing configuration

type Sentry

type Sentry struct {
	Enable      bool
	Dsn         string
	Environment string
	Tags        map[string]string
}

Sentry configures Sentry error reporting.

Fields:

  • Enable: Enable Sentry error reporting
  • Dsn: Sentry DSN (Data Source Name)
  • Environment: Environment name (e.g., "production", "development")
  • Tags: Additional tags for Sentry events

type StandaloneBootstrap added in v1.62.0

type StandaloneBootstrap struct {
	*BaseBootstrap
	// contains filtered or unexported fields
}

StandaloneBootstrap represents the initialization context for standalone applications. It embeds BaseBootstrap and provides functionality for reading application configuration from a local file.

Use this type for applications that do not require cluster coordination or remote configuration. Ideal for single-instance services, batch jobs, or development environments.

Create a StandaloneBootstrap using the NewStandalone() function.

func NewStandalone added in v1.62.0

func NewStandalone(moduleVersion string) *StandaloneBootstrap

NewStandalone creates and initializes a new StandaloneBootstrap instance.

Parameters:

  • moduleVersion: Version string of the module (e.g., "1.0.0")

Returns a fully initialized StandaloneBootstrap with:

  • Application context and logging
  • Sentry error reporting
  • Infrastructure server with metrics and health endpoints
  • Tracing provider (if configured)

Unlike New(), this function does not initialize cluster client or remote configuration. It is suitable for standalone applications that read their configuration from local files.

Example:

boot := bootstrap.NewStandalone("1.2.3")
var cfg MyConfig
if err := boot.ReadConfig(&cfg); err != nil {
    // handle configuration error
}

func (*StandaloneBootstrap) ReadConfig added in v1.62.0

func (b *StandaloneBootstrap) ReadConfig(destPtr any) error

ReadConfig reads and validates the application configuration from a JSON file.

Parameters:

  • destPtr: Pointer to a struct where the configuration will be unmarshaled

Returns an error if:

  • The configuration file cannot be read
  • The JSON cannot be unmarshaled into the destination struct
  • The configuration fails validation

The configuration file path is determined by the RemoteConfigPath field in the local configuration, or defaults to "./conf/config.json" in dev mode or "./conf/config.json" relative to the binary in production.

Example:

var cfg MyConfig
if err := boot.ReadConfig(&cfg); err != nil {
    log.Fatalf("failed to read config: %v", err)
}

type Tracing

type Tracing struct {
	Enable      bool
	Address     string
	Environment string
	Attributes  map[string]string
}

Tracing configures distributed tracing (OpenTelemetry).

Fields:

  • Enable: Enable distributed tracing
  • Address: Tracing collector endpoint address
  • Environment: Environment name for trace attribution
  • Attributes: Additional attributes for trace spans

Jump to

Keyboard shortcuts

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