cleanup
This commit is contained in:
@@ -1,19 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GrainPool interface {
|
||||
Process(id CartId, messages ...Message) (interface{}, error)
|
||||
Get(id CartId) (Grain, error)
|
||||
Process(id CartId, messages ...Message) ([]byte, error)
|
||||
Get(id CartId) ([]byte, error)
|
||||
}
|
||||
|
||||
type Ttl struct {
|
||||
Expires time.Time
|
||||
Item *CartGrain
|
||||
Grain *CartGrain
|
||||
}
|
||||
|
||||
type GrainLocalPool struct {
|
||||
@@ -46,13 +47,13 @@ func (p *GrainLocalPool) Purge() {
|
||||
for i := 0; i < len(p.expiry); i++ {
|
||||
item := p.expiry[i]
|
||||
if item.Expires.Before(time.Now()) {
|
||||
if item.Item.GetLastChange() > keepChanged {
|
||||
log.Printf("Changed item %s expired, keeping", item.Item.GetId())
|
||||
if item.Grain.GetLastChange() > keepChanged {
|
||||
log.Printf("Expired item %s changed, keeping", item.Grain.GetId())
|
||||
p.expiry = append(p.expiry[:i], p.expiry[i+1:]...)
|
||||
p.expiry = append(p.expiry, item)
|
||||
} else {
|
||||
log.Printf("Item %s expired", item.Item.GetId())
|
||||
delete(p.grains, item.Item.GetId())
|
||||
log.Printf("Item %s expired", item.Grain.GetId())
|
||||
delete(p.grains, item.Grain.GetId())
|
||||
p.expiry = append(p.expiry[:i], p.expiry[i+1:]...)
|
||||
}
|
||||
} else {
|
||||
@@ -71,7 +72,7 @@ func (p *GrainLocalPool) GetGrain(id CartId) (*CartGrain, error) {
|
||||
if !ok {
|
||||
if len(p.grains) >= p.PoolSize {
|
||||
if p.expiry[0].Expires.Before(time.Now()) {
|
||||
delete(p.grains, p.expiry[0].Item.GetId())
|
||||
delete(p.grains, p.expiry[0].Grain.GetId())
|
||||
p.expiry = p.expiry[1:]
|
||||
} else {
|
||||
return nil, fmt.Errorf("pool is full")
|
||||
@@ -84,16 +85,23 @@ func (p *GrainLocalPool) GetGrain(id CartId) (*CartGrain, error) {
|
||||
return grain, err
|
||||
}
|
||||
|
||||
func (p *GrainLocalPool) Process(id CartId, messages ...Message) (interface{}, error) {
|
||||
func (p *GrainLocalPool) Process(id CartId, messages ...Message) ([]byte, error) {
|
||||
grain, err := p.GetGrain(id)
|
||||
if err == nil && grain != nil {
|
||||
for _, message := range messages {
|
||||
_, err = grain.HandleMessage(&message, false)
|
||||
}
|
||||
}
|
||||
return grain, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(grain)
|
||||
}
|
||||
|
||||
func (p *GrainLocalPool) Get(id CartId) (Grain, error) {
|
||||
return p.GetGrain(id)
|
||||
func (p *GrainLocalPool) Get(id CartId) ([]byte, error) {
|
||||
grain, err := p.GetGrain(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(grain)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user