runtime

package module
v0.2.15 Latest Latest
Warning

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

Go to latest
Published: Dec 30, 2025 License: MIT Imports: 17 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

This section is empty.

Functions

func ConvertToAppInfo added in v0.2.13

func ConvertToAppInfo(appConfig *appv1.App) interfaces.AppInfo

ConvertToAppInfo converts a protobuf App message to an interfaces.AppInfo.

func ProvideDefaultRegistrar added in v0.2.6

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

ProvideDefaultRegistrar is a Wire provider function that extracts the default registrar from the App interface. It is intended to be used by the application's own Wire injector.

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 interface. It is intended to be used by the application's own Wire injector.

Types

type App added in v0.2.13

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

App defines the application's runtime environment.

func New

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

New is the primary and most common constructor for creating a new App instance. It requires the application name and version directly.

func NewWithOptions added in v0.2.14

func NewWithOptions(opts ...Option) *App

NewWithOptions creates a new, partially initialized App instance using only functional options. This constructor provides maximum flexibility. It requires that the application's name and version be provided via options (e.g., by using WithAppInfo).

func (*App) AddComponentOptions added in v0.2.13

func (r *App) AddComponentOptions(name string, opts ...options.Option)

AddComponentOptions provides a generic way to add pre-configured options for any named component.

func (*App) AddGlobalOptions added in v0.2.13

func (r *App) AddGlobalOptions(opts ...options.Option)

AddGlobalOptions adds options that will be applied to all providers.

func (*App) AppInfo added in v0.2.13

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

AppInfo returns the application's metadata as an interface.

func (*App) CacheProvider added in v0.2.13

func (r *App) CacheProvider() (container.CacheProvider, error)

CacheProvider returns the cache provider, using pre-configured options.

func (*App) Component added in v0.2.13

func (r *App) Component(name string) (interface{}, error)

Component retrieves a generic, user-defined component by its registered name.

func (*App) Config added in v0.2.13

func (r *App) Config() interfaces.Config

Config returns the configuration decoder.

func (*App) ConfigureCache added in v0.2.13

func (r *App) ConfigureCache(opts ...options.Option)

ConfigureCache adds pre-configured options for the cache provider.

func (*App) ConfigureDatabase added in v0.2.13

func (r *App) ConfigureDatabase(opts ...options.Option)

ConfigureDatabase adds pre-configured options for the database provider.

func (*App) ConfigureMiddleware added in v0.2.13

func (r *App) ConfigureMiddleware(opts ...options.Option)

ConfigureMiddleware adds pre-configured options for the middleware provider.

func (*App) ConfigureObjectStore added in v0.2.13

func (r *App) ConfigureObjectStore(opts ...options.Option)

ConfigureObjectStore adds pre-configured options for the object store provider.

func (*App) ConfigureRegistry added in v0.2.13

func (r *App) ConfigureRegistry(opts ...options.Option)

ConfigureRegistry adds pre-configured options for the registry provider.

func (*App) Container added in v0.2.13

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

Container returns the underlying dependency injection container.

func (*App) DatabaseProvider added in v0.2.13

func (r *App) DatabaseProvider() (container.DatabaseProvider, error)

DatabaseProvider returns the database provider, using pre-configured options.

func (*App) DefaultRegistrar added in v0.2.13

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

DefaultRegistrar returns the default service registrar.

func (*App) Load added in v0.2.13

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

Load reads the configuration from the given path, completes the App initialization, and prepares it for running. It returns an error if the final application name or version is missing after merging all configurations.

func (*App) Logger added in v0.2.13

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

Logger returns the configured Kratos logger.

func (*App) MiddlewareProvider added in v0.2.13

func (r *App) MiddlewareProvider() (container.MiddlewareProvider, error)

MiddlewareProvider returns the middleware provider, using pre-configured options.

func (*App) NewApp added in v0.2.13

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

NewApp creates a new Kratos application instance.

func (*App) ObjectStoreProvider added in v0.2.13

func (r *App) ObjectStoreProvider() (container.ObjectStoreProvider, error)

ObjectStoreProvider returns the object store provider, using pre-configured options.

func (*App) RegistryProvider added in v0.2.13

func (r *App) RegistryProvider() (container.RegistryProvider, error)

RegistryProvider returns the service registry provider, using pre-configured options.

func (*App) StructuredConfig added in v0.2.13

func (r *App) StructuredConfig() interfaces.StructuredConfig

StructuredConfig returns the structured configuration decoder.

func (*App) WarmUp added in v0.2.13

func (r *App) WarmUp() error

WarmUp attempts to initialize all configured providers and generic components. This method should be called after all configurations have been added to the App. It returns an error if any component fails to initialize, allowing for early error detection.

type AppInfo added in v0.2.6

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

AppInfo is the concrete, exported implementation that satisfies the AppInfo interface.

func NewAppInfo added in v0.2.6

func NewAppInfo(name, version string) *AppInfo

NewAppInfo is the primary constructor for creating a pre-configured AppInfo instance.

func NewAppInfoBuilder added in v0.2.14

func NewAppInfoBuilder() *AppInfo

NewAppInfoBuilder returns a new, blank AppInfo instance, serving as the entry point for chainable method configurations.

func (*AppInfo) AddMetadata added in v0.2.14

func (a *AppInfo) AddMetadata(key, value string) *AppInfo

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

func (*AppInfo) Env added in v0.2.14

func (a *AppInfo) Env() string

func (*AppInfo) ID added in v0.2.14

func (a *AppInfo) ID() string

func (*AppInfo) Merge added in v0.2.14

func (a *AppInfo) Merge(other interfaces.AppInfo)

Merge combines the current AppInfo with another interfaces.AppInfo. Values from the 'other' AppInfo will override the current AppInfo's values if they are not empty or zero.

func (*AppInfo) Metadata added in v0.2.14

func (a *AppInfo) Metadata() map[string]string

Metadata returns a defensive copy of the metadata map to ensure immutability.

func (*AppInfo) Name added in v0.2.14

func (a *AppInfo) Name() string

func (*AppInfo) SetEnv added in v0.2.14

func (a *AppInfo) SetEnv(env string) *AppInfo

SetEnv sets the application environment.

func (*AppInfo) SetID added in v0.2.14

func (a *AppInfo) SetID(id string) *AppInfo

SetID sets the application ID.

func (*AppInfo) SetMetadata added in v0.2.14

func (a *AppInfo) SetMetadata(metadata map[string]string) *AppInfo

SetMetadata completely replaces the application's metadata with the provided map.

func (*AppInfo) SetName added in v0.2.14

func (a *AppInfo) SetName(name string) *AppInfo

SetName sets the application name.

func (*AppInfo) SetNameAndVersion added in v0.2.14

func (a *AppInfo) SetNameAndVersion(name, version string) *AppInfo

SetNameAndVersion sets both the application name and version.

func (*AppInfo) SetStartTime added in v0.2.14

func (a *AppInfo) SetStartTime(startTime time.Time) *AppInfo

SetStartTime sets the application start time.

func (*AppInfo) SetVersion added in v0.2.14

func (a *AppInfo) SetVersion(version string) *AppInfo

SetVersion sets the application version.

func (*AppInfo) StartTime added in v0.2.14

func (a *AppInfo) StartTime() time.Time

func (*AppInfo) Version added in v0.2.14

func (a *AppInfo) Version() string

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 WithAppInfo added in v0.2.7

func WithAppInfo(info *AppInfo) Option

WithAppInfo sets the App's AppInfo using a concrete *AppInfo instance. This option has priority over the name and version parameters in New().

func WithContainerOptions added in v0.2.13

func WithContainerOptions(opts ...options.Option) Option

WithContainerOptions adds options that will be applied to the dependency injection container. These options are collected during the New() phase and applied during the Load() phase when the container is created.

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.

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 interfaces for the module.
Package file implements the functions, types, and interfaces for the module.
internal/reflection
Package reflection implements the functions, types, and interfaces for the module.
Package reflection implements the functions, types, and interfaces 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.
internal/util
Package util implements the functions, types, and interfaces for the module.
Package util implements the functions, types, and interfaces for the module.
Package context contains generated code by adptool.
Package context contains generated code by adptool.
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 interfaces for the module.
Package database implements the functions, types, and interfaces 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.
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
extensions
optionutil
Package optionutil provides utility functions for working with options.Context.
Package optionutil provides utility functions for working with options.Context.
constant
Package constant defines the constant keys for structured configuration components.
Package constant defines the constant keys for structured configuration components.
storage
Package storage defines the interfaces for storage services.
Package storage defines the interfaces for storage services.
storage/database
Package database implements the functions, types, and interfaces for the module.
Package database implements the functions, types, and interfaces for the module.
internal
factory
Package factory implements the functions, types, and interfaces for the module.
Package factory implements the functions, types, and interfaces for the module.
Package log implements the functions, types, and interfaces for the module.
Package log implements the functions, types, and interfaces for the module.
Package middleware implements the functions, types, and interfaces for the module.
Package middleware implements the functions, types, and interfaces 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 interfaces for the module.
Package validate implements the functions, types, and interfaces for the module.
Package registry implements the functions, types, and interfaces for the module.
Package registry implements the functions, types, and interfaces for the module.
Package service implements the functions, types, and interfaces for the module.
Package service implements the functions, types, and interfaces 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 interfaces for the module.
Package tls implements the functions, types, and interfaces for the module.
transport
Package transport contains generated code by adptool.
Package transport contains generated code by adptool.
test

Jump to

Keyboard shortcuts

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