From d9e109e3a5d971413671fa5b285027a528b38990 Mon Sep 17 00:00:00 2001 From: Helmut Merz Date: Sat, 3 Jun 2023 17:21:34 +0200 Subject: [PATCH] implement Context interface from standard library --- common/common.go | 43 +++++++++++++++++++++++++++++++++++++++---- scopes.go | 2 +- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/common/common.go b/common/common.go index 60f5d99..de0ac12 100644 --- a/common/common.go +++ b/common/common.go @@ -1,6 +1,10 @@ package common -import "sync" +import ( + stdlib_context "context" + "sync" + "time" +) type Config interface { Name() string @@ -16,6 +20,7 @@ type Services map[string]Context type ContextState interface{} type Context interface { + stdlib_context.Context Config() Config Parent() Context Services() Services @@ -23,8 +28,8 @@ type Context interface { State() ContextState WithState(ContextState) Context Mailbox() chan Message - Done() chan struct{} WaitGroup() *sync.WaitGroup + Stop() } type FctCtx = func(Context) @@ -87,10 +92,14 @@ func (ctx *context) WaitGroup() *sync.WaitGroup { return ctx.parent.WaitGroup() } -func (ctx *context) Done() chan struct{} { +func (ctx *context) Done() <-chan struct{} { return ctx.parent.Done() } +func (ctx *context) Stop() { + // ctx.Warn("Only application-level service can be stopped +} + func makeCtx(cfg Config, parent Context) *context { return &context{ cfg: cfg, @@ -128,10 +137,14 @@ func (ctx *appContext) WaitGroup() *sync.WaitGroup { return ctx.waitgroup } -func (ctx *appContext) Done() chan struct{} { +func (ctx *appContext) Done() <-chan struct{} { return ctx.doneCh } +func (ctx *appContext) Stop() { + close(ctx.doneCh) +} + func AppContext(cfg Config) Context { ctx := &appContext{ context: makeCtx(cfg, nil), @@ -142,3 +155,25 @@ func AppContext(cfg Config) Context { ctx.services[cfg.Name()] = ctx return ctx } + +// implement interface context.Context from standard library + +func (ctx *context) Deadline() (deadline time.Time, ok bool) { + return time.Time{}, false +} + +func (ctx *context) Err() error { + select { + case _, ok := <-ctx.Done(): + if !ok { + return stdlib_context.Canceled + } + default: + return nil + } + return nil +} + +func (ctx *context) Value(key interface{}) interface{} { + return nil +} diff --git a/scopes.go b/scopes.go index 85f1530..5923b9e 100644 --- a/scopes.go +++ b/scopes.go @@ -21,7 +21,7 @@ func Start(ctx common.Context) { } func start(ctx common.Context) { - defer close(ctx.Done()) + defer ctx.Stop() for _, cfg := range ctx.Config().Children() { cctx := ctx.ChildContext(cfg) cfg.Starter()(cctx)