97 lines
2.1 KiB
Go
97 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promauto"
|
|
)
|
|
|
|
func (id CartId) String() string {
|
|
return strings.Trim(string(id[:]), "\x00")
|
|
}
|
|
|
|
type CartIdPayload struct {
|
|
Id CartId
|
|
Data []byte
|
|
}
|
|
|
|
func MakeCartInnerFrame(id CartId, payload []byte) []byte {
|
|
return append(id[:], payload...)
|
|
}
|
|
|
|
func GetCartFrame(data []byte) (*CartIdPayload, error) {
|
|
if len(data) < 16 {
|
|
return nil, fmt.Errorf("data too short")
|
|
}
|
|
return &CartIdPayload{
|
|
Id: CartId(data[:16]),
|
|
Data: data[16:],
|
|
}, nil
|
|
}
|
|
|
|
func ToCartId(id string) CartId {
|
|
var result [16]byte
|
|
copy(result[:], []byte(id))
|
|
return result
|
|
}
|
|
|
|
type RemoteGrain struct {
|
|
*Connection
|
|
Id CartId
|
|
Host string
|
|
}
|
|
|
|
func NewRemoteGrain(id CartId, host string) (*RemoteGrain, error) {
|
|
return &RemoteGrain{
|
|
Id: id,
|
|
Host: host,
|
|
Connection: NewConnection(fmt.Sprintf("%s:1337", host)),
|
|
}, nil
|
|
}
|
|
|
|
var (
|
|
remoteCartLatency = promauto.NewCounter(prometheus.CounterOpts{
|
|
Name: "cart_remote_grain_calls_total_latency",
|
|
Help: "The total latency of remote grains",
|
|
})
|
|
remoteCartCallsTotal = promauto.NewCounter(prometheus.CounterOpts{
|
|
Name: "cart_remote_grain_calls_total",
|
|
Help: "The total number of calls to remote grains",
|
|
})
|
|
)
|
|
|
|
// var start time.Time
|
|
|
|
// func MeasureLatency(fn func() (*CallResult, error)) (*CallResult, error) {
|
|
// start = time.Now()
|
|
// data, err := fn()
|
|
// if err != nil {
|
|
// return data, err
|
|
// }
|
|
// elapsed := time.Since(start).Milliseconds()
|
|
// go func() {
|
|
// remoteCartLatency.Add(float64(elapsed))
|
|
// remoteCartCallsTotal.Inc()
|
|
// }()
|
|
// return data, nil
|
|
// }
|
|
|
|
func (g *RemoteGrain) HandleMessage(message *Message, isReplay bool) (*FrameWithPayload, error) {
|
|
|
|
data, err := GetData(message.Write)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return g.Call(RemoteHandleMutation, MakeCartInnerFrame(g.Id, data))
|
|
}
|
|
|
|
func (g *RemoteGrain) GetId() CartId {
|
|
return g.Id
|
|
}
|
|
|
|
func (g *RemoteGrain) GetCurrentState() (*FrameWithPayload, error) {
|
|
return g.Call(RemoteGetState, MakeCartInnerFrame(g.Id, nil))
|
|
}
|