go-scopes/scopes.go

155 lines
2.6 KiB
Go

// Package `scopes` provides a set of core types (mostly interfaces
// and function declarations) and some basic functions.
package scopes
import (
stdlib_context "context"
"fmt"
"sync"
)
// elementary types
type Ident uint
type Data interface{}
type Map map[string]Data
type StrMap map[string]string
type Slice []Data
type StrSlice []string
// services - context
type Services map[string]Context
type ContextState interface{}
type Context interface {
stdlib_context.Context
Addressable
Config() Config
Name() string
Parent() Context
Services() Services
ChildContext(Config) Context
State() ContextState
WithState(ContextState) Context
Mailbox() chan Message
WaitGroup() *sync.WaitGroup
Stop()
Send(Message)
}
// payload, message, address types
type Payload interface {
fmt.Stringer
Data() Data
FromJson(string) Payload
}
type MsgHead interface {
fmt.Stringer
Slice() []string
Domain() string
Action() string
Class() string
Item() string
}
type Message interface {
MsgHead
Head() MsgHead
Sender() Addressable
Payload() Payload
WithSender(Addressable) Message
WithPayload(Payload) Message
}
type Addressable interface {
Address() Address
Cell() Context
}
type Address interface {
fmt.Stringer
Addressable
Url() string
Service() string
Interaction() (string, string)
SetUrl(string)
SetInteraction(string, string)
}
// action
type Action interface {
Context() Context
Spec() ActionSpec
Message() Message
Handle() bool
}
type ActionSpec interface {
Handler() ActionHandler
Receivers() []Addressable
AddReceiver(Addressable) ActionSpec
RemoveReceiver(Addressable)
}
// procedures and handlers
type Proc = func(Context)
type Step = func(Context) bool
type MessageHandler = func(Context, Message) bool
type ActionHandler = func(Action) bool
// standard configuration interfaces
type Config interface {
Name() string
SetName(string)
Starter() Proc
Listener() Proc
Step() Step
MessageHandler() MessageHandler
DoneHandler() Step
Actions() []ActionConfig
AddAction(string, ...ActionSpec)
Children() []Config
Add(...Config)
}
type ActionConfig interface {
Pattern() Pattern
Specs() []ActionSpec
}
type Pattern interface {
fmt.Stringer
Slice() []string
}
// core library functions
func RunCtx(ctx Context, fct Proc) {
ctx.WaitGroup().Add(1)
go func() {
defer ctx.WaitGroup().Done()
fct(ctx)
}()
}
func HandleMsg(ctx Context, msg Message) bool {
return ctx.Config().MessageHandler()(ctx, msg)
}
func GetState[St ContextState](ctx Context) St {
return ctx.State().(St)
}
func GetCfg[C Config](ctx Context) C {
return ctx.Config().(C)
}