Merge pull request #372 from Hornwitser/storage-page

Storage page
This commit is contained in:
Hornwitser authored and GitHub committed 2021-03-23 20:02:31 +01:00
commit e73599a800
16 files changed
+481 -50

No files matched your search

+103 -1
View File
@@ -329,6 +329,43 @@ class BaseMasterPlugin {
*/
onSlaveConnectionEvent(connection, event) { }
/**
* Called when an avent on a control connection happens
*
* The event param may be one of connect, drop, resume and close and has
* the following meaning:
*
* ##### connect
*
* Invoked when a new connection to the control has been established.
*
* ##### drop
*
* Invoked when a connection loss is detected between the master and a
* control. Plugins should respond to this event by throtteling
* messages it is sending to the given control connection to an absolute
* minimum.
*
* Messages sent over a dropped control connection will get queued up in
* memory on the master and sent all in one go when the connection is
* re-established again.
*
* ##### resume
*
* Invoked when a connection that had previously been dropped is
* re-established.
*
* ##### close
*
* Invoked when the connection to the control has been closed.
*
* @param {module:master/master~ControlConnection} connection -
* The connection the event occured on.
* @param {string} event - one of connect, drop, resume, and close.
*/
onControlConnectionEvent(connection, event) { }
/**
* Called when a slave is preparing to disconnect from the master
*
@@ -439,6 +476,21 @@ class BaseControlPlugin {
* form.
*/
/**
* Plugin supplied pages
* @typedef {Object} module:Lib/plugin~Page
* @property {string} path - URL path to this page.
* @property {string=} sidebarPath -
* If present and this path matches one of the pages in the sidebar it
* will cause that sidebar entry to be highlighted as active.
* @property {string=} sidebarName -
* If present creates an entry in the sidebar for this page with the
* given text.
* @property {ReactNode} content -
* A react node which is rendered when this page is navigated to.
* Should render a PageLayout.
*/
/**
* Base class for web interface plugins
*
@@ -462,6 +514,13 @@ class BaseWebPlugin {
*/
this.info = info;
/**
* Control link to the master server, not available until the
* connect event in onMasterConnectionEvent is signaled.
* @type {?module:lib/link.Link}
*/
this.control = null;
/**
* Logger for this plugin
*
@@ -477,12 +536,55 @@ class BaseWebPlugin {
* @type {Array<module:lib/plugin~LoginForm>}
*/
this.loginForms = [];
/**
* List of pages provided by this plugin
*
* @type {Array<module:lib/plugin~Page>}
*/
this.pages = [];
}
/**
* Called immediately after the class is instantiated.
*/
async init() { }
/**
* Called when an event on the master connection happens
*
* The event param may be one of connect, drop, resume and close and has
* the following meaning:
*
* ##### connect
*
* Invoked when a new connection to the master has been established.
*
* ##### drop
*
* Invoked when a connection loss is detected between the control link
* and the master. Plugins should respond to this event by throtteling
* messages it is sending to the master to an absolute minimum.
*
* Messages sent over a dropped master connection will get queued up in
* memory in the browser and sent all in one go when the connection is
* re-established again.
*
* ##### resume
*
* Invoked when the connection that had previously dropped is
* re-established.
*
* ##### close
*
* Invoked when the connection to the master has been closed. This
* typically means the master server has shut down. Plugins should not
* send any messages that goes to or via the master server after the
* connection has been closed and before a new one is established.
*
* @param {string} event - one of connect, drop, resume and close
*/
onMasterConnectionEvent(event) { }
}
/**
@@ -508,7 +610,7 @@ function attachPluginMessages(link, plugin) {
messageFormat.attach(link);
} else {
messageFormat.attach(link, async (message, format) => await plugin[handler](message, format));
messageFormat.attach(link, async (message, format) => await plugin[handler](message, format, link));
}
} catch (err) {
+13 -5
View File
@@ -696,6 +696,14 @@ class ControlConnection extends BaseConnection {
debugEvents.off("message", this.ws_dumper);
}
});
for (let event of ["connect", "drop", "resume", "close"]) {
this.connector.on(event, () => {
for (let masterPlugin of masterPlugins.values()) {
masterPlugin.onControlConnectionEvent(this, event);
}
});
}
}
async getMasterConfigRequestHandler() {
@@ -2012,7 +2020,7 @@ async function startServer(args) {
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackConfigs = [];
if (args.dev) {
webpackConfigs.push(require("./webpack.config"));
webpackConfigs.push(require("./webpack.config")({}));
}
if (args.devPlugin) {
for (let name of args.devPlugin) {
@@ -2020,14 +2028,14 @@ async function startServer(args) {
if (!info) {
throw new libErrors.StartupError(`No plugin named ${name}`);
}
webpackConfigs.push(
require(path.posix.join(info.requirePath, "webpack.config"))
);
let config = require(path.posix.join(info.requirePath, "webpack.config"))({});
config.output.publicPath = `/plugins/${name}/`;
webpackConfigs.push(config);
}
}
/* eslint-enable global-require */
const compiler = webpack(webpackConfigs.map(config => config({})));
const compiler = webpack(webpackConfigs);
devMiddleware = webpackDevMiddleware(compiler, {});
app.use(devMiddleware);
}
+16 -41
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useContext, useEffect, useState } from "react";
import { Switch, Route, useHistory } from "react-router-dom";
import { Dropdown, Layout, Menu } from "antd";
import UserOutlined from "@ant-design/icons/UserOutlined";
@@ -7,46 +7,21 @@ import webUiPackage from "../../package.json";
import { useAccount } from "../model/account";
import ErrorBoundary from "./ErrorBoundary";
import ErrorPage from "./ErrorPage";
import PluginsContext from "./PluginsContext";
import { pages } from "../pages";
const { Header, Sider } = Layout;
import MasterPage from "./MasterPage";
import SlavesPage from "./SlavesPage";
import InstancesPage from "./InstancesPage";
import InstanceViewPage from "./InstanceViewPage";
import UsersPage from "./UsersPage";
import UserViewPage from "./UserViewPage";
import RolesPage from "./RolesPage";
import RoleViewPage from "./RoleViewPage";
import PluginsPage from "./PluginsPage";
import PluginViewPage from "./PluginViewPage";
const pages = [
{ path: "/instances/:id/view", sidebarPath: "/instances", content: <InstanceViewPage /> },
{ path: "/users/:name/view", sidebarPath: "/users", content: <UserViewPage /> },
{ path: "/roles/:id/view", sidebarPath: "/roles", content: <RoleViewPage /> },
{ path: "/plugins/:name/view", sidebarPath: "/plugins", content: <PluginViewPage /> },
];
const sidebar = [
{ name: "Master", path: "/master", content: <MasterPage /> },
{ name: "Slaves", path: "/slaves", content: <SlavesPage /> },
{ name: "Instances", path: "/instances", content: <InstancesPage />},
{ name: "Users", path: "/users", content: <UsersPage /> },
{ name: "Roles", path: "/roles", content: <RolesPage /> },
{ name: "Plugins", path: "/plugins", content: <PluginsPage /> },
];
export default function SiteLayout(props) {
let history = useHistory();
let [sidebarPath, setSidebarPath] = useState(null);
let [currentSidebarPath, setCurrentSidebarPath] = useState(null);
let account = useAccount();
let plugins = useContext(PluginsContext);
function SetSidebar(setSidebarProps) {
useEffect(() => {
setSidebarPath(setSidebarProps.path);
setCurrentSidebarPath(setSidebarProps.path);
});
return null;
}
@@ -57,6 +32,10 @@ export default function SiteLayout(props) {
<Menu.Item danger onClick={() => { account.logOut(); }}>Log out</Menu.Item>
</Menu>;
let combinedPages = [...pages];
for (let plugin of plugins.values()) {
combinedPages.push(...plugin.pages);
}
return <Layout style={{ minHeight: "100vh" }}>
<Header className="header">
@@ -86,27 +65,23 @@ export default function SiteLayout(props) {
>
<Menu
mode="inline"
selectedKeys={[sidebarPath]}
selectedKeys={[currentSidebarPath]}
style={{ height: "100%", borderRight: 0 }}
onClick={({ key }) => history.push(key)}
>
{sidebar.map(({name, path}) => <Menu.Item key={path}>{name}</Menu.Item>)}
{combinedPages.map(({sidebarName, path}) => (
sidebarName ? <Menu.Item key={path}>{sidebarName}</Menu.Item> : null)
)}
</Menu>
</Sider>
<Layout className="site-layout-content-container">
<Switch>
{sidebar.map(({path, content}) => <Route exact path={path} key={path}>
<SetSidebar path={path} />
{combinedPages.map(({path, sidebarPath, content}) => <Route exact path={path} key={path}>
<SetSidebar path={sidebarPath ? sidebarPath : path} />
<ErrorBoundary Component={ErrorPage}>
{content}
</ErrorBoundary>
</Route>)}
{pages.map(page => <Route exact path={page.path} key={page.path}>
<SetSidebar path={page.sidebarPath} />
<ErrorBoundary Component={ErrorPage}>
{page.content}
</ErrorBoundary>
</Route>)}
<Route>
<SetSidebar path={null} />
</Route>
File renamed without changes.

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

+6
View File
@@ -259,3 +259,9 @@ body {
.json-input {
font-family: monospace;
}
.factorio-icon.item-unknown-item {
background: url("./images/unknown-item.png");
height: 32px;
width: 32px;
}
+2
View File
@@ -3,6 +3,8 @@ export { default as notify, notifyErrorHandler } from "./util/notify.jsx";
export * from "./model/instance.jsx";
export * from "./model/slave.jsx";
export * from "./model/locale.jsx";
export * from "./model/item_metadata.jsx";
export { default as ControlContext } from "./components/ControlContext";
@@ -0,0 +1,38 @@
import React, { useEffect, useState } from "react";
let itemMetadataCache = null;
export function useItemMetadata() {
let [itemMetadata, setItemMetadata] = useState(itemMetadataCache || new Map());
useEffect(() => {
async function load() {
let response = await fetch(`${webRoot}export/item-metadata.json`);
if (response.ok) {
let data = await response.json();
itemMetadataCache = new Map(data);
let style = document.createElement("style");
style.type = "text/css";
document.head.appendChild(style);
for (let [name, meta] of itemMetadataCache) {
style.sheet.insertRule(
`.item-${CSS.escape(name)} {
background-image: url("${webRoot}export/item-spritesheet.png");
background-repeat: no-repeat;
background-position: -${meta.x}px -${meta.y}px;
height: ${meta.size}px;
width: ${meta.size}px;
}`
);
}
setItemMetadata(itemMetadataCache);
}
}
if (!itemMetadataCache) {
load();
}
}, []);
return itemMetadata;
}
+24
View File
@@ -0,0 +1,24 @@
import React, { useEffect, useState } from "react";
let localeCache = null;
export function useLocale() {
let [locale, setLocale] = useState(localeCache || new Map());
useEffect(() => {
async function load() {
let response = await fetch(`${webRoot}export/locale.json`);
if (response.ok) {
let data = await response.json();
localeCache = new Map(data);
setLocale(localeCache);
}
}
if (!localeCache) {
load();
}
}, []);
return locale;
}
+29
View File
@@ -0,0 +1,29 @@
import React from "react";
import MasterPage from "./components/MasterPage";
import SlavesPage from "./components/SlavesPage";
import InstancesPage from "./components/InstancesPage";
import InstanceViewPage from "./components/InstanceViewPage";
import UsersPage from "./components/UsersPage";
import UserViewPage from "./components/UserViewPage";
import RolesPage from "./components/RolesPage";
import RoleViewPage from "./components/RoleViewPage";
import PluginsPage from "./components/PluginsPage";
import PluginViewPage from "./components/PluginViewPage";
export const pages = [
{ path: "/master", sidebarName: "Master", content: <MasterPage /> },
{ path: "/slaves", sidebarName: "Slaves", content: <SlavesPage /> },
{ path: "/instances", sidebarName: "Instances", content: <InstancesPage />},
{ path: "/instances/:id/view", sidebarPath: "/instances", content: <InstanceViewPage /> },
{ path: "/users", sidebarName: "Users", content: <UsersPage /> },
{ path: "/users/:name/view", sidebarPath: "/users", content: <UserViewPage /> },
{ path: "/roles", sidebarName: "Roles", content: <RolesPage /> },
{ path: "/roles/:id/view", sidebarPath: "/roles", content: <RoleViewPage /> },
{ path: "/plugins", sidebarName: "Plugins", content: <PluginsPage /> },
{ path: "/plugins/:name/view", sidebarPath: "/plugins", content: <PluginViewPage /> },
];
export const sidebarPages = [
];
+9
View File
@@ -46,6 +46,7 @@ export class Control extends libLink.Link {
*/
this.plugins = plugins;
for (let plugin of plugins.values()) {
plugin.control = this;
libPlugin.attachPluginMessages(this, plugin);
}
@@ -73,6 +74,14 @@ export class Control extends libLink.Link {
this.connector.on("close", () => {
this.accountName = null;
});
for (let event of ["connect", "drop", "resume", "close"]) {
this.connector.on(event, () => {
for (let plugin of this.plugins.values()) {
plugin.onMasterConnectionEvent(event);
}
});
}
}
async logMessageEventHandler(message) {
+23 -2
View File
@@ -1,6 +1,7 @@
"use strict";
const libLink = require("@clusterio/lib/link");
const libConfig = require("@clusterio/lib/config");
const libUsers = require("@clusterio/lib/users");
class MasterConfigGroup extends libConfig.PluginConfigGroup {}
MasterConfigGroup.defaultAccess = ["master", "slave", "control"];
@@ -41,6 +42,13 @@ InstanceConfigGroup.define({
});
InstanceConfigGroup.finalize();
libUsers.definePermission({
name: "subspace_storage.storage.view",
title: "View Subspace Storage",
description: "View the items and fluids stored in the shared subspace.",
grantByDefault: true,
});
// JSON schema for subspace storage items
const items = {
type: "array",
@@ -65,6 +73,9 @@ module.exports = {
masterEntrypoint: "master",
MasterConfigGroup,
webEntrypoint: "./web",
routes: ["/storage"],
messages: {
// XXX this should be a request to be reliable
place: new libLink.Event({
@@ -90,7 +101,8 @@ module.exports = {
}),
getStorage: new libLink.Request({
type: "subspace_storage:get_storage",
links: ["instance-slave", "slave-master"],
links: ["instance-slave", "slave-master", "control-master"],
permission: "subspace_storage.storage.view",
forwardTo: "master",
responseProperties: {
"items": items,
@@ -98,11 +110,20 @@ module.exports = {
}),
updateStorage: new libLink.Event({
type: "subspace_storage:update_storage",
links: ["master-slave", "slave-instance"],
links: ["master-slave", "slave-instance", "master-control"],
broadcastTo: "instance",
eventProperties: {
"items": items,
},
}),
setStorageSubscription: new libLink.Request({
type: "subspace_storage:set_storage_subscription",
links: ["control-master"],
permission: "subspace_storage.storage.view",
requestProperties: {
"storage": { type: "boolean" },
},
}),
},
};
+19
View File
@@ -72,6 +72,8 @@ class MasterPlugin extends libPlugin.BaseMasterPlugin {
}
}, 1000);
this.subscribedControlLinks = new Set();
routes.addApiRoutes(this.master.app, this.items, this.metrics.endpointHitCounter);
}
@@ -90,6 +92,9 @@ class MasterPlugin extends libPlugin.BaseMasterPlugin {
itemsToUpdate = [...itemsToUpdate.entries()];
this.broadcastEventToSlaves(this.info.messages.updateStorage, { items: itemsToUpdate });
for (let link of this.subscribedControlLinks) {
this.info.messages.updateStorage.send(link, { items: itemsToUpdate });
}
this.itemsLastUpdate = new Map(this.items._items.entries());
}
@@ -181,6 +186,20 @@ class MasterPlugin extends libPlugin.BaseMasterPlugin {
};
}
async setStorageSubscriptionRequestHandler(message, request, link) {
if (message.data.storage) {
this.subscribedControlLinks.add(link);
} else {
this.subscribedControlLinks.delete(link);
}
}
onControlConnectionEvent(connection, event) {
if (event === "close") {
this.subscribedControlLinks.delete(connection);
}
}
onMetrics() {
if (this.items) {
for (let [key, count] of this.items._items) {
+5
View File
@@ -0,0 +1,5 @@
.factorio-icon {
display: inline-block;
vertical-align: middle;
margin-right: 0.5em;
}
+184
View File
@@ -0,0 +1,184 @@
import React, { useContext, useEffect, useState } from "react";
import { Input, Table, Typography } from "antd";
import libPlugin from "@clusterio/lib/plugin";
import { notifyErrorHandler, useItemMetadata, useLocale, PageLayout, ControlContext } from "@clusterio/web_ui";
import info from "../info";
import "./index.css";
const { Paragraph } = Typography;
function useStorage(control) {
let plugin = control.plugins.get("subspace_storage");
let [storage, setStorage] = useState([...plugin.storage]);
useEffect(() => {
function update() {
setStorage([...plugin.storage]);
}
plugin.onUpdate(update);
return () => {
plugin.offUpdate(update);
};
}, []);
return storage;
}
function StoragePage() {
let control = useContext(ControlContext);
let locale = useLocale();
let itemMetadata = useItemMetadata();
let storage = useStorage(control);
let [filter, setFilter] = useState(null);
function getLocaleName(itemName) {
let localeName = itemName;
let meta = itemMetadata.get(itemName);
if (meta && meta.localized_name) {
// TODO: implement the locale to name conversion.
localeName = locale.get(meta.localized_name[0]);
} else {
for (let section of ["item-name", "entity-name", "fluid-name", "equipment-name"]) {
let name = locale.get(`${section}.${itemName}`);
if (name) {
localeName = name;
break;
}
}
}
return localeName;
}
let numberFormat = new Intl.NumberFormat("en-US");
return <PageLayout nav={[{ name: "Storage" }]}>
<h2>Storage</h2>
<Paragraph>
<Input
placeholder="Search"
onChange={(event) => {
let search = event.target.value.trim();
if (!search) {
setFilter(null);
return;
}
search = search.replace(/(^| )(\w)/g, "$1\\b$2");
search = search.replace(/ +/g, ".*");
let filterExpr = new RegExp(search, "i");
setFilter(() => (item => {
let name = getLocaleName(item[0]);
return filterExpr.test(name) || filterExpr.test(item[0]);
}));
}}
/>
</Paragraph>
<Table
columns={[
{
title: "Resource",
key: "resource",
sorter: (a, b) => {
let aName = getLocaleName(a[0]);
let bName = getLocaleName(b[0]);
if (aName < bName) { return -1; }
if (aName > bName) { return 1; }
return 0;
},
render: item => {
let localeName = getLocaleName(item[0]);
let hasMeta = itemMetadata.get(item[0]);
return <>
<span className={`factorio-icon item-${hasMeta ? item[0] : "unknown-item"}`}/>
{localeName}
</>;
},
},
{
title: "Quantity",
key: "quantity",
align: "right",
defaultSortOrder: "descend",
sorter: (a, b) => a[1] - b[1],
render: item => numberFormat.format(item[1]),
},
]}
dataSource={filter ? storage.filter(filter) : storage}
rowKey={item => item[0]}
pagination={false}
/>
</PageLayout>;
}
export class WebPlugin extends libPlugin.BaseWebPlugin {
async init() {
this.pages = [
{ path: "/storage", sidebarName: "Storage", content: <StoragePage/> },
];
this.storage = new Map();
this.callbacks = [];
}
onMasterConnectionEvent(event) {
if (event === "connect") {
this.updateSubscription();
}
}
async updateStorageEventHandler(message) {
this.updateStorage(message.data.items);
}
onUpdate(callback) {
this.callbacks.push(callback);
if (this.callbacks.length) {
this.updateSubscription();
}
}
offUpdate(callback) {
let index = this.callbacks.lastIndexOf(callback);
if (index === -1) {
throw new Error("callback is not registered");
}
this.callbacks.splice(index, 1);
if (!this.callbacks.length) {
this.updateSubscription();
}
}
updateStorage(items) {
for (let [name, amount] of items) {
this.storage.set(name, amount);
}
for (let callback of this.callbacks) {
callback();
}
}
updateSubscription() {
if (!this.control.connector.connected) {
return;
}
info.messages.setStorageSubscription.send(
this.control, { storage: Boolean(this.callbacks.length) }
).catch(notifyErrorHandler("Error subscribing to storage"));
if (this.callbacks.length) {
info.messages.getStorage.send(this.control).then(
result => {
this.updateStorage(result.items);
}
).catch(notifyErrorHandler("Error updating storage"));
} else {
this.storage.clear();
}
}
}
+3 -1
View File
@@ -21,12 +21,14 @@ module.exports = (env = {}) => merge(common(env), {
exposes: {
"./info": "./info.js",
"./package.json": "./package.json",
"./web": "./web/index.jsx",
},
shared: {
"@clusterio/lib/config": { import: false },
"@clusterio/lib/link": { import: false },
"@clusterio/lib/plugin": { import: false },
"@clusterio/lib/users": { import: false },
"@clusterio/web_ui": { import: false },
"ajv": { import: false },
"antd": { import: false },
"react": { import: false },
"react-dom": { import: false },
+7
View File
@@ -13,6 +13,13 @@ const server = require("@clusterio/lib/factorio/server");
const { ConsoleTransport, logger } = require("@clusterio/lib/logging");
const libLoggingUtils = require("@clusterio/lib/logging_utils");
// Make sure permissions from plugins are loaded
require("../../plugins/global_chat/info");
require("../../plugins/player_auth/info");
require("../../plugins/research_sync/info");
require("../../plugins/statistics_exporter/info");
require("../../plugins/subspace_storage/info");
class TestControl extends libLink.Link {
constructor(connector) {