runtime

package module
v0.2.19 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 30 Imported by: 3

README

Runtime Package

Introduction

The @/runtime package serves as the foundational implementation for building distributed-ready services within our system, leveraging the Kratos microservice framework. It provides a set of core abstractions and utilities that simplify the development and management of Kratos-based services, enabling developers to write business logic independent of the underlying deployment model.

This design ensures that services developed using this package are inherently loosely coupled and independently deployable. Whether initially deployed as part of a monolithic application or as standalone microservices, the transition between these deployment modes can be achieved seamlessly by simply changing the underlying infrastructure implementations, without requiring modifications to the core business code.

The Runtime component centralizes the management of essential resources required for service operation, including configuration, logging, monitoring, caching, and data storage, all integrated within the Kratos ecosystem.

Core Philosophy / Design Principles

  1. Kratos-Native Development: The @/runtime package is built upon the Kratos framework, providing a streamlined and opinionated way to develop Kratos-based microservices. It aims to reduce boilerplate and enforce best practices within the Kratos ecosystem.
  2. Deployment Agnosticism: Business logic should be decoupled from deployment concerns. By leveraging Kratos's robust capabilities, the @/runtime package provides abstractions that allow services to run equally well in a single process (monolithic deployment) or across multiple nodes (distributed deployment).
  3. Loose Coupling by Design: Through standardized interfaces and explicit communication mechanisms (e.g., API contracts, gRPC), the package, in conjunction with Kratos's service discovery and communication patterns, encourages and facilitates the development of services that are inherently loosely coupled, making them easier to test, maintain, and evolve independently.
  4. Infrastructure Simplification & Swappability: It abstracts away the complexities of underlying infrastructure components (e.g., configuration sources, logging backends, service discovery mechanisms). This allows for easy swapping of different infrastructure implementations (e.g., from local file-based config to a distributed config center) as the system scales, without impacting the service's core logic, all while integrating seamlessly with Kratos's extension points.
  5. Standardization & Consistency: The package provides a consistent set of patterns and tools for common cross-cutting concerns, ensuring a standardized development and operational experience across all services built on this architecture, adhering to Kratos's architectural principles.

Naming Conventions

To ensure clarity and consistency within the @/runtime package, especially given its close integration with the Kratos framework, we adhere to the following naming conventions:

  1. Kratos-Specific Elements: Any type, interface, or struct that is directly from the Kratos framework, or is a direct wrapper/alias/bridge implementation of a Kratos element within @/runtime, must be prefixed with K.

    • Purpose: This clearly indicates that the element is Kratos-native or directly interacts with Kratos.
    • Examples: KRegistrar, KDiscovery, KApp, KServer.
  2. @/runtime Abstractions: Any type, interface, or struct defined within @/runtime that represents a general-purpose abstraction or utility, even if its underlying implementation uses Kratos, should NOT be prefixed with K.

    • Purpose: These are the public-facing APIs of the @/runtime package, designed to be used by business logic without direct Kratos dependency at the interface level.
    • Examples: Sender (for mail), StorageProvider, ConfigLoader.

This distinction helps developers quickly understand the nature and scope of each component, promoting better code readability and maintainability.

Before You Start

Before you start using the Runtime package, ensure that you have the following prerequisites: In order to prevent import conflicts caused by packages with the same name as kratos, packages with the same name in this database will import the export content from kratos. All type definitions will be prefixed with the K fixed prefix. Note: Only type declarations are prefixed, not functions.

Available Packages
  • bootstrap: The bootstrap package contains Configuration file reading and writing, initialization variable declaration, etc
  • cmd: Contains command-line utilities or example main packages for the runtime.
  • config: The files in this directory define the basic configuration of the service runtime, as well as the loading of the run configuration.
  • context: The context directory defines the context interface and the context implementation.
  • gen: This directory contains generated code (e.g., Go structs, gRPC service stubs) derived from the Protocol Buffer (.proto) definition files.
  • internal: Contains internal packages and helper utilities not intended for external consumption.
  • log: Provides logging interfaces and implementations for the runtime, integrated with Kratos's logging system.
  • mail: The mail directory defines the email interface and the email implementation.
  • middleware: The middleware directory defines the middleware interface and the middleware implementation for common cross-cutting concerns like authentication, logging, and rate limiting.
  • proto: This directory contains the original Protocol Buffer (.proto) definition files that define the service interfaces and data structures. These files are used to generate code for various languages, ensuring compatibility and strong typing across different services.
  • registry: This directory defines an alias for 'kratos/v2/registry', primarily for backward compatibility and for placing import error paths.
  • service: The service directory contains the definition of the service interface, which is used to define the interface of the service and the implementation of the service.
  • storage: This directory provides abstractions and implementations for various data storage mechanisms, including caching, databases, and file storage. It centralizes data access concerns, allowing services to easily swap underlying storage technologies.
  • third_party: Contains vendored or third-party code dependencies.
Top-Level Files
  • runtime.go: The main entry point and core logic for the runtime package, orchestrating the initialization and lifecycle of services.
  • generate.go: Defines go generate commands used for automated code generation tasks, such as generating protobuf code.
  • buf.lock: A lock file generated by Buf, ensuring reproducible builds of Protocol Buffers.
  • buf.yaml: The main configuration file for Buf, defining linting rules, formatting, and other settings for .proto files.
  • buf.gen.yaml: Configuration for Buf's code generation, specifying how .proto files are compiled into code for different languages (e.g., Go).

Getting Started

To incorporate the Toolkit into your project, follow these steps:

  1. Add the dependency: Add the Toolkit as a dependency in your go.mod file, specifying the latest version:

go get github.com/origadmin/runtime@vX.Y.Z

Replace vX.Y.Z with the desired version or latest to fetch the most recent release.

  1. Import required packages: In your Go source files, import the necessary packages from the Toolkit:
import (
"github.com/origadmin/runtime"
"github.com/origadmin/runtime/config"
"github.com/origadmin/runtime/registry"
)

// NewDiscovery creates a new discovery.
func NewDiscovery(registryConfig *config.RegistryConfig) registry.Discovery {
if registryConfig == nil {
panic("no registry config")
}
discovery, err := runtime.NewDiscovery(registryConfig)
if err != nil {
panic(err)
}
return discovery
}

// NewRegistrar creates a new registrar.
func NewRegistrar(registryConfig *config.RegistryConfig) registry.Registrar {
if registryConfig == nil {
panic("no registry config")
}
registrar, err := runtime.NewRegistrar(registryConfig)
if err != nil {
panic(err)
}
return registrar
}

Contributing

We welcome contributions from the community to improve and expand the Toolkit. To contribute, please follow these guidelines:

  1. Familiarize yourself with the project: Read the CONTRIBUTING file for details on the contribution process, code style, and Pull Request requirements.
  2. Submit an issue or proposal: If you encounter any bugs, have feature suggestions, or want to discuss potential changes, create an issue in the GitHub repository.
  3. Create a Pull Request: After implementing your changes, submit a Pull Request following the guidelines outlined in CONTRIBUTING.

Contributors

Code of Conduct

All contributors and participants are expected to abide by the Contributor Covenant, version 2.1. This document outlines the expected behavior when interacting with the Toolkit community.

License

The Toolkit is distributed under the terms of the MIT. This permissive license allows for free use, modification, and distribution of the toolkit in both commercial and non-commercial contexts.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultResolvers = map[component.Category]component.ConfigResolver{
	CategoryLogger:      log.Resolve,
	CategoryRegistrar:   registry.Resolve,
	CategoryDiscovery:   registry.Resolve,
	CategoryMiddleware:  middleware.Resolve,
	CategoryDatabase:    database.Resolve,
	CategoryCache:       cache.Resolve,
	CategoryObjectStore: objectstore.Resolve,
}

Functions

func AdjustAppInfo added in v0.2.19

func AdjustAppInfo(ai *appv1.App)

AdjustAppInfo adjusts the application info, setting default values.

func CloneAppInfo added in v0.2.19

func CloneAppInfo(src *appv1.App) *appv1.App

CloneAppInfo clones the application info.

func NewAppInfo added in v0.2.6

func NewAppInfo(name, version string) *appv1.App

NewAppInfo creates a new application information instance.

func NewAppInfoBuilder added in v0.2.14

func NewAppInfoBuilder() *appv1.App

NewAppInfoBuilder returns a new, blank App instance for building.

func NewContext added in v0.2.19

func NewContext(ctx context.Context) context.Context

NewContext creates a new context from the app context.

func NewInstanceID added in v0.2.19

func NewInstanceID(project, appID, version, host string) string

NewInstanceID generates an instance ID.

func NewTrace added in v0.2.19

func NewTrace(ctx context.Context, traceID string) context.Context

NewTrace creates a new context with the given trace ID.

func ProvideDefaultRegistrar added in v0.2.6

func ProvideDefaultRegistrar(rt *App) (kregistry.Registrar, error)

ProvideDefaultRegistrar is a Wire provider function that extracts the registrar from the App.

func ProvideLogger added in v0.2.6

func ProvideLogger(rt *App) log.Logger

ProvideLogger is a Wire provider function that extracts the logger from the App.

func Register added in v0.2.19

func Register(cat Category, p Provider, opts ...RegisterOption)

Register adds a component registration to the engine.

func ResolveHost added in v0.2.19

func ResolveHost() string

ResolveHost returns the host identifier.

func UpdateAppInfo added in v0.2.19

func UpdateAppInfo(dst, src *appv1.App)

UpdateAppInfo merges application information from a source App into a destination App. Only non-empty fields from the source will overwrite the destination fields.

Types

type App added in v0.2.13

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

App defines the application's runtime environment powered by engine.

func New

func New(name, version string, opts ...Option) *App

New creates a new App instance.

func NewWithAppInfo added in v0.2.19

func NewWithAppInfo(info *appv1.App, opts ...Option) *App

NewWithAppInfo creates a new App instance using a pre-configured App info.

func (*App) AppInfo added in v0.2.13

func (r *App) AppInfo() *appv1.App

func (*App) Config added in v0.2.13

func (r *App) Config() any

func (*App) Container added in v0.2.13

func (r *App) Container() component.Container

func (*App) Context added in v0.2.16

func (r *App) Context() context.Context

Context returns the app context.

func (*App) Decoder added in v0.2.19

func (r *App) Decoder() runtimeconfig.KConfig

Getters

func (*App) DefaultRegistrar added in v0.2.13

func (r *App) DefaultRegistrar() (kregistry.Registrar, error)

func (*App) Discoveries added in v0.2.19

func (r *App) Discoveries() (map[string]registry.KDiscovery, error)

func (*App) In added in v0.2.19

func (r *App) In(cat Category, opts ...InOption) component.Registry

func (*App) Load added in v0.2.13

func (r *App) Load(path string, bootOpts ...bootstrap.Option) error

Load loads configuration into Result.

func (*App) Logger added in v0.2.13

func (r *App) Logger() log.Logger

func (*App) NewApp added in v0.2.13

func (r *App) NewApp(servers []transport.Server, options ...kratos.Option) *kratos.App

func (*App) Result added in v0.2.19

func (r *App) Result() bootstrap.Result

func (*App) ShowAppInfo added in v0.2.19

func (r *App) ShowAppInfo()

func (*App) Stop added in v0.2.16

func (r *App) Stop()

func (*App) WarmUp added in v0.2.13

func (r *App) WarmUp() error

WarmUp activates the engine with the loaded configuration.

type AppOption added in v0.2.19

type AppOption = Option

type Category added in v0.2.19

type Category = component.Category
const (
	CategoryInfrastructure Category = "infrastructure"
	CategoryLogger         Category = "logger"
	CategoryRegistrar      Category = "registrar"
	CategoryDiscovery      Category = "discovery"
	CategoryClient         Category = "client"
	CategoryServer         Category = "server"
	CategoryMiddleware     Category = "middleware"
	CategoryDatabase       Category = "database"
	CategoryCache          Category = "cache"
	CategoryObjectStore    Category = "objectstore"
	CategoryQueue          Category = "queue"
	CategoryTask           Category = "task"
	CategoryMail           Category = "mail"
	CategoryStorage        Category = "storage"
	CategorySecurity       Category = "security"
	CategorySkipper        Category = "skipper"
)

type ConfigEntry added in v0.2.19

type ConfigEntry = component.ConfigEntry

type ConfigResolver added in v0.2.19

type ConfigResolver = component.ConfigResolver

type Container added in v0.2.19

type Container = component.Container

type Handle added in v0.2.19

type Handle = component.Handle

type InOption added in v0.2.19

type InOption = component.InOption

func WithInScope added in v0.2.19

func WithInScope(s Scope) InOption

WithInScope specifies the perspective scope.

func WithInTags added in v0.2.19

func WithInTags(tags ...string) InOption

WithInTags specifies the perspective tags.

type LoadOption added in v0.2.19

type LoadOption = component.LoadOption

type Locator added in v0.2.19

type Locator = component.Locator

type ModuleConfig added in v0.2.19

type ModuleConfig = component.ModuleConfig

type Option added in v0.2.0

type Option func(*App)

Option is a functional option for configuring the App. It allows for applying configurations to the App instance at creation time.

func WithContainer added in v0.2.19

func WithContainer(fn func(component.Container)) Option

WithContainer sets a callback to configure the internal engine container.

func WithEnv added in v0.2.13

func WithEnv(env string) Option

WithEnv sets the environment for the application.

func WithID added in v0.2.13

func WithID(id string) Option

WithID sets a custom instance ID.

func WithMetadata added in v0.2.13

func WithMetadata(key, value string) Option

WithMetadata adds a key-value pair to the application's metadata.

func WithMetadataMap added in v0.2.13

func WithMetadataMap(metadata map[string]string) Option

WithMetadataMap adds a map of key-value pairs to the application's metadata.

func WithStartTime added in v0.2.13

func WithStartTime(startTime time.Time) Option

WithStartTime sets a custom start time.

type Priority added in v0.2.19

type Priority = component.Priority

type Provider added in v0.2.19

type Provider = component.Provider

type RegisterOption added in v0.2.19

type RegisterOption = component.RegisterOption

func WithEntries added in v0.2.19

func WithEntries(names ...string) RegisterOption

WithEntries specifies the default entries for a component.

func WithRequirement added in v0.2.19

func WithRequirement(f func(ctx context.Context, h component.Handle, purpose string) (any, error)) RegisterOption

WithRequirement specifies a local requirement resolver for a component.

func WithResolver added in v0.2.1

func WithResolver(res component.ConfigResolver) RegisterOption

WithResolver specifies a local config resolver for a component.

func WithScopes added in v0.2.19

func WithScopes(ss ...Scope) RegisterOption

WithScopes specifies the scopes for a component.

func WithTag added in v0.2.19

func WithTag(tag string) RegisterOption

WithTag specifies the tag for a component.

type Registration added in v0.2.19

type Registration = component.Registration

type RegistrationOptions added in v0.2.19

type RegistrationOptions = component.RegistrationOptions

type Registry added in v0.2.19

type Registry = component.Registry

type RequirementResolver added in v0.2.19

type RequirementResolver = component.RequirementResolver

type Scope added in v0.2.19

type Scope = component.Scope
const (
	// GlobalScope is the default fallback scope for the system.
	GlobalScope Scope = ""
	// ServerScope is the standard scope for server-side components.
	ServerScope Scope = "server"
	// ClientScope is the standard scope for client-side components.
	ClientScope Scope = "client"
)

Directories

Path Synopsis
api
Package config contains generated code by adptool.
Package config contains generated code by adptool.
envsource
Package envsource is a configuration source that loads environment variables.
Package envsource is a configuration source that loads environment variables.
file
Package file implements the functions, types, and contracts for the module.
Package file implements the functions, types, and contracts for the module.
internal/reflection
Package reflection implements the functions, types, and contracts for the module.
Package reflection implements the functions, types, and contracts for the module.
protoutil
Package protoutil provides utility functions for working with protobuf Any messages.
Package protoutil provides utility functions for working with protobuf Any messages.
broker
Package broker defines a generic interface for a message broker.
Package broker defines a generic interface for a message broker.
storage
Package storage defines the contracts for storage services.
Package storage defines the contracts for storage services.
storage/database
Package database implements the functions, types, and contracts for the module.
Package database implements the functions, types, and contracts for the module.
data
storage
Package storage provides a unified interface for various storage solutions including cache, database, and file storage.
Package storage provides a unified interface for various storage solutions including cache, database, and file storage.
storage/cache
Package cache provides a factory function to create Cache instances.
Package cache provides a factory function to create Cache instances.
storage/database
Package database implements the functions, types, and contracts for the module.
Package database implements the functions, types, and contracts for the module.
storage/objectstore
Package objectstore provides a factory function to create ObjectStore instances.
Package objectstore provides a factory function to create ObjectStore instances.
context
Package context contains generated code by adptool.
Package context contains generated code by adptool.
Package errors provides enhanced error handling with module support, error codes, and metadata.
Package errors provides enhanced error handling with module support, error codes, and metadata.
examples
storage command
helpers
comp
Package comp provides concise generic utility functions for component handling.
Package comp provides concise generic utility functions for component handling.
optionutil
Package optionutil provides utility functions for working with options.Context.
Package optionutil provides utility functions for working with options.Context.
Package log implements the functions, types, and contracts for the module.
Package log implements the functions, types, and contracts for the module.
Package middleware implements the functions, types, and contracts for the module.
Package middleware implements the functions, types, and contracts for the module.
cors
Package cors implements CORS middleware for the framework.
Package cors implements CORS middleware for the framework.
validate
Package validate implements the functions, types, and contracts for the module.
Package validate implements the functions, types, and contracts for the module.
Package registry implements the functions, types, and contracts for the module.
Package registry implements the functions, types, and contracts for the module.
Package service implements the functions, types, and contracts for the module.
Package service implements the functions, types, and contracts for the module.
selector
Package selector contains generated code by adptool.
Package selector contains generated code by adptool.
tls
Package tls implements the functions, types, and contracts for the module.
Package tls implements the functions, types, and contracts for the module.
transport
Package transport contains generated code by adptool.
Package transport contains generated code by adptool.
tests

Jump to

Keyboard shortcuts

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