Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update macro events real-time #294

Open
wants to merge 15 commits into
base: dev
Choose a base branch
from
2 changes: 1 addition & 1 deletion core/bindings/MacroEventInner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ExitStatus } from "./ExitStatus";

export type MacroEventInner = { type: "Started" } | { type: "Detach" } | { type: "Stopped", exit_status: ExitStatus, };
export type MacroEventInner = { type: "Started", macro_name: string, time: bigint, } | { type: "Detach" } | { type: "Stopped", exit_status: ExitStatus, };
5 changes: 4 additions & 1 deletion core/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,10 @@ pub struct UserEvent {
#[ts(export)]
#[serde(tag = "type")]
pub enum MacroEventInner {
Started,
Started {
macro_name: String,
time: i64
},
/// Macro requests to be detached, useful for macros that run in the background such as prelaunch script
Detach,
Stopped {
Expand Down
9 changes: 7 additions & 2 deletions core/src/macro_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,10 +364,15 @@ impl MacroExecutor {
}
};

let macro_name: String = path_to_main_module.file_name().unwrap().to_str().unwrap().to_string();

event_broadcaster.send(
MacroEvent {
macro_pid: pid,
macro_event_inner: MacroEventInner::Started,
macro_event_inner: MacroEventInner::Started {
macro_name: String::from(&macro_name[..macro_name.len() - 3]),
time: chrono::Utc::now().timestamp(),
},
instance_uuid: instance_uuid.clone(),
}
.into(),
Expand Down Expand Up @@ -492,7 +497,7 @@ impl MacroExecutor {
if let Ok(event) = rx.recv().await {
if let EventInner::MacroEvent(MacroEvent {
macro_pid,
macro_event_inner: MacroEventInner::Started,
macro_event_inner: MacroEventInner::Started { .. },
..
}) = event.event_inner
{
Expand Down
2 changes: 1 addition & 1 deletion core/src/output_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl From<&Event> for ClientEvent {
},
EventInner::UserEvent(_) => EventLevel::Info,
EventInner::MacroEvent(m) => match m.macro_event_inner {
MacroEventInner::Started => EventLevel::Info,
MacroEventInner::Started { .. } => EventLevel::Info,
MacroEventInner::Stopped { ref exit_status } => {
if exit_status.is_success() {
EventLevel::Info
Expand Down
7 changes: 5 additions & 2 deletions dashboard/src/bindings/MacroEventInner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ExitStatus } from "./ExitStatus";
import type { ExitStatus } from './ExitStatus';

export type MacroEventInner = { type: "Started" } | { type: "Detach" } | { type: "Stopped", exit_status: ExitStatus, };
export type MacroEventInner =
| { type: 'Started'; macro_name: string; time: bigint }
| { type: 'Detach' }
| { type: 'Stopped'; exit_status: ExitStatus };
94 changes: 73 additions & 21 deletions dashboard/src/data/EventStream.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useUid, useUserInfo } from 'data/UserInfo';
import { useUid } from 'data/UserInfo';
import { addInstance, deleteInstance, updateInstance } from 'data/InstanceList';
import { LodestoneContext } from 'data/LodestoneContext';
import { useQueryClient } from '@tanstack/react-query';
Expand All @@ -14,6 +14,9 @@ import { UserPermission } from 'bindings/UserPermission';
import { PublicUser } from 'bindings/PublicUser';
import { toast } from 'react-toastify';
import { Player } from 'bindings/Player';
import { TaskEntry } from 'bindings/TaskEntry';
import { HistoryEntry } from 'bindings/HistoryEntry';
import { MacroPID } from '../bindings/MacroPID';

/**
* does not return anything, call this for the side effect of subscribing to the event stream
Expand Down Expand Up @@ -248,7 +251,10 @@ export const useEventStream = () => {
['user', 'list'],
(oldList: { [uid: string]: PublicUser } | undefined) => {
if (!oldList) return oldList;
const newUser = {...oldList[uid], permissions: new_permissions};
const newUser = {
...oldList[uid],
permissions: new_permissions,
};
const newList = { ...oldList };
newList[uid] = newUser;
return newList;
Expand All @@ -268,8 +274,22 @@ export const useEventStream = () => {
macro_event_inner: event_inner,
}) =>
match(event_inner, {
Started: () => {
Started: ({ macro_name, time }) => {
console.log(`Macro ${macro_pid} started on ${uuid}`);

queryClient.setQueryData(
['instance', uuid, 'taskList'],
(oldData?: TaskEntry[]): TaskEntry[] => {
const newTask: TaskEntry = {
name: macro_name,
creation_time: time,
pid: macro_pid,
};

return oldData ? [...oldData, newTask] : [newTask];
}
);

dispatch({
title: `Macro ${macro_pid} started on ${uuid}`,
event,
Expand All @@ -278,16 +298,40 @@ export const useEventStream = () => {
});
},
Detach: () => {
console.log(`Macro ${macro_pid} detached on ${uuid}`);
dispatch({
title: `Macro ${macro_pid} detached on ${uuid}`,
event,
type: 'add',
fresh,
});
console.log(`Macro ${macro_pid} detached on ${uuid}`);
dispatch({
title: `Macro ${macro_pid} detached on ${uuid}`,
event,
type: 'add',
fresh,
});
},
Stopped: ({ exit_status }) => {
console.log(`Macro ${macro_pid} stopped on ${uuid} with status ${exit_status.type}`);
console.log(
`Macro ${macro_pid} stopped on ${uuid} with status ${exit_status.type}`
);

let oldTask: TaskEntry | undefined;
queryClient.setQueryData(
['instance', uuid, 'taskList'],
(oldData?: TaskEntry[]): TaskEntry[] | undefined => {
oldTask = oldData?.find((task) => task.pid === macro_pid);
return oldData?.filter((task) => task.pid !== macro_pid);
}
);
hanmindev marked this conversation as resolved.
Show resolved Hide resolved

queryClient.setQueryData(
['instance', uuid, 'historyList'],
(oldData?: HistoryEntry[]): HistoryEntry[] | undefined => {
if (!oldTask) return oldData;
const newHistory: HistoryEntry = {
task: oldTask,
exit_status,
};

return [newHistory, ...(oldData || [])];
}
);
dispatch({
title: `Macro ${macro_pid} stopped on ${uuid} with status ${exit_status.type}`,
event,
Expand Down Expand Up @@ -320,14 +364,22 @@ export const useEventStream = () => {
addInstance(instance_info, queryClient),
InstanceDelete: ({ instance_uuid: uuid }) =>
deleteInstance(uuid, queryClient),
FSOperationCompleted: ({ instance_uuid, success, message }) => {
FSOperationCompleted: ({
instance_uuid,
success,
message,
}) => {
if (success) {
toast.success(message)
toast.success(message);
} else {
toast.error(message)
toast.error(message);
}
queryClient.invalidateQueries(['instance', instance_uuid, 'fileList']);
}
queryClient.invalidateQueries([
'instance',
instance_uuid,
'fileList',
]);
},
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
(_) => {}
Expand Down Expand Up @@ -407,11 +459,11 @@ export const useEventStream = () => {
if (!token) return;

const connectWebsocket = () => {
const wsAddress = `${core.protocol === 'https' ? 'wss' : 'ws'}://${core.address}:${
core.port ?? LODESTONE_PORT
}/api/${core.apiVersion}/events/all/stream?filter=${JSON.stringify(
eventQuery
)}`;
const wsAddress = `${core.protocol === 'https' ? 'wss' : 'ws'}://${
core.address
}:${core.port ?? LODESTONE_PORT}/api/${
core.apiVersion
}/events/all/stream?filter=${JSON.stringify(eventQuery)}`;

if (wsRef.current) wsRef.current.close();

Expand Down
Loading