refactor/serializing (#1)

Co-authored-by: matst80 <mats.tornberg@gmail.com>
Reviewed-on: https://git.tornberg.me/mats/go-cart-actor/pulls/1
This commit was merged in pull request #1.
This commit is contained in:
2024-11-08 23:02:09 +01:00
parent 4cc41bcec6
commit 1b75f81119
19 changed files with 576 additions and 409 deletions

View File

@@ -7,25 +7,27 @@ import (
)
type GrainPool interface {
GetOrSpawn(id string) (Grain, error)
Get(id string) (Grain, error)
Process(id CartId, messages ...Message) (interface{}, error)
Get(id CartId) (Grain, error)
}
type Ttl struct {
Expires time.Time
Item Grain
Item *CartGrain
}
type GrainLocalPool struct {
grains map[string]Grain
grains map[CartId]*CartGrain
expiry []Ttl
spawn func(id CartId) (*CartGrain, error)
Ttl time.Duration
PoolSize int
}
func NewGrainLocalPool(size int, ttl time.Duration) *GrainLocalPool {
func NewGrainLocalPool(size int, ttl time.Duration, spawn func(id CartId) (*CartGrain, error)) *GrainLocalPool {
ret := &GrainLocalPool{
grains: make(map[string]Grain),
spawn: spawn,
grains: make(map[CartId]*CartGrain),
expiry: make([]Ttl, 0),
Ttl: ttl,
PoolSize: size,
@@ -59,11 +61,12 @@ func (p *GrainLocalPool) Purge() {
}
}
func (p *GrainLocalPool) GetGrains() map[string]Grain {
func (p *GrainLocalPool) GetGrains() map[CartId]*CartGrain {
return p.grains
}
func (p *GrainLocalPool) GetOrSpawn(id string, generator func(id string) Grain) (Grain, error) {
func (p *GrainLocalPool) GetGrain(id CartId) (*CartGrain, error) {
var err error
grain, ok := p.grains[id]
if !ok {
if len(p.grains) >= p.PoolSize {
@@ -74,16 +77,23 @@ func (p *GrainLocalPool) GetOrSpawn(id string, generator func(id string) Grain)
return nil, fmt.Errorf("pool is full")
}
}
grain = generator(id)
grain, err = p.spawn(id)
p.grains[id] = grain
}
return grain, nil
return grain, err
}
func (p *GrainLocalPool) Get(id string) (Grain, error) {
grain, ok := p.grains[id]
if !ok {
return nil, fmt.Errorf("grain not found")
func (p *GrainLocalPool) Process(id CartId, messages ...Message) (interface{}, error) {
grain, err := p.GetGrain(id)
if err == nil && grain != nil {
for _, message := range messages {
_, err = grain.HandleMessage(&message, false)
}
}
return grain, nil
return grain, err
}
func (p *GrainLocalPool) Get(id CartId) (Grain, error) {
return p.GetGrain(id)
}