runtime

package module
v0.2.8 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2025 License: MIT Imports: 9 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/toolkit/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/toolkit/runtime"
"github.com/origadmin/toolkit/runtime/config"
"github.com/origadmin/toolkit/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 ProvideDefaultRegistrar added in v0.2.6

func ProvideDefaultRegistrar(rt Runtime) registry.Registrar

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

func ProvideLogger added in v0.2.6

func ProvideLogger(rt Runtime) log.Logger

ProvideLogger is a Wire provider function that extracts the logger from the Runtime interface. It is intended to be used by the application's own Wire injector.

func WithAppInfo added in v0.2.7

func WithAppInfo(info *AppInfo) bootstrap.Option

WithAppInfo returns an Option that sets the application information.

Types

type AppInfo added in v0.2.6

type AppInfo interfaces.AppInfo

AppInfo represents the application's static, immutable identity information. It includes essential metadata such as the application's name, version, environment, and instance ID. This information is determined at startup and remains constant throughout the application's lifecycle.

func NewAppInfo added in v0.2.6

func NewAppInfo(name, version, env string) *AppInfo

NewAppInfo creates a new AppInfo instance with default values for ID, StartTime, and Metadata. It requires the application's name, version, and environment.

func (AppInfo) GetEnv added in v0.2.6

func (a AppInfo) GetEnv() string

GetEnv returns the environment the application is running in.

func (AppInfo) GetID added in v0.2.6

func (a AppInfo) GetID() string

GetID returns the unique identifier of the application instance.

func (AppInfo) GetName added in v0.2.6

func (a AppInfo) GetName() string

GetName returns the name of the application.

func (AppInfo) GetStartTime added in v0.2.6

func (a AppInfo) GetStartTime() time.Time

GetStartTime returns the time the application was started.

func (AppInfo) GetUptime added in v0.2.6

func (a AppInfo) GetUptime() time.Duration

GetUptime returns the duration since the application was started.

func (AppInfo) GetVersion added in v0.2.6

func (a AppInfo) GetVersion() string

GetVersion returns the version of the application.

func (AppInfo) IsValid added in v0.2.6

func (a AppInfo) IsValid() bool

IsValid checks if the AppInfo instance contains essential, non-empty identification fields.

func (AppInfo) Options added in v0.2.6

func (a AppInfo) Options() []kratos.Option

Options returns a slice of kratos.Option with the application's identity fields, suitable for passing to kratos.New().

func (AppInfo) String added in v0.2.6

func (a AppInfo) String() string

String implements the fmt.Stringer interface for easy logging and identification. It returns a string in the format "name-version".

func (AppInfo) WithMetadata added in v0.2.6

func (a AppInfo) WithMetadata(key, value string) AppInfo

WithMetadata returns a new AppInfo with the provided key-value pair added to the metadata. This method supports fluent chaining, e.g., appInfo.WithMetadata(...).WithMetadata(...)

type Runtime added in v0.1.15

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

Runtime defines the application's runtime environment, providing convenient access to core components. It encapsulates an interfaces.Container and is the primary object that applications will interact with.

func New

func New(result bootstrap.Result) *Runtime

New is the core constructor for a Runtime instance. It takes a fully initialized bootstrap result, which is guaranteed to be non-nil.

func NewFromBootstrap added in v0.2.6

func NewFromBootstrap(bootstrapPath string, opts ...bootstrap.Option) (*Runtime, error)

NewFromBootstrap is a convenience constructor that simplifies application startup. It encapsulates the entire process of calling bootstrap.New and then runtime.New. It accepts bootstrap.Option parameters directly, allowing the user to configure the bootstrap process.

func (*Runtime) AppInfo added in v0.2.6

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

AppInfo returns the application's configured information (ID, name, version, metadata).

func (*Runtime) Cleanup added in v0.2.7

func (r *Runtime) Cleanup()

Cleanup executes the cleanup function for all resources acquired during bootstrap. This should be called via defer right after the Runtime is created.

func (*Runtime) Component added in v0.2.6

func (r *Runtime) Component(name string) (interface{}, bool)

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

func (*Runtime) Config added in v0.1.15

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

Config returns the configuration decoder, allowing access to raw configuration values.

func (*Runtime) Container added in v0.2.7

func (r *Runtime) Container() interfaces.Container

Container returns the underlying dependency injection container. This method is primarily for advanced use cases where direct access to the container is necessary. For most common operations, prefer using the specific accessor methods provided by the Runtime (e.g., Logger(), Config(), Component()).

func (*Runtime) DefaultRegistrar added in v0.2.6

func (r *Runtime) DefaultRegistrar() registry.Registrar

DefaultRegistrar returns the default service registrar, used for service self-registration. It may be nil if no default registry is configured.

func (*Runtime) Discovery added in v0.2.6

func (r *Runtime) Discovery(name string) (registry.Discovery, bool)

Discovery returns a service discovery component by its configured name.

func (*Runtime) Logger added in v0.2.6

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

Logger returns the configured Kratos logger.

func (*Runtime) NewApp added in v0.2.6

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

NewApp creates a new Kratos application instance. It wires together the runtime's configured components (like the default registrar) with the provided transport servers. It now accepts additional Kratos options for more flexible configuration.

func (*Runtime) Registrar added in v0.2.6

func (r *Runtime) Registrar(name string) (registry.Registrar, bool)

Registrar returns a service registrar component by its configured name.

func (*Runtime) StructuredConfig added in v0.2.7

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

StructuredConfig returns the structured configuration decoder, which provides path-based access to configuration values. This is typically used for initializing components like servers and clients that require specific configuration blocks.

Directories

Path Synopsis
api
Package bootstrap implements the functions, types, and interfaces for the module.
Package bootstrap implements the functions, types, and interfaces for the module.
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.
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
extension
customize
Package customize provides helper functions for working with flexible configuration structures in Protobuf, such as google.protobuf.Struct and google.protobuf.Any.
Package customize provides helper functions for working with flexible configuration structures in Protobuf, such as google.protobuf.Struct and google.protobuf.Any.
database
Package database implements the functions, types, and interfaces for the module.
Package database implements the functions, types, and interfaces for the module.
pagination
Package pagination implements the functions, types, and interfaces for the module.
Package pagination implements the functions, types, and interfaces for the module.
security
Package security implements the functions, types, and interfaces for the module.
Package security implements the functions, types, and interfaces for the module.
security/token
Package token provides token caching functionality for security module
Package token provides token caching functionality for security module
storage
Package storage implements the functions, types, and interfaces for the module.
Package storage implements the functions, types, and interfaces for the module.
storage/components/blob
Package blob implements the functions, types, and interfaces for the module.
Package blob implements the functions, types, and interfaces for the module.
storage/components/layout
Package layout provides a generic interface for storage layouts.
Package layout provides a generic interface for storage layouts.
storage/components/meta
Package meta implements the functions, types, and interfaces for the module.
Package meta 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 mail implements the functions, types, and interfaces for the module.
Package mail 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 optionutil provides utility functions for working with options.Context.
Package optionutil provides utility functions for working with options.Context.
Package registry contains generated code by adptool.
Package registry contains generated code by adptool.
Package service contains generated code by adptool.
Package service contains generated code by adptool.
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.
Package storage implements the functions, types, and interfaces for the module.
Package storage implements the functions, types, and interfaces for the module.
filestore/meta
Package meta implements the functions, types, and interfaces for the module.
Package meta implements the functions, types, and interfaces for the module.
filestore/meta/v1
Package metav1 implements the functions, types, and interfaces for the module.
Package metav1 implements the functions, types, and interfaces for the module.
filestore/meta/v2
Package metav2 implements the functions, types, and interfaces for the module.
Package metav2 implements the functions, types, and interfaces for the module.
test

Jump to

Keyboard shortcuts

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