122 lines
2.2 KiB
Go
122 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
)
|
|
|
|
type RemoteGrainPool struct {
|
|
mu sync.RWMutex
|
|
Host string
|
|
grains map[CartId]*RemoteGrain
|
|
}
|
|
|
|
func (id CartId) String() string {
|
|
return strings.Trim(string(id[:]), "\x00")
|
|
}
|
|
|
|
func ToCartId(id string) CartId {
|
|
var result [16]byte
|
|
copy(result[:], []byte(id))
|
|
return result
|
|
}
|
|
|
|
type RemoteGrain struct {
|
|
*CartClient
|
|
Id CartId
|
|
Address string
|
|
}
|
|
|
|
func NewRemoteGrain(id CartId, address string) *RemoteGrain {
|
|
client, err := CartDial(address)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
return &RemoteGrain{
|
|
Id: id,
|
|
Address: address,
|
|
CartClient: client,
|
|
}
|
|
}
|
|
|
|
func (g *RemoteGrain) HandleMessage(message *Message, isReplay bool) ([]byte, error) {
|
|
|
|
data, err := GetData(message.Write)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
reply, err := g.Call(RemoteHandleMessage, g.Id, RemoteHandleMessageReply, data)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return reply, err
|
|
}
|
|
|
|
func (g *RemoteGrain) GetId() CartId {
|
|
return g.Id
|
|
}
|
|
|
|
func (g *RemoteGrain) GetCurrentState() ([]byte, error) {
|
|
return g.Call(RemoteGetState, g.Id, RemoteGetStateReply, nil)
|
|
}
|
|
|
|
func NewRemoteGrainPool(addr string) *RemoteGrainPool {
|
|
return &RemoteGrainPool{
|
|
Host: addr,
|
|
grains: make(map[CartId]*RemoteGrain),
|
|
}
|
|
}
|
|
|
|
func (p *RemoteGrainPool) findRemoteGrain(id CartId) *RemoteGrain {
|
|
p.mu.RLock()
|
|
grain, ok := p.grains[id]
|
|
p.mu.RUnlock()
|
|
if !ok || grain == nil {
|
|
return nil
|
|
}
|
|
return grain
|
|
}
|
|
|
|
func (p *RemoteGrainPool) findOrCreateGrain(id CartId) *RemoteGrain {
|
|
grain := p.findRemoteGrain(id)
|
|
if grain == nil {
|
|
grain = NewRemoteGrain(id, p.Host)
|
|
|
|
p.mu.Lock()
|
|
p.grains[id] = grain
|
|
p.mu.Unlock()
|
|
}
|
|
return grain
|
|
}
|
|
|
|
func (p *RemoteGrainPool) Delete(id CartId) {
|
|
p.mu.Lock()
|
|
delete(p.grains, id)
|
|
p.mu.Unlock()
|
|
}
|
|
|
|
func (p *RemoteGrainPool) Process(id CartId, messages ...Message) ([]byte, error) {
|
|
var result []byte
|
|
var err error
|
|
grain := p.findOrCreateGrain(id)
|
|
if grain == nil {
|
|
return nil, fmt.Errorf("grain not found")
|
|
}
|
|
for _, message := range messages {
|
|
result, err = grain.HandleMessage(&message, false)
|
|
}
|
|
return result, err
|
|
}
|
|
|
|
func (p *RemoteGrainPool) Get(id CartId) ([]byte, error) {
|
|
grain := p.findOrCreateGrain(id)
|
|
if grain == nil {
|
|
return nil, fmt.Errorf("grain not found")
|
|
}
|
|
return grain.GetCurrentState()
|
|
}
|