bootstrap

package
v1.64.4 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 29 Imported by: 0

README

Package bootstrap

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

Types

Bootstrap

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

Методы:

(b *BaseBootstrap) Fatal(err error)

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

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

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

  • moduleVersion - версия модуля
  • remoteConfig - структура для динамической конфигурации
  • endpoints - список эндпоинтов модуля
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)

	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

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
}

func (*BaseBootstrap) Fatal added in v1.62.0

func (b *BaseBootstrap) Fatal(err error)

type Bootstrap

type Bootstrap struct {
	*BaseBootstrap

	ClusterCli   ClusterClient
	RemoteConfig *rc.Config
}

func New

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

type ClusterClient added in v1.62.0

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

type ClusteredLocalConfig added in v1.62.0

type ClusteredLocalConfig struct {
	LocalConfig

	ConfigServiceAddress        ConfigServiceAddr
	DefaultRemoteConfigPath     string
	RemoteConfigReceiverTimeout time.Duration
	MetricsAutodiscovery        MetricsAutodiscovery
}

type ConfigServiceAddr

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

type GrpcInnerAddr

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

type GrpcOuterAddr

type GrpcOuterAddr struct {
	IP   string
	Port int `validate:"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
}

type LogFile

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

type Logs

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

type MetricsAutodiscovery added in v1.52.0

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

type Observability

type Observability struct {
	Sentry  Sentry
	Tracing Tracing
}

type Sentry

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

type StandaloneBootstrap added in v1.62.0

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

func NewStandalone added in v1.62.0

func NewStandalone(moduleVersion string) *StandaloneBootstrap

func (*StandaloneBootstrap) ReadConfig added in v1.62.0

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

type Tracing

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

Jump to

Keyboard shortcuts

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