whispervis/simulation.go

85 lines
2.4 KiB
Go
Raw Normal View History

2018-10-19 16:01:49 +02:00
package main
import (
"bytes"
"encoding/json"
"fmt"
2018-10-24 17:20:19 +02:00
"io"
2018-10-19 16:01:49 +02:00
"net/http"
"github.com/divan/graphx/formats"
"github.com/status-im/simulation/propagation"
"github.com/status-im/simulation/stats"
)
// Simulation represents the state of last simulation.
type Simulation struct {
plog *propagation.Log
stats *stats.Stats
}
2018-10-24 17:20:19 +02:00
// SimulationRequests defines a POST request payload for simulation backend.
type SimulationRequest struct {
SenderIdx int `json:"senderIdx"` // index of the sender node (index of data.Nodes, in fact)
TTL int `json:"ttl"` // ttl in seconds
MsgSize int `json:"msg_size"` // msg size in bytes
Network json.RawMessage `json:"network"` // current network graph
}
2018-10-19 16:01:49 +02:00
// runSimulation starts whisper message propagation simulation,
// remotely talking to simulation backend with given address.
2018-10-24 19:37:31 +02:00
func (p *Page) runSimulation(address string, ttl int) (*Simulation, error) {
buf, err := p.newPOSTSimulationRequest(ttl)
2018-10-24 17:20:19 +02:00
if err != nil {
return nil, fmt.Errorf("Internal error. See console output.")
}
2018-10-19 22:10:56 +02:00
resp, err := http.Post(address, "application/json", buf)
2018-10-19 16:01:49 +02:00
if err != nil {
fmt.Println("[ERROR] POST request to simulation backend:", err)
return nil, fmt.Errorf("Backend error. Did you run backend?")
2018-10-19 16:01:49 +02:00
}
var plog propagation.Log
err = json.NewDecoder(resp.Body).Decode(&plog)
if err != nil {
fmt.Println("[ERROR] decoding response from simulation backend:", err)
return nil, fmt.Errorf("decoding JSON response error: %v", err)
}
return &Simulation{
plog: &plog,
}, nil
}
2018-10-24 17:20:19 +02:00
// newPOSTSimulationRequest generates SimulationReqeust and
// prepares it as io.Reader for usage with http.Post.
2018-10-24 19:37:31 +02:00
func (p *Page) newPOSTSimulationRequest(ttl int) (io.Reader, error) {
2018-10-24 17:20:19 +02:00
req := SimulationRequest{
SenderIdx: 0,
2018-10-24 19:37:31 +02:00
TTL: ttl,
2018-10-24 17:20:19 +02:00
MsgSize: 400,
Network: p.currentNetworkJSON(),
}
payload, err := json.Marshal(req)
if err != nil {
fmt.Println("[ERROR] Can't marshal SimulationRequest", err)
return nil, err
}
buf := bytes.NewBuffer(payload)
return buf, nil
}
2018-10-19 16:01:49 +02:00
// currentNetworkJSON returns JSON encoded description of the current graph/network.
func (p *Page) currentNetworkJSON() []byte {
2018-10-23 06:42:56 +02:00
net := p.network.Current().Data
2018-10-19 16:01:49 +02:00
var buf bytes.Buffer
err := formats.NewD3JSON(&buf, true).ExportGraph(net)
if err != nil {
fmt.Println("[ERROR] Can't export graph:", err)
return nil
}
return buf.Bytes()
}