This commit is contained in:
matst80
2024-11-08 21:58:28 +01:00
parent dfcdf0939f
commit 65a969443a
13 changed files with 437 additions and 173 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) Process(id CartId, messages ...Message) (interface{}, error) {
var err error
grain, ok := p.grains[id]
if !ok {
if len(p.grains) >= p.PoolSize {
@@ -74,13 +77,19 @@ 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
if err == nil && grain != nil {
for _, message := range messages {
_, err = grain.HandleMessage(&message, false)
}
}
return grain, err
}
func (p *GrainLocalPool) Get(id string) (Grain, error) {
func (p *GrainLocalPool) Get(id CartId) (Grain, error) {
grain, ok := p.grains[id]
if !ok {
return nil, fmt.Errorf("grain not found")