chore: import upstream snapshot with attribution
govulncheck / govulncheck (push) Has been cancelled
Lint / golangci-lint (push) Has been cancelled
Run Tests / Unit Tests (push) Has been cancelled
Run Tests / Etcd Integration Tests (push) Has been cancelled
Harness (E2E) / Harnesses (mock LLM) (push) Has been cancelled
Harness (E2E) / Provider harnesses (live LLM conformance) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:40:33 +08:00
commit e071084ebe
982 changed files with 160368 additions and 0 deletions
+98
View File
@@ -0,0 +1,98 @@
package service
import (
"context"
"os"
"os/signal"
"sync"
signalutil "go-micro.dev/v6/internal/util/signal"
log "go-micro.dev/v6/logger"
)
// Group runs multiple services in a single binary with shared
// lifecycle management. All services start together and stop
// together on signal or context cancellation.
type Group struct {
services []Service
logger log.Logger
}
// NewGroup creates a new service group.
func NewGroup(svcs ...Service) *Group {
return &Group{
services: svcs,
logger: log.DefaultLogger,
}
}
// Add appends one or more services to the group.
func (g *Group) Add(svcs ...Service) {
g.services = append(g.services, svcs...)
}
// Run starts all services concurrently and blocks until a signal
// is received or the context is canceled, then stops all services.
func (g *Group) Run() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Initialize all services. Disable per-service signal handling
// since the group manages signals.
for _, svc := range g.services {
svc.Init(HandleSignal(false))
}
g.logger.Logf(log.InfoLevel, "Starting service group with %d services", len(g.services))
// Start all services
errCh := make(chan error, len(g.services))
for _, svc := range g.services {
g.logger.Logf(log.InfoLevel, "Starting [service] %s", svc.Name())
if err := svc.Start(); err != nil {
cancel()
_ = g.stopAll()
return err
}
}
// Wait for signal or context cancellation
ch := make(chan os.Signal, 1)
signal.Notify(ch, signalutil.Shutdown()...)
select {
case <-ch:
g.logger.Logf(log.InfoLevel, "Received signal, stopping all services")
case <-ctx.Done():
case err := <-errCh:
cancel()
_ = g.stopAll()
return err
}
return g.stopAll()
}
func (g *Group) stopAll() error {
var (
mu sync.Mutex
lastErr error
)
var wg sync.WaitGroup
for _, svc := range g.services {
wg.Add(1)
go func(s Service) {
defer wg.Done()
g.logger.Logf(log.InfoLevel, "Stopping [service] %s", s.Name())
if err := s.Stop(); err != nil {
mu.Lock()
lastErr = err
mu.Unlock()
}
}(svc)
}
wg.Wait()
return lastErr
}
+368
View File
@@ -0,0 +1,368 @@
package service
import (
"context"
"time"
"github.com/urfave/cli/v2"
"go-micro.dev/v6/auth"
"go-micro.dev/v6/broker"
"go-micro.dev/v6/cache"
"go-micro.dev/v6/client"
"go-micro.dev/v6/cmd"
"go-micro.dev/v6/config"
"go-micro.dev/v6/debug/profile"
"go-micro.dev/v6/debug/trace"
"go-micro.dev/v6/logger"
"go-micro.dev/v6/model"
"go-micro.dev/v6/model/memory"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/selector"
"go-micro.dev/v6/server"
"go-micro.dev/v6/store"
"go-micro.dev/v6/transport"
)
// Options for micro service.
type Options struct {
Registry registry.Registry
Store store.Store
Auth auth.Auth
Cmd cmd.Cmd
Config config.Config
Client client.Client
Server server.Server
Model model.Model
// Other options for implementations of the interface
// can be stored in a context
Context context.Context
Cache cache.Cache
Profile profile.Profile
Transport transport.Transport
Logger logger.Logger
Broker broker.Broker
// Before and After funcs
BeforeStart []func() error
AfterStart []func() error
AfterStop []func() error
BeforeStop []func() error
Signal bool
}
type Option func(*Options)
func newOptions(opts ...Option) Options {
opt := Options{
Auth: auth.DefaultAuth,
Broker: broker.DefaultBroker,
Cmd: cmd.NewCmd(),
Config: config.DefaultConfig,
// Per-service instances: each service gets its own server, client,
// store, and cache to allow multiple services in a single binary.
Client: client.NewClient(),
Server: server.NewRPCServer(),
Store: store.NewStore(),
Model: memory.New(),
Cache: cache.NewCache(),
Registry: registry.DefaultRegistry,
Transport: transport.DefaultTransport,
Context: context.Background(),
Signal: true,
Logger: logger.DefaultLogger,
}
for _, o := range opts {
o(&opt)
}
return opt
}
// Broker to be used for service.
func Broker(b broker.Broker) Option {
return func(o *Options) {
o.Broker = b
// Update Client and Server
_ = o.Client.Init(client.Broker(b))
_ = o.Server.Init(server.Broker(b))
}
}
func Cache(c cache.Cache) Option {
return func(o *Options) {
o.Cache = c
}
}
func Cmd(c cmd.Cmd) Option {
return func(o *Options) {
o.Cmd = c
}
}
// Client to be used for service.
func Client(c client.Client) Option {
return func(o *Options) {
o.Client = c
}
}
// Context specifies a context for the service.
// Can be used to signal shutdown of the service and for extra option values.
func Context(ctx context.Context) Option {
return func(o *Options) {
o.Context = ctx
}
}
// Handle will register a handler without any fuss
func Handle(v interface{}) Option {
return func(o *Options) {
_ = o.Server.Handle(
o.Server.NewHandler(v),
)
}
}
// HandleSignal toggles automatic installation of the signal handler that
// traps TERM, INT, and QUIT. Users of this feature to disable the signal
// handler, should control liveness of the service through the context.
func HandleSignal(b bool) Option {
return func(o *Options) {
o.Signal = b
}
}
// Profile to be used for debug profile.
func Profile(p profile.Profile) Option {
return func(o *Options) {
o.Profile = p
}
}
// Server to be used for service.
func Server(s server.Server) Option {
return func(o *Options) {
o.Server = s
}
}
// Store sets the store to use.
func Store(s store.Store) Option {
return func(o *Options) {
o.Store = s
}
}
// Model sets the model backend to use.
func Model(m model.Model) Option {
return func(o *Options) {
o.Model = m
}
}
// Registry sets the registry for the service
// and the underlying components.
func Registry(r registry.Registry) Option {
return func(o *Options) {
o.Registry = r
// Update Client and Server
_ = o.Client.Init(client.Registry(r))
_ = o.Server.Init(server.Registry(r))
// Update Broker
_ = o.Broker.Init(broker.Registry(r))
}
}
// Tracer sets the tracer for the service.
func Tracer(t trace.Tracer) Option {
return func(o *Options) {
_ = o.Server.Init(server.Tracer(t))
}
}
// Auth sets the auth for the service.
func Auth(a auth.Auth) Option {
return func(o *Options) {
o.Auth = a
}
}
// Config sets the config for the service.
func Config(c config.Config) Option {
return func(o *Options) {
o.Config = c
}
}
// Selector sets the selector for the service client.
func Selector(s selector.Selector) Option {
return func(o *Options) {
_ = o.Client.Init(client.Selector(s))
}
}
// Transport sets the transport for the service
// and the underlying components.
func Transport(t transport.Transport) Option {
return func(o *Options) {
o.Transport = t
// Update Client and Server
_ = o.Client.Init(client.Transport(t))
_ = o.Server.Init(server.Transport(t))
}
}
// Convenience options
// Address sets the address of the server.
func Address(addr string) Option {
return func(o *Options) {
_ = o.Server.Init(server.Address(addr))
}
}
// Name of the service.
func Name(n string) Option {
return func(o *Options) {
_ = o.Server.Init(server.Name(n))
}
}
// Version of the service.
func Version(v string) Option {
return func(o *Options) {
_ = o.Server.Init(server.Version(v))
}
}
// Metadata associated with the service.
func Metadata(md map[string]string) Option {
return func(o *Options) {
_ = o.Server.Init(server.Metadata(md))
}
}
// Flags that can be passed to service.
func Flags(flags ...cli.Flag) Option {
return func(o *Options) {
o.Cmd.App().Flags = append(o.Cmd.App().Flags, flags...)
}
}
// Action can be used to parse user provided cli options.
func Action(a func(*cli.Context) error) Option {
return func(o *Options) {
o.Cmd.App().Action = a
}
}
// RegisterTTL specifies the TTL to use when registering the service.
func RegisterTTL(t time.Duration) Option {
return func(o *Options) {
_ = o.Server.Init(server.RegisterTTL(t))
}
}
// RegisterInterval specifies the interval on which to re-register.
func RegisterInterval(t time.Duration) Option {
return func(o *Options) {
_ = o.Server.Init(server.RegisterInterval(t))
}
}
// WrapClient is a convenience method for wrapping a Client with
// some middleware component. A list of wrappers can be provided.
// Wrappers are applied in reverse order so the last is executed first.
func WrapClient(w ...client.Wrapper) Option {
return func(o *Options) {
// apply in reverse
for i := len(w); i > 0; i-- {
o.Client = w[i-1](o.Client)
}
}
}
// WrapCall is a convenience method for wrapping a Client CallFunc.
func WrapCall(w ...client.CallWrapper) Option {
return func(o *Options) {
_ = o.Client.Init(client.WrapCall(w...))
}
}
// WrapHandler adds a handler Wrapper to a list of options passed into the server.
func WrapHandler(w ...server.HandlerWrapper) Option {
return func(o *Options) {
var wrappers []server.Option
for _, wrap := range w {
wrappers = append(wrappers, server.WrapHandler(wrap))
}
// Init once
_ = o.Server.Init(wrappers...)
}
}
// WrapSubscriber adds a subscriber Wrapper to a list of options passed into the server.
func WrapSubscriber(w ...server.SubscriberWrapper) Option {
return func(o *Options) {
var wrappers []server.Option
for _, wrap := range w {
wrappers = append(wrappers, server.WrapSubscriber(wrap))
}
// Init once
_ = o.Server.Init(wrappers...)
}
}
// Add opt to server option.
func AddListenOption(option server.Option) Option {
return func(o *Options) {
_ = o.Server.Init(option)
}
}
// Before and Afters
// BeforeStart run funcs before service starts.
func BeforeStart(fn func() error) Option {
return func(o *Options) {
o.BeforeStart = append(o.BeforeStart, fn)
}
}
// BeforeStop run funcs before service stops.
func BeforeStop(fn func() error) Option {
return func(o *Options) {
o.BeforeStop = append(o.BeforeStop, fn)
}
}
// AfterStart run funcs after service starts.
func AfterStart(fn func() error) Option {
return func(o *Options) {
o.AfterStart = append(o.AfterStart, fn)
}
}
// AfterStop run funcs after service stops.
func AfterStop(fn func() error) Option {
return func(o *Options) {
o.AfterStop = append(o.AfterStop, fn)
}
}
// Logger sets the logger for the service.
func Logger(l logger.Logger) Option {
return func(o *Options) {
o.Logger = l
}
}
+90
View File
@@ -0,0 +1,90 @@
// Package profileconfig provides grouped plugin profiles for go-micro
package profile
import (
"os"
"strings"
natslib "github.com/nats-io/nats.go"
"go-micro.dev/v6/broker"
"go-micro.dev/v6/broker/nats"
"go-micro.dev/v6/events"
nevents "go-micro.dev/v6/events/natsjs"
"go-micro.dev/v6/registry"
nreg "go-micro.dev/v6/registry/nats"
"go-micro.dev/v6/store"
nstore "go-micro.dev/v6/store/nats-js-kv"
"go-micro.dev/v6/transport"
ntx "go-micro.dev/v6/transport/nats"
)
type Profile struct {
Registry registry.Registry
Broker broker.Broker
Store store.Store
Transport transport.Transport
Stream events.Stream
}
// LocalProfile returns a profile with local mDNS as the registry, HTTP as the broker, file as the store, and HTTP as the transport
// It is used for local development and testing
func LocalProfile() (Profile, error) {
stream, err := events.NewStream()
return Profile{
Registry: registry.NewMDNSRegistry(),
Broker: broker.NewHttpBroker(),
Store: store.NewFileStore(),
Transport: transport.NewHTTPTransport(),
Stream: stream,
}, err
}
// NatsProfile returns a profile with NATS as the registry, broker, store, and transport
// It uses the environment variable MICR_NATS_ADDRESS to set the NATS server address
// If the variable is not set, it defaults to nats://0.0.0.0:4222 which will connect to a local NATS server
func NatsProfile() (Profile, error) {
addr := os.Getenv("MICRO_NATS_ADDRESS")
if addr == "" {
addr = "nats://0.0.0.0:4222"
}
// Split the address by comma, trim whitespace, and convert to a slice of strings
addrs := splitNatsAdressList(addr)
reg := nreg.NewNatsRegistry(registry.Addrs(addrs...))
nopts := natslib.GetDefaultOptions()
nopts.Servers = addrs
brok := nats.NewNatsBroker(broker.Addrs(addrs...), nats.Options(nopts))
st := nstore.NewStore(nstore.NatsOptions(natslib.Options{Servers: addrs}))
tx := ntx.NewTransport(ntx.Options(natslib.Options{Servers: addrs}))
stream, err := nevents.NewStream(
nevents.Address(addr),
)
registry.DefaultRegistry = reg
broker.DefaultBroker = brok
store.DefaultStore = st
transport.DefaultTransport = tx
return Profile{
Registry: reg,
Broker: brok,
Store: st,
Transport: tx,
Stream: stream,
}, err
}
func splitNatsAdressList(addr string) []string {
// Split the address by comma
addrs := strings.Split(addr, ",")
// Trim any whitespace from each address
for i, a := range addrs {
addrs[i] = strings.TrimSpace(a)
}
return addrs
}
// Add more profiles as needed, e.g. grpc
+223
View File
@@ -0,0 +1,223 @@
package service
import (
"os"
"os/signal"
rtime "runtime"
"sync"
"go-micro.dev/v6/client"
"go-micro.dev/v6/cmd"
signalutil "go-micro.dev/v6/internal/util/signal"
log "go-micro.dev/v6/logger"
"go-micro.dev/v6/model"
"go-micro.dev/v6/server"
"go-micro.dev/v6/store"
)
// Service is the interface for a go-micro service.
type Service interface {
// Name returns the service name.
Name() string
// Init initializes options. Parses command line flags on first call.
Init(...Option)
// Options returns the current options.
Options() Options
// Handle registers a handler with optional server.HandlerOption args.
Handle(v interface{}, opts ...server.HandlerOption) error
// Client returns the RPC client.
Client() client.Client
// Server returns the RPC server.
Server() server.Server
// Model returns the data model backend.
Model() model.Model
// Start the service (non-blocking).
Start() error
// Stop the service.
Stop() error
// Run starts the service, blocks on signal/context, then stops.
Run() error
// String returns the implementation name.
String() string
}
type serviceImpl struct {
opts Options
once sync.Once
}
// New creates a new service with the given options.
func New(opts ...Option) Service {
return &serviceImpl{
opts: newOptions(opts...),
}
}
func (s *serviceImpl) Name() string {
return s.opts.Server.Options().Name
}
// Init initializes options. Additionally it calls cmd.Init
// which parses command line flags. cmd.Init is only called
// on first Init.
func (s *serviceImpl) Init(opts ...Option) {
// process options
for _, o := range opts {
o(&s.opts)
}
s.once.Do(func() {
// set cmd name
if len(s.opts.Cmd.App().Name) == 0 {
s.opts.Cmd.App().Name = s.Server().Options().Name
}
// Initialize the command flags, overriding new service
if err := s.opts.Cmd.Init(
cmd.Auth(&s.opts.Auth),
cmd.Broker(&s.opts.Broker),
cmd.Registry(&s.opts.Registry),
cmd.Transport(&s.opts.Transport),
cmd.Client(&s.opts.Client),
cmd.Config(&s.opts.Config),
cmd.Server(&s.opts.Server),
cmd.Store(&s.opts.Store),
cmd.Profile(&s.opts.Profile),
); err != nil {
s.opts.Logger.Log(log.FatalLevel, err)
}
// Scope the service's store to its own table (database "service",
// table = service name), consistent with how agents ("agent/{name}")
// and flows ("flow/{name}") scope their state. This replaces the
// older Init(store.Table(name)) global mutation with a composable
// scoped handle: each service gets an isolated handle that works
// even when several run in one process. When the service uses the
// package default store, bridge it to the same scope so handlers
// that reach for store.DefaultStore stay isolated too.
name := s.opts.Cmd.App().Name
wasDefault := s.opts.Store == store.DefaultStore
s.opts.Store = store.Scope(s.opts.Store, "service", name)
if wasDefault {
store.DefaultStore = s.opts.Store
}
})
}
func (s *serviceImpl) Options() Options {
return s.opts
}
func (s *serviceImpl) Client() client.Client {
return s.opts.Client
}
func (s *serviceImpl) Server() server.Server {
return s.opts.Server
}
func (s *serviceImpl) Model() model.Model {
return s.opts.Model
}
func (s *serviceImpl) String() string {
return "micro"
}
func (s *serviceImpl) Start() error {
for _, fn := range s.opts.BeforeStart {
if err := fn(); err != nil {
return err
}
}
if err := s.opts.Server.Start(); err != nil {
return err
}
for _, fn := range s.opts.AfterStart {
if err := fn(); err != nil {
return err
}
}
return nil
}
func (s *serviceImpl) Stop() error {
var gerr error
for _, fn := range s.opts.BeforeStop {
if err := fn(); err != nil {
gerr = err
}
}
if err := s.opts.Server.Stop(); err != nil {
return err
}
for _, fn := range s.opts.AfterStop {
if err := fn(); err != nil {
gerr = err
}
}
return gerr
}
func (s *serviceImpl) Handle(v interface{}, opts ...server.HandlerOption) error {
return s.opts.Server.Handle(
s.opts.Server.NewHandler(v, opts...),
)
}
func (s *serviceImpl) Run() (err error) {
logger := s.opts.Logger
// exit when help flag is provided
for _, v := range os.Args[1:] {
if v == "-h" || v == "--help" {
os.Exit(0)
}
}
// start the profiler
if s.opts.Profile != nil {
// to view mutex contention
rtime.SetMutexProfileFraction(5)
// to view blocking profile
rtime.SetBlockProfileRate(1)
if err = s.opts.Profile.Start(); err != nil {
return err
}
defer func() {
if nerr := s.opts.Profile.Stop(); nerr != nil {
logger.Log(log.ErrorLevel, nerr)
}
}()
}
logger.Logf(log.InfoLevel, "Starting [service] %s", s.Name())
if err = s.Start(); err != nil {
return err
}
ch := make(chan os.Signal, 1)
if s.opts.Signal {
signal.Notify(ch, signalutil.Shutdown()...)
}
select {
// wait on kill signal
case <-ch:
// wait on context cancel
case <-s.opts.Context.Done():
}
return s.Stop()
}