Add instance update subscription

Provide the control link with the ability to subscribe to updates when
instance status and properties changes.  This allows the web interface
to respond in real time to instance starts and stops that are triggered
from somewhere else.
This commit is contained in:
Hornwitser committed 2021-05-21 17:27:01 +02:00
1 parent bda103d7a0
commit 6ffcb8c451
11 files changed
+219 -29

No files matched your search

@@ -26,7 +26,7 @@ export default function InstanceViewPage(props) {
let history = useHistory();
let control = useContext(ControlContext);
let [instance, updateInstance] = useInstance(instanceId);
let [instance] = useInstance(instanceId);
let [slave] = useSlave(Number(instance["assigned_slave"]));
let [creatingSave, setCreatingSave] = useState(false);
@@ -44,10 +44,7 @@ export default function InstanceViewPage(props) {
}
let instanceButtons = <Space>
<StartStopInstanceButton
instance={instance}
onFinish={updateInstance}
/>
<StartStopInstanceButton instance={instance} />
{instance.status === "stopped" && <Button
loading={creatingSave}
onClick={() => {
@@ -55,7 +52,6 @@ export default function InstanceViewPage(props) {
libLink.messages.createSave.send(
control, { instance_id: instanceId }
).catch(notifyErrorHandler("Error creating save")).finally(() => {
updateInstance();
setCreatingSave(false);
});
}}
@@ -107,7 +103,6 @@ export default function InstanceViewPage(props) {
disabled: !["unknown", "unassigned", "stopped"].includes(instance["status"]),
}}
buttonContent={assigned ? "Reassign" : "Assign"}
onFinish={updateInstance}
/>
</Descriptions.Item>
<Descriptions.Item label="Status">{instance["status"]}</Descriptions.Item>
@@ -117,6 +112,6 @@ export default function InstanceViewPage(props) {
<InstanceConsole id={instanceId} />
<InstanceRcon id={instanceId} disabled={instance["status"] !== "running"} />
<InstanceConfigTree id={instanceId} onApply={updateInstance} />
<InstanceConfigTree id={instanceId} />
</PageLayout>;
}
+16 -8
View File
@@ -2,6 +2,7 @@ import React, { useEffect, useContext, useState } from "react";
import ControlContext from "../components/ControlContext";
import libLink from "@clusterio/lib/link";
import { logger } from "@clusterio/lib/logging";
export function useInstance(id) {
@@ -14,19 +15,26 @@ export function useInstance(id) {
return;
}
// XXX optimize by requesting only the instance in question
libLink.messages.listInstances.send(control).then(result => {
let match = result.list.find(i => i.id === id);
if (!match) {
setInstance({ missing: true });
} else {
setInstance({ ...match, present: true });
}
libLink.messages.getInstance.send(control, { id }).then(result => {
setInstance({ ...result, present: true });
}).catch(err => {
logger.log(`Failed to get instance: ${err}`);
setInstance({ missing: true });
});
}
useEffect(() => {
updateInstance();
function updateHandler(newInstance) {
setInstance({ ...newInstance, present: true });
}
control.onInstanceUpdate(id, updateHandler);
return () => {
control.offInstanceUpdate(id, updateHandler);
};
}, [id]);
return [instance, updateInstance];
+58
View File
@@ -62,10 +62,14 @@ export class Control extends libLink.Link {
*/
this.accountName = null;
this.instanceUpdateHandlers = new Map();
this.instanceLogHandlers = new Map();
this.connector.on("connect", data => {
this.accountName = data.account.name;
this.updateInstanceSubscriptions().catch(err => logger.error(
`Unexpected error updating instance subscriptions:\n${err.stack}`
));
this.updateLogSubscriptions().catch(err => logger.error(
`Unexpected error updating log subscriptions:\n${err.stack}`
));
@@ -84,6 +88,60 @@ export class Control extends libLink.Link {
}
}
async instanceUpdateEventHandler(message) {
let handlers = this.instanceUpdateHandlers.get(message.data.id);
for (let handler of handlers || []) {
handler(message.data);
}
};
async onInstanceUpdate(id, handler) {
if (!Number.isInteger(id)) {
throw new Error("Invalid instance id");
}
let handlers = this.instanceUpdateHandlers.get(id);
if (!handlers) {
handlers = [];
this.instanceUpdateHandlers.set(id, handlers);
}
handlers.push(handler);
if (handlers.length === 1) {
await this.updateInstanceSubscriptions();
}
}
async offInstanceUpdate(id, handler) {
let handlers = this.instanceUpdateHandlers.get(id);
if (!handlers || !handlers.length) {
throw new Error(`No handlers for instance ${id} exist`);
}
let index = handlers.lastIndexOf(handler);
if (index === -1) {
throw new Error(`Given handler is not registered for instance ${id}`);
}
handlers.splice(index, 1);
if (!handlers.length) {
this.instanceUpdateHandlers.delete(id);
await this.updateInstanceSubscriptions();
}
}
async updateInstanceSubscriptions() {
if (!this.connector.connected) {
return;
}
await libLink.messages.setInstanceSubscriptions.send(this, {
all: false,
instance_ids: [...this.instanceUpdateHandlers.keys()],
});
}
async logMessageEventHandler(message) {
let info = message.data.info;