dashboard: footer, deep state update

This commit is contained in:
Kurkó Mihály 2018-01-08 14:45:19 +02:00
parent 9d06026c19
commit fe7a4cc8fe
14 changed files with 40219 additions and 5908 deletions

View file

@ -20,7 +20,7 @@ Normally the dashboard assets are bundled into Geth via `go-bindata` to avoid ex
```
$ (cd dashboard/assets && ./node_modules/.bin/webpack --watch)
$ geth --dashboard --dashboard.assets=dashboard/assets/public --vmodule=dashboard=5
$ geth --dashboard --dashboard.assets=dashboard/assets --vmodule=dashboard=5
```
To bundle up the final UI into Geth, run `go generate`:

File diff suppressed because one or more lines are too long

38145
dashboard/assets/bundle.js Normal file

File diff suppressed because one or more lines are too long

View file

@ -62,32 +62,4 @@ export type MenuProp = {|...ProvidedMenuProp, id: string|};
// This way the mistyping is prevented.
export const MENU: Map<string, {...MenuProp}> = new Map(menuSkeletons.map(({id, menu}) => ([id, {id, ...menu}])));
type ProvidedSampleProp = {|limit: number|};
const sampleSkeletons: Array<{|id: string, sample: ProvidedSampleProp|}> = [
{
id: 'memory',
sample: {
limit: 200,
},
}, {
id: 'traffic',
sample: {
limit: 200,
},
}, {
id: 'logs',
sample: {
limit: 200,
},
},
];
export type SampleProp = {|...ProvidedSampleProp, id: string|};
export const SAMPLE: Map<string, {...SampleProp}> = new Map(sampleSkeletons.map(({id, sample}) => ([id, {id, ...sample}])));
export const DURATION = 200;
export const LENS: Map<string, string> = new Map([
'content',
...menuSkeletons.map(({id}) => id),
...sampleSkeletons.map(({id}) => id),
].map(lens => [lens, lens]));

View file

@ -19,36 +19,109 @@
import React, {Component} from 'react';
import withStyles from 'material-ui/styles/withStyles';
import {lensPath, view, set} from 'ramda';
import Header from './Header';
import Body from './Body';
import {MENU, SAMPLE} from './Common';
import type {Message, HomeMessage, LogsMessage, Chart} from '../types/message';
import Footer from './Footer';
import {MENU} from './Common';
import type {Content} from '../types/content';
// appender appends an array (A) to the end of another array (B) in the state.
// lens is the path of B in the state, samples is A, and limit is the maximum size of the changed array.
//
// appender retrieves a function, which overrides the state's value at lens, and returns with the overridden state.
const appender = (lens, samples, limit) => (state) => {
const newSamples = [
...view(lens, state), // retrieves a specific value of the state at the given path (lens).
...samples,
];
// set is a function of ramda.js, which needs the path, the new value, the original state, and retrieves
// the altered state.
return set(
lens,
newSamples.slice(newSamples.length > limit ? newSamples.length - limit : 0),
state
);
// deepCopy retrieves a copy of the given object, copying recursively in all depth.
// It is used at the state update, because React doesn't handle the object nesting well.
// References are prohibited, since the state needs to be immutable.
// NOTE: maybe there is better solution.
const deepCopy = (prev: mixed) => {
const copied = Array.isArray(prev) ? [] : {};
Object.keys(prev).forEach((key) => {
const c: mixed = prev[key]
copied[key] = typeof c === 'object' ? deepCopy(c) : c;
});
return copied;
};
// deepUpdate updates an object corresponding to the given update data, which has
// the shape of the same structure as the original object. handler also has the same
// structure, except that it contains functions where the original data needs to be
// updated. These functions are used to handle the update.
//
// Since the messages have the same shape as the state content, this approach allows
// the generalization of the message handling. The only necessary thing is to set a
// handler function for every path of the state in order to maximalize the flexibility
// of the update.
const deepUpdate = (prev: mixed, update: mixed, handler: mixed) => {
if (typeof update === 'undefined') {
return deepCopy(prev);
}
if (typeof handler === 'function') {
return handler(prev, update);
}
const updated = Array.isArray(prev) ? [] : {};
Object.keys(prev).forEach((key) => {
if (typeof update[key] === 'undefined') {
updated[key] = deepCopy(prev[key]);
} else {
updated[key] = deepUpdate(prev[key], update[key], handler[key]);
}
});
return updated;
};
// shouldUpdate retrieves the structure of a message. It is used to prevent unnecessary render
// method triggerings. In the affected component's shouldComponentUpdate method it can be checked
// whether the involved data was changed or not by checking the message structure.
const shouldUpdate = (msg: mixed, handler: mixed) => {
const su = {};
Object.keys(msg).forEach((key) => {
su[key] = typeof msg[key] === 'object' && typeof handler[key] !== 'function' ? shouldUpdate(msg[key], handler[key]) : true;
});
return su;
};
// appender is a state update generalization function, which appends the update data
// to the existing data. limit defines the maximum allowed size of the created array.
const appender = <T>(limit: number) => (prev: Array<T>, update: Array<T>) => [...prev, ...update].slice(-limit);
// appender200 is an appender function with limit 200.
const appender200 = appender(200);
// replacer is a state update generalization function, which replaces the original data.
const replacer = <T>(prev: T, update: T) => update;
// defaultContent is the initial value of the state content.
const defaultContent: Content = {
general: {
version: '-',
},
home: {
memory: [],
traffic: [],
},
chain: {},
txpool: {},
network: {},
system: {},
logs: {
log: [],
},
};
// handlers contains the state update generalization functions for each path of the state.
// TODO (kurkomisi): Define a tricky type which embraces the content and the handlers.
const handlers = {
general: {
version: replacer,
},
home: {
memory: appender200,
traffic: appender200,
},
chain: null,
txpool: null,
network: null,
system: null,
logs: {
log: appender200,
},
};
// Lenses for specific data fields in the state, used for a clearer deep update.
// NOTE: This solution will be changed very likely.
const memoryLens = lensPath(['content', 'home', 'memory']);
const trafficLens = lensPath(['content', 'home', 'traffic']);
const logLens = lensPath(['content', 'logs', 'log']);
// styles retrieves the styles for the Dashboard component.
const styles = theme => ({
dashboard: {
@ -67,8 +140,8 @@ export type Props = {
type State = {
active: string, // active menu
sideBar: boolean, // true if the sidebar is opened
content: $Shape<Content>, // the visualized data
shouldUpdate: Set<string> // labels for the components, which need to rerender based on the incoming message
content: Content, // the visualized data
shouldUpdate: Object // labels for the components, which need to rerender based on the incoming message
};
// Dashboard is the main component, which renders the whole page, makes connection with the server and
// listens for messages. When there is an incoming message, updates the page's content correspondingly.
@ -78,25 +151,22 @@ class Dashboard extends Component<Props, State> {
this.state = {
active: MENU.get('home').id,
sideBar: true,
content: {home: {memory: [], traffic: []}, logs: {log: []}},
shouldUpdate: new Set(),
content: defaultContent,
shouldUpdate: {},
};
}
// componentDidMount initiates the establishment of the first websocket connection after the component is rendered.
componentDidMount() {
this.reconnect();
this.connect();
}
// reconnect establishes a websocket connection with the server, listens for incoming messages
// connect establishes a websocket connection with the server, listens for incoming messages
// and tries to reconnect on connection loss.
reconnect = () => {
this.setState({
content: {home: {memory: [], traffic: []}, logs: {log: []}},
});
connect = () => {
const server = new WebSocket(`${((window.location.protocol === 'https:') ? 'wss://' : 'ws://') + window.location.host}/api`);
server.onmessage = (event) => {
const msg: Message = JSON.parse(event.data);
const msg: Content = JSON.parse(event.data);
if (!msg) {
return;
}
@ -107,56 +177,18 @@ class Dashboard extends Component<Props, State> {
};
};
// samples retrieves the raw data of a chart field from the incoming message.
samples = (chart: Chart) => {
let s = [];
if (chart.history) {
s = chart.history.map(({value}) => (value || 0)); // traffic comes without value at the beginning
}
if (chart.new) {
s = [...s, chart.new.value || 0];
}
return s;
// reconnect clears the state before the connection establishment.
reconnect = () => {
this.setState({content: defaultContent, shouldUpdate: {}});
this.connect();
};
// handleHome changes the home-menu related part of the state.
handleHome = (home: HomeMessage) => {
this.setState((prevState) => {
let newState = prevState;
newState.shouldUpdate = new Set();
if (home.memory) {
newState = appender(memoryLens, this.samples(home.memory), SAMPLE.get('memory').limit)(newState);
newState.shouldUpdate.add('memory');
}
if (home.traffic) {
newState = appender(trafficLens, this.samples(home.traffic), SAMPLE.get('traffic').limit)(newState);
newState.shouldUpdate.add('traffic');
}
return newState;
});
};
// handleLogs changes the logs-menu related part of the state.
handleLogs = (logs: LogsMessage) => {
this.setState((prevState) => {
let newState = prevState;
newState.shouldUpdate = new Set();
if (logs.log) {
newState = appender(logLens, [logs.log], SAMPLE.get('logs').limit)(newState);
newState.shouldUpdate.add('logs');
}
return newState;
});
};
// update analyzes the incoming message, and updates the charts' content correspondingly.
update = (msg: Message) => {
if (msg.home) {
this.handleHome(msg.home);
}
if (msg.logs) {
this.handleLogs(msg.logs);
}
// update updates the content corresponding to the incoming message.
update = (msg: $Shape<Content>) => {
this.setState(prevState => ({
content: deepUpdate(prevState.content, msg, handlers),
shouldUpdate: shouldUpdate(msg, handlers),
}));
};
// changeContent sets the active label, which is used at the content rendering.
@ -191,6 +223,13 @@ class Dashboard extends Component<Props, State> {
content={this.state.content}
shouldUpdate={this.state.shouldUpdate}
/>
<Footer
opened={this.state.sideBar}
openSideBar={this.openSideBar}
closeSideBar={this.closeSideBar}
general={this.state.content.general}
shouldUpdate={this.state.shouldUpdate}
/>
</div>
);
}

View file

@ -0,0 +1,106 @@
// @flow
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
import React, {Component} from 'react';
import withStyles from 'material-ui/styles/withStyles';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Transition from 'react-transition-group/Transition';
import IconButton from 'material-ui/IconButton';
import Typography from 'material-ui/Typography';
import ChevronLeftIcon from 'material-ui-icons/ChevronLeft';
import {DURATION} from './Common';
// arrowDefault is the default style of the arrow button.
const arrowDefault = {
transition: `transform ${DURATION}ms`,
};
// arrowTransition is the additional style of the arrow button corresponding to the transition's state.
const arrowTransition = {
entered: {transform: 'rotate(180deg)'},
};
// Styles for the Header component.
const styles = theme => ({
header: {
backgroundColor: theme.palette.background.appBar,
color: theme.palette.getContrastText(theme.palette.background.appBar),
zIndex: theme.zIndex.appBar,
},
toolbar: {
paddingLeft: theme.spacing.unit,
paddingRight: theme.spacing.unit,
},
mainText: {
paddingLeft: theme.spacing.unit,
},
});
export type Props = {
classes: Object,
opened: boolean,
openSideBar: () => {},
closeSideBar: () => {},
};
// TODO (kurkomisi): If the structure is appropriate, make an abstraction of the common parts with the Header.
// Footer renders the header of the dashboard.
class Footer extends Component<Props> {
shouldComponentUpdate(nextProps) {
return typeof nextProps.shouldUpdate.logs !== 'undefined';
}
// changeSideBar opens or closes the sidebar corresponding to the previous state.
changeSideBar = () => {
if (this.props.opened) {
this.props.closeSideBar();
} else {
this.props.openSideBar();
}
};
// arrowButton is connected to the sidebar; changes its state.
arrowButton = (transitionState: string) => (
<IconButton onClick={this.changeSideBar}>
<ChevronLeftIcon
style={{
...arrowDefault,
...arrowTransition[transitionState],
}}
/>
</IconButton>
);
render() {
const {classes, opened} = this.props; // The classes property is injected by withStyles().
return (
<AppBar position="static" className={classes.header}>
<Toolbar className={classes.toolbar}>
<Transition mountOnEnter in={opened} timeout={{enter: DURATION}}>
{this.arrowButton}
</Transition>
<Typography type="title" color="inherit" noWrap className={classes.mainText}>
{this.props.general.version}
</Typography>
</Toolbar>
</AppBar>
);
}
}
export default withStyles(styles)(Footer);

View file

@ -22,7 +22,7 @@ import withTheme from 'material-ui/styles/withTheme';
import {LineChart, AreaChart, Area, YAxis, CartesianGrid, Line} from 'recharts';
import ChartGrid from './ChartGrid';
import type {ChartEntry} from '../types/message';
import type {ChartEntry} from '../types/content';
export type Props = {
theme: Object,
@ -40,11 +40,16 @@ class Home extends Component<Props> {
}
shouldComponentUpdate(nextProps) {
return nextProps.shouldUpdate.has('memory') || nextProps.shouldUpdate.has('traffic');
return typeof nextProps.shouldUpdate.home !== 'undefined';
}
memoryColor: Object;
trafficColor: Object;
render() {
const {memory, traffic} = this.props;
let {memory, traffic} = this.props;
memory = memory.map(({value}) => (value || 0));
traffic = traffic.map(({value}) => (value || 0));
return (
<ChartGrid spacing={24}>

View file

@ -1,7 +1,7 @@
{
"dependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.3",
"babel-eslint": "^8.1.2",
"babel-loader": "^7.1.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
@ -12,16 +12,16 @@
"babel-preset-stage-0": "^6.24.1",
"babel-runtime": "^6.26.0",
"classnames": "^2.2.5",
"css-loader": "^0.28.7",
"eslint": "^4.13.1",
"css-loader": "^0.28.8",
"eslint": "^4.15.0",
"eslint-config-airbnb": "^16.1.0",
"eslint-loader": "^1.9.0",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.5.1",
"eslint-plugin-flowtype": "^2.40.1",
"eslint-plugin-flowtype": "^2.41.0",
"file-loader": "^1.1.6",
"flow-bin": "^0.61.0",
"flow-bin": "^0.63.1",
"flow-bin-loader": "^1.0.2",
"flow-typed": "^2.2.3",
"material-ui": "^1.0.0-beta.24",
@ -32,7 +32,7 @@
"react-dom": "^16.2.0",
"react-fa": "^5.0.0",
"react-transition-group": "^2.2.1",
"recharts": "^1.0.0-beta.6",
"recharts": "^1.0.0-beta.7",
"style-loader": "^0.19.1",
"url": "^0.11.0",
"url-loader": "^0.6.2",

View file

@ -16,9 +16,8 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
import type {ChartEntry} from './message';
export type Content = {
general: General,
home: Home,
chain: Chain,
txpool: TxPool,
@ -27,9 +26,20 @@ export type Content = {
logs: Logs,
};
export type General = {
version: string,
};
export type Home = {
memory: Array<ChartEntry>,
traffic: Array<ChartEntry>,
memory: ChartEntries,
traffic: ChartEntries,
};
export type ChartEntries = Array<ChartEntry>;
export type ChartEntry = {
time: Date,
value: number,
};
export type Chain = {

View file

@ -1,61 +0,0 @@
// @flow
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
export type Message = {
home?: HomeMessage,
chain?: ChainMessage,
txpool?: TxPoolMessage,
network?: NetworkMessage,
system?: SystemMessage,
logs?: LogsMessage,
};
export type HomeMessage = {
memory?: Chart,
traffic?: Chart,
};
export type Chart = {
history?: Array<ChartEntry>,
new?: ChartEntry,
};
export type ChartEntry = {
time: Date,
value: number,
};
export type ChainMessage = {
/* TODO (kurkomisi) */
};
export type TxPoolMessage = {
/* TODO (kurkomisi) */
};
export type NetworkMessage = {
/* TODO (kurkomisi) */
};
export type SystemMessage = {
/* TODO (kurkomisi) */
};
export type LogsMessage = {
log: string,
};

View file

@ -23,7 +23,7 @@ module.exports = {
},
entry: './index',
output: {
path: path.resolve(__dirname, 'public'),
path: path.resolve(__dirname, ''),
filename: 'bundle.js',
},
plugins: [

View file

@ -18,9 +18,15 @@ package dashboard
//go:generate npm --prefix ./assets install
//go:generate ./assets/node_modules/.bin/webpack --config ./assets/webpack.config.js --context ./assets
<<<<<<< HEAD
//go:generate go-bindata -nometadata -o assets.go -prefix assets -nocompress -pkg dashboard assets/public/...
//go:generate sh -c "sed 's#var _public#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
//go:generate gofmt -w -s assets.go
=======
//go:generate go-bindata -nometadata -o assets.go -prefix assets -nocompress -pkg dashboard assets/dashboard.html assets/bundle.js
//go:generate gofmt -s -w assets.go
//go:generate sed -i "s#var _public#//nolint:misspell\\n&#" assets.go
>>>>>>> dashboard: footer, deep state update
import (
"fmt"
@ -34,6 +40,7 @@ import (
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc"
"github.com/rcrowley/go-metrics"
"golang.org/x/net/websocket"
@ -73,8 +80,8 @@ func New(config *Config) (*Dashboard, error) {
config: config,
quit: make(chan chan error),
charts: &HomeMessage{
Memory: &Chart{},
Traffic: &Chart{},
Memory: ChartEntries{},
Traffic: ChartEntries{},
},
}, nil
}
@ -87,6 +94,8 @@ func (db *Dashboard) APIs() []rpc.API { return nil }
// Start implements node.Service, starting the data collection thread and the listening server of the dashboard.
func (db *Dashboard) Start(server *p2p.Server) error {
log.Info("Starting dashboard")
db.wg.Add(2)
go db.collectData()
go db.collectLogs() // In case of removing this line change 2 back to 1 in wg.Add.
@ -160,7 +169,7 @@ func (db *Dashboard) webHandler(w http.ResponseWriter, r *http.Request) {
w.Write(blob)
return
}
blob, err := Asset(filepath.Join("public", path))
blob, err := Asset(path)
if err != nil {
log.Warn("Failed to load the asset", "path", path, "err", err)
http.Error(w, "not found", http.StatusNotFound)
@ -199,13 +208,12 @@ func (db *Dashboard) apiHandler(conn *websocket.Conn) {
}()
// Send the past data.
client.msg <- Message{
General: &GeneralMessage{
Version: params.Version,
},
Home: &HomeMessage{
Memory: &Chart{
History: db.charts.Memory.History,
},
Traffic: &Chart{
History: db.charts.Traffic.History,
},
Memory: db.charts.Memory,
Traffic: db.charts.Traffic,
},
}
// Start tracking the connection and drop at connection loss.
@ -249,24 +257,20 @@ func (db *Dashboard) collectData() {
Value: inboundTraffic,
}
first := 0
if len(db.charts.Memory.History) == memorySampleLimit {
if len(db.charts.Memory) == memorySampleLimit {
first = 1
}
db.charts.Memory.History = append(db.charts.Memory.History[first:], memory)
db.charts.Memory = append(db.charts.Memory[first:], memory)
first = 0
if len(db.charts.Traffic.History) == trafficSampleLimit {
if len(db.charts.Traffic) == trafficSampleLimit {
first = 1
}
db.charts.Traffic.History = append(db.charts.Traffic.History[first:], traffic)
db.charts.Traffic = append(db.charts.Traffic[first:], traffic)
db.sendToAll(&Message{
Home: &HomeMessage{
Memory: &Chart{
New: memory,
},
Traffic: &Chart{
New: traffic,
},
Memory: ChartEntries{memory},
Traffic: ChartEntries{traffic},
},
})
}
@ -287,7 +291,7 @@ func (db *Dashboard) collectLogs() {
case <-time.After(db.config.Refresh / 2):
db.sendToAll(&Message{
Logs: &LogsMessage{
Log: fmt.Sprintf("%-4d: This is a fake log.", id),
Log: []string{fmt.Sprintf("%-4d: This is a fake log.", id)},
},
})
id++

View file

@ -19,6 +19,7 @@ package dashboard
import "time"
type Message struct {
General *GeneralMessage `json:"general,omitempty"`
Home *HomeMessage `json:"home,omitempty"`
Chain *ChainMessage `json:"chain,omitempty"`
TxPool *TxPoolMessage `json:"txpool,omitempty"`
@ -27,16 +28,17 @@ type Message struct {
Logs *LogsMessage `json:"logs,omitempty"`
}
type HomeMessage struct {
Memory *Chart `json:"memory,omitempty"`
Traffic *Chart `json:"traffic,omitempty"`
type GeneralMessage struct {
Version string `json:"version,omitempty"`
}
type Chart struct {
History []*ChartEntry `json:"history,omitempty"`
New *ChartEntry `json:"new,omitempty"`
type HomeMessage struct {
Memory ChartEntries `json:"memory,omitempty"`
Traffic ChartEntries `json:"traffic,omitempty"`
}
type ChartEntries []*ChartEntry
type ChartEntry struct {
Time time.Time `json:"time,omitempty"`
Value float64 `json:"value,omitempty"`
@ -59,5 +61,5 @@ type SystemMessage struct {
}
type LogsMessage struct {
Log string `json:"log,omitempty"`
Log []string `json:"log,omitempty"`
}