package protoc_gen_kit import ( "context" "git.diulo.com/mogfee/protoc-gen-kit/log" "github.com/google/uuid" "golang.org/x/sync/errgroup" "os" "sync" "syscall" "time" ) type AppInfo interface { ID() string Name() string Version() string Metadata() map[string]string Endpoint() []string } type App struct { opts options ctx context.Context cancel func() mu sync.Mutex instance *registry.ServiceInstance } func New(opts ...Option) *App { o := options{ ctx: context.Background(), sigs: []os.Signal{syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT}, registrarTimeout: 10 * time.Second, stopTimeout: 10 * time.Second, } if id, err := uuid.NewUUID(); err == nil { o.id = id.String() } for _, opt := range opts { opt(&o) } if o.logger != nil { log.SetLogger(o.logger) } ctx, cancel := context.WithCancel(o.ctx) return &App{ opts: o, ctx: ctx, cancel: cancel, } } // ID returns app instance id. func (a *App) ID() string { return a.opts.id } // Name returns service name. func (a *App) Name() string { return a.opts.name } // Version returns app version. func (a *App) Version() string { return a.opts.version } // Metadata returns service metadata. func (a *App) Metadata() map[string]string { return a.opts.metadata } // Endpoint returns endpoints. func (a *App) Endpoint() []string { if a.instance != nil { return a.instance.Endpoints } return nil } func (a *App) Run() error { instance, err := a.buildInstance() if err != nil { return err } a.mu.Lock() a.instance = instance a.mu.Unlock() sctx := NewContext(a.ctx, a) eg, ctx := errgroup.WithContext(sctx) wg := sync.WaitGroup{} for _, fn := range a.opts.beforeStart { if err = fn(sctx); err != nil { return err } } for _, srv := range a.opts.servers { srv := srv eg.Go(func() error { <-ctx.Done() stopCtx, cancel := context.WithTimeout(NewContext(a.opts.ctx, a)) defer cancel() return srv.Stop(stopCtx) }) wg.Add(1) eg.Go(func() error { wg.Done() return srv.Start(sctx) }) } wg.Wait() }