Unverified Commit 009fb6a5 authored by Licho's avatar Licho Committed by GitHub

[refactor]Watch to SSE (#2213)

* refactor: package uri wrong, and trivial optimization * feat: finish java, every request each sse, * Spotless Apply * refactor: migrate watch table feature. * fox: import * refactor: remove redundant <> * fix: send sse * refactor: dataStudio * refactor: get TableData * refactor: createModelTypes function * refactor: createModelTypes function * refactor: typo * refactor: * refactor: createModelTypes * refactor: createModelTypes * refactor: * refactor: typo submitting * refactor: * Spotless Apply * refactor: * Spotless Apply * refactor: * fix: test Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * test: Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * Spotless Apply * fix: task data update problem * Spotless Apply * refact * Spotless Apply --------- Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com>
parent 61c549ea
......@@ -22,10 +22,13 @@ package org.dinky.controller;
import org.dinky.data.result.Result;
import org.dinky.service.WatchTableService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
......@@ -34,22 +37,21 @@ import lombok.AllArgsConstructor;
@RestController
@Api(tags = "Watch Table Controller")
@AllArgsConstructor
@RequestMapping("api")
@RequestMapping("/api")
public class WatchTableController {
private final WatchTableService watchTableService;
@PutMapping("/subscribe/watch")
@GetMapping(value = "/subscribe/watch", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ApiOperation("Subscribe watch table")
public Result subscribe(@RequestParam Integer id, @RequestParam String table) {
String destination = watchTableService.registerListenEntry(id, table);
return Result.succeed(destination);
public SseEmitter subscribe(@RequestParam String table) {
return watchTableService.registerListenEntry(table);
}
@PutMapping("/unSubscribe/watch")
@ApiOperation("UnSubscribe watch table")
public Result unsubscribe(@RequestParam Integer id, @RequestParam String table) {
watchTableService.unRegisterListenEntry(id, table);
public Result<Void> unsubscribe(@RequestParam String table) {
watchTableService.unRegisterListenEntry(table);
return Result.succeed();
}
}
......@@ -19,8 +19,10 @@
package org.dinky.service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
public interface WatchTableService {
String registerListenEntry(Integer userId, String table);
SseEmitter registerListenEntry(String table);
void unRegisterListenEntry(Integer userId, String table);
void unRegisterListenEntry(String table);
}
......@@ -29,13 +29,15 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import lombok.extern.slf4j.Slf4j;
......@@ -43,14 +45,11 @@ import lombok.extern.slf4j.Slf4j;
@Service
public class WatchTableServiceImpl implements WatchTableService {
private final SimpMessagingTemplate messagingTemplate;
private final Map<String, Set<String>> registerTableMap = new ConcurrentHashMap<>();
private final Map<String, Set<Target>> registerTableMap = new ConcurrentHashMap<>();
private static final Pattern FULL_TABLE_NAME_PATTERN = Pattern.compile("^`(\\w+)`\\.`(\\w+)`\\.`(\\w+)`$");
public WatchTableServiceImpl(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
public WatchTableServiceImpl() {
WatchTableListener watcher = new WatchTableListener(this::send);
watcher.start();
}
......@@ -58,9 +57,14 @@ public class WatchTableServiceImpl implements WatchTableService {
public void send(String message) {
try {
String[] data = message.split("\n", 2);
final Set<String> destinations = registerTableMap.get(data[0]);
if (destinations != null) {
destinations.forEach(d -> this.messagingTemplate.convertAndSend(d, data[1]));
final Set<Target> targets = registerTableMap.get(data[0]);
if (targets != null) {
targets.forEach(d -> {
if (!d.send(data[1], "data")) {
// maybe closed
targets.remove(d);
}
});
}
} catch (MessagingException e) {
log.error(e.toString());
......@@ -68,25 +72,28 @@ public class WatchTableServiceImpl implements WatchTableService {
}
@Override
public String registerListenEntry(Integer userId, String table) {
public SseEmitter registerListenEntry(String table) {
SseEmitter emitter = new SseEmitter();
String fullName = getFullTableName(table);
String destination = getDestinationByFullName(userId, fullName);
Set<String> destinations = registerTableMap.get(fullName);
if (destinations == null) {
registerTableMap.put(fullName, new HashSet<>(Collections.singletonList(destination)));
String destination = getDestinationByFullName(fullName);
Target target = Target.of(emitter, destination);
Set<Target> targets = registerTableMap.get(fullName);
if (targets == null) {
registerTableMap.put(fullName, new HashSet<>(Collections.singleton(target)));
} else {
destinations.add(destination);
targets.add(target);
}
return destination;
return emitter;
}
@Override
public void unRegisterListenEntry(Integer userId, String table) {
public void unRegisterListenEntry(String table) {
String fullName = getFullTableName(table);
String destination = getDestination(userId, fullName);
Set<String> destinations = registerTableMap.get(fullName);
String destination = getDestination(fullName);
Set<Target> destinations = registerTableMap.get(fullName);
if (destinations != null) {
destinations.remove(destination);
destinations.stream().filter(d -> d.destination.equals(destination)).forEach(Target::complete);
destinations.removeIf(d -> d.destination.equals(destination));
}
}
......@@ -105,26 +112,70 @@ public class WatchTableServiceImpl implements WatchTableService {
return result;
}
public static String getDestination(Integer userId, String table) {
public static String getDestination(String table) {
String fn = getFullTableName(table);
return String.format("/topic/table/%s/%s", userId, fn);
return String.format("/topic/table/%s", fn);
}
public static String getDestinationByFullName(Integer userId, String tableFullName) {
return String.format("/topic/table/%s/%s", userId, tableFullName);
public static String getDestinationByFullName(String tableFullName) {
return String.format("/topic/table/%s", tableFullName);
}
public static class WatchTableListener extends Thread {
public static final class Target {
private final String destination;
public final SseEmitter emitter;
public Target(String destination, SseEmitter emitter) {
this.destination = destination;
this.emitter = emitter;
}
public static Target of(SseEmitter emitter, String destination) {
return new Target(destination, emitter);
}
public boolean send(String message, String type) {
try {
SseEmitter.SseEventBuilder sseEventBuilder = SseEmitter.event();
emitter.send(sseEventBuilder.data(message).name("wt_" + type));
return true;
} catch (Exception e) {
log.error("send message to {} failed: {}", destination, e.getMessage());
emitter.complete();
return false;
}
}
public String getDestination() {
return destination;
}
public SseEmitter getEmitter() {
return emitter;
}
public void complete() {
emitter.complete();
}
}
public static class WatchTableListener {
private final Consumer<String> consumer;
public static final int PORT = 7125;
private DatagramSocket socket;
private boolean running;
private final byte[] buf = new byte[4096];
private final ExecutorService executor;
public WatchTableListener(Consumer<String> consumer) {
this.consumer = consumer;
this.socket = getDatagramSocket(PORT);
executor = Executors.newSingleThreadExecutor();
}
public void start() {
executor.execute(this::run);
}
private static DatagramSocket getDatagramSocket(int port) {
......@@ -137,31 +188,24 @@ public class WatchTableServiceImpl implements WatchTableService {
}
public void run() {
running = true;
while (running) {
if (socket == null) {
log.warn("WatchTableListener:socket is null, try to initial it");
socket = getDatagramSocket(PORT);
if (socket == null) break;
}
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
consumer.accept(received);
} catch (Exception e) {
log.error(e.getMessage());
}
if (socket == null) {
log.warn("WatchTableListener:socket is null, try to initial it");
socket = getDatagramSocket(PORT);
if (socket == null) return;
}
if (socket != null) {
socket.close();
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
consumer.accept(received);
} catch (Exception e) {
log.error(e.getMessage());
}
}
public void stopThread() {
running = false;
public ExecutorService getExecutor() {
return executor;
}
}
}
......@@ -28,10 +28,10 @@ class WatchTableServiceImplTest {
@Test
void getDestination() {
String tableName = "`default_catalog`.`default_database`.`Orders`";
String result = WatchTableServiceImpl.getDestination(123, tableName);
assertEquals("/topic/table/123/`default_catalog`.`default_database`.`print_Orders`", result);
String result = WatchTableServiceImpl.getDestination(tableName);
assertEquals("/topic/table/`default_catalog`.`default_database`.`print_Orders`", result);
result = WatchTableServiceImpl.getDestination(123, "Orders");
assertEquals("/topic/table/123/`default_catalog`.`default_database`.`print_Orders`", result);
result = WatchTableServiceImpl.getDestination("Orders");
assertEquals("/topic/table/`default_catalog`.`default_database`.`print_Orders`", result);
}
}
......@@ -190,7 +190,7 @@ export const dva = {
const patch = (oldRoutes: any, routes: SysMenu[]) => {
oldRoutes[1].routes = oldRoutes[1].routes.map(
(route: { routes: { path: any; element: JSX.Element }[]; path: string }) => {
if (route.routes && route.routes.length) {
if (route.routes?.length) {
const redirect = routes.filter((r) => r.path.startsWith(route.path));
if (redirect.length) {
route.routes.shift();
......
......@@ -172,8 +172,8 @@ export default {
'global.success': 'Success',
'global.getdata.tips': 'Get Data',
'global.notifaction.iknow': 'I understand',
'global.notifaction.full-error': 'Complete error message',
'global.notification.iknow': 'I understand',
'global.notification.full-error': 'Complete error message',
'global.item': 'Pieces',
'global.bout': 'Times',
......
......@@ -1039,11 +1039,11 @@ export default {
'pages.datastudio.editor.execute.warn':
'The execution mode of this task is [{type}], which does not support SQL query, please save it manually and use the button on the right - job submission',
'pages.datastudio.editor.submiting': 'The new task [{jobName}] is executing',
'pages.datastudio.editor.submitting': 'The new task [{jobName}] is executing',
'pages.datastudio.editor.exec.success': 'Execution succeeded',
'pages.datastudio.editor.exec.error': 'Task [jobName}] execution failed',
'pages.datastudio.editor.async.submit': 'Submit jobs asynchronously',
'pages.datastudio.editor.async.submiting': 'The task [{jobName}] is submitting asynchronously',
'pages.datastudio.editor.async.submitting': 'The task [{jobName}] is submitting asynchronously',
'pages.datastudio.editor.async.submitConfirm':
'Are you sure to asynchronously submit the job [{jobName}] to its configured cluster? Please make sure your work has been saved! ',
'pages.datastudio.editor.async.success': 'Asynchronous submission succeeded',
......
......@@ -169,8 +169,8 @@ export default {
'global.success': '成功',
'global.getdata.tips': '获取数据',
'global.notifaction.iknow': '我知道了',
'global.notifaction.full-error': '完整错误信息',
'global.notification.iknow': '我知道了',
'global.notification.full-error': '完整错误信息',
'global.item': '个',
'global.bout': '次',
......
......@@ -1009,11 +1009,11 @@ export default {
'pages.datastudio.editor.execute.warn':
'该任务执行模式为【{type}】,不支持 SQL 查询,请手动保存后使用右侧按钮——作业提交',
'pages.datastudio.editor.submiting': '新任务【{jobName}】正在执行',
'pages.datastudio.editor.submitting': '新任务【{jobName}】正在执行',
'pages.datastudio.editor.exec.success': '执行成功',
'pages.datastudio.editor.exec.error': '任务【{jobName}】执行失败',
'pages.datastudio.editor.async.submit': '异步提交作业',
'pages.datastudio.editor.async.submiting': '任务【{jobName}】正在异步提交',
'pages.datastudio.editor.async.submitting': '任务【{jobName}】正在异步提交',
'pages.datastudio.editor.async.submitConfirm':
'确定异步提交作业【{jobName}】到其配置的集群吗?请确认您的作业是否已经被保存!',
'pages.datastudio.editor.async.success': '异步提交成功',
......
import { getCurrentData } from '@/pages/DataStudio/function';
import { StateType } from '@/pages/DataStudio/model';
import { getData, getSseData, postAll } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints';
import { connect } from '@@/exports';
import { Modal, Select, Tabs } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import { ReactNode, useEffect, useState } from 'react';
export async function getWatchTables(statement: string) {
return postAll('api/statement/getWatchTables', { statement });
}
/*--- Clear Console ---*/
export function clearConsole() {
return getData('api/process/clearConsole', {});
}
const DataPage = (props: any) => {
const { height, title } = props;
const [consoleInfo, setConsoleInfo] = useState<string>('');
const [eventSource, setEventSource] = useState<EventSource>();
const [tableName, setTableName] = useState<string>('');
const onSearchName = (value: string) => {
if (!value) return;
eventSource?.close();
const eventSourceNew = getSseData(API_CONSTANTS.FLINK_TABLE_DATA + '?table=' + value);
eventSourceNew.onmessage = (event: any) => {
setConsoleInfo((preConsoleInfo) => preConsoleInfo + '\n' + event);
};
setEventSource(eventSourceNew);
setTableName(value);
};
useEffect(() => {
onSearchName(title);
return eventSource?.close();
}, []);
return (
<div style={{ width: '100%' }}>
<TextArea value={consoleInfo} />
</div>
);
};
const TableData = (props: any) => {
const { statement } = props;
const [panes, setPanes] = useState<{ label: string; key: string; children: ReactNode }[]>([]);
const addTab = async () => {
let title: string;
if (!statement) return;
const result = await getWatchTables(statement);
let tables: [string] = result.datas;
Modal.confirm({
title: 'Please select table name',
content: (
<Select
defaultValue=''
style={{ width: 120 }}
onChange={(e) => (title = e)}
options={tables.map((table) => ({ value: table }))}
/>
),
onOk() {
const activeKey = `${panes.length + 1}`;
const newPanes = [...panes];
newPanes.push({
label: title,
children: <DataPage title={title} />,
key: activeKey
});
setPanes(newPanes);
}
});
};
return (
<Tabs
type='editable-card'
onEdit={(targetKey, action) => {
if (action === 'add') {
addTab();
} else if (action === 'remove') {
const newPanes = panes.filter((pane) => pane.key !== targetKey);
setPanes(newPanes);
}
}}
items={panes}
/>
);
};
export default connect(({ Studio }: { Studio: StateType }) => ({
height: Studio.bottomContainer.height,
statement: getCurrentData(Studio.tabs.panes, Studio.tabs.activeKey)?.statement
}))(TableData);
......@@ -17,12 +17,7 @@
*
*/
import { FlexCenterDiv } from '@/components/StyledComponents';
import {
getCurrentData,
getCurrentTab,
isDataStudioTabsItemType,
mapDispatchToProps
} from '@/pages/DataStudio/function';
import { getCurrentData, getCurrentTab, mapDispatchToProps } from '@/pages/DataStudio/function';
import Explain from '@/pages/DataStudio/HeaderContainer/Explain';
import FlinkGraph from '@/pages/DataStudio/HeaderContainer/FlinkGraph';
import { buildGraphData } from '@/pages/DataStudio/HeaderContainer/FlinkGraph/function';
......@@ -37,7 +32,14 @@ import {
isSql,
offLineTask
} from '@/pages/DataStudio/HeaderContainer/service';
import { DataStudioTabsItemType, StateType, TabsPageType, VIEW } from '@/pages/DataStudio/model';
import {
DataStudioParams,
DataStudioTabsItemType,
StateType,
TabsPageType,
TaskDataType,
VIEW
} from '@/pages/DataStudio/model';
import { handlePutDataJson } from '@/services/BusinessCrud';
import { l } from '@/utils/intl';
import { ErrorNotification } from '@/utils/messages';
......@@ -64,6 +66,7 @@ const headerStyle: React.CSSProperties = {
fontSize: '16px',
padding: '4px 10px'
};
type ButtonRoute = {
icon: React.ReactNode;
title: string;
......@@ -87,7 +90,9 @@ const HeaderContainer = (props: any) => {
const [messageApi, messageContextHolder] = message.useMessage();
const handlerStop = () => {
const current = getCurrentData(panes, activeKey);
if (!current) return;
if (!current) {
return;
}
modal.confirm({
title: l('pages.datastudio.editor.stop.job'),
......@@ -99,18 +104,15 @@ const HeaderContainer = (props: any) => {
onOk: async () => {
offLineTask(l('pages.datastudio.editor.stop.job'), current.id, 'canceljob').then(
(result) => {
const currentTab = getCurrentTab(panes, activeKey);
if (isDataStudioTabsItemType(currentTab)) {
currentTab.params.taskData.jobInstanceId = 0;
}
(
getCurrentTab(panes, activeKey)?.params as DataStudioParams
).taskData.jobInstanceId = 0;
saveTabs({ ...props.tabs });
}
);
}
});
};
const handlerExec = () => {
const current = getCurrentData(panes, activeKey);
if (!current) {
......@@ -122,15 +124,16 @@ const HeaderContainer = (props: any) => {
return;
}
const param: any = {
const param: TaskDataType = {
...current,
jobName: current.name,
taskId: current.id
};
const taskKey = Math.random() * 1000 + '';
notificationApi.success({
message: l('pages.datastudio.editor.submiting', '', {
message: l('pages.datastudio.editor.submitting', '', {
jobName: param.name
}),
description: param.statement.substring(0, 40) + '...',
......@@ -139,7 +142,7 @@ const HeaderContainer = (props: any) => {
icon: <SmileOutlined style={{ color: '#108ee9' }} />
});
executeSql(l('pages.datastudio.editor.submiting', '', { jobName: param.name }), param).then(
executeSql(l('pages.datastudio.editor.submitting', '', { jobName: param.name }), param).then(
(res) => {
notificationApi.destroy(taskKey);
if (!res) {
......@@ -153,10 +156,8 @@ const HeaderContainer = (props: any) => {
});
if (res.datas.success) {
messageApi.success(l('pages.datastudio.editor.exec.success'));
const currentTab = getCurrentTab(panes, activeKey);
if (isDataStudioTabsItemType(currentTab)) {
currentTab.params.taskData.jobInstanceId = res.datas.jobInstanceId;
}
(getCurrentTab(panes, activeKey)?.params as DataStudioParams).taskData.jobInstanceId =
res.datas.jobInstanceId;
saveTabs({ ...props.tabs });
} else {
ErrorNotification(
......
import { TaskDataType } from '@/pages/DataStudio/model';
import { postAll } from '@/services/api';
import { handleGetOption, handleOption } from '@/services/BusinessCrud';
import { DIALECT, RUN_MODE } from '@/services/constants';
......@@ -8,7 +9,7 @@ export async function explainSql(params: any) {
export async function getJobPlan(title: string, params: any) {
return handleOption('/api/studio/getJobPlan', title, params);
}
export async function executeSql(title: string, params: any) {
export async function executeSql(title: string, params: TaskDataType) {
return handleOption('/api/studio/executeSql', title, params);
}
export function offLineTask(title: string, id: number, type: string) {
......
......@@ -27,7 +27,6 @@ import { DefaultOptionType } from 'antd/es/select';
/**
* build job run model
* @returns {DefaultOptionType[]}
*/
export const buildRunModelOptions = () => {
let resultReturn: DefaultOptionType[] = [];
......@@ -71,8 +70,6 @@ export const buildRunModelOptions = () => {
/**
* build cluster options
* @param {Cluster.Instance[]} sessionCluster
* @returns {any[]}
*/
export const buildClusterOptions = (sessionCluster: Cluster.Instance[]) => {
const sessionClusterOptions: DefaultOptionType[] = [];
......@@ -95,9 +92,6 @@ export const buildClusterOptions = (sessionCluster: Cluster.Instance[]) => {
/**
* build cluster config options
* @param current
* @param {Cluster.Config[]} clusterConfiguration
* @returns {any[]}
*/
export const buildClusterConfigOptions = (current: any, clusterConfiguration: Cluster.Config[]) => {
const clusterConfigOptions: DefaultOptionType[] = [];
......@@ -122,8 +116,6 @@ export const buildClusterConfigOptions = (current: any, clusterConfiguration: Cl
/**
* build env options
* @param {any[]} env
* @returns {JSX.Element[]}
*/
export const buildEnvOptions = (env: any[]) => {
const envList: DefaultOptionType[] = [
......@@ -154,8 +146,6 @@ export const buildEnvOptions = (env: any[]) => {
/**
* build job alert groups
* @param {Alert.AlertGroup[]} alertGroups
* @returns {JSX.Element[]}
*/
export const buildAlertGroupOptions = (alertGroups: Alert.AlertGroup[]) => {
const alertGroupOptions: DefaultOptionType[] = [
......
......@@ -18,7 +18,11 @@
*/
import { SAVE_POINT_TYPE } from '@/pages/DataStudio/constants';
import { getCurrentData } from '@/pages/DataStudio/function';
import {
getCurrentData,
getCurrentTab,
isDataStudioTabsItemType
} from '@/pages/DataStudio/function';
import { SessionType, StateType, STUDIO_MODEL } from '@/pages/DataStudio/model';
import {
buildAlertGroupOptions,
......@@ -58,6 +62,8 @@ const JobConfig = (props: any) => {
} = props;
const current = getCurrentData(panes, activeKey);
if (!current) return;
const currentSession: SessionType = {
connectors: [],
sessionConfig: {
......@@ -68,15 +74,16 @@ const JobConfig = (props: any) => {
const [form] = useForm();
form.setFieldsValue(current);
const onValuesChange = (change: any, all: any) => {
for (let i = 0; i < panes.length; i++) {
if (panes[i].key === activeKey) {
for (let key in change) {
panes[i].params.taskData[key] = all[key];
}
break;
}
const onValuesChange = (change: { [key in string]: string }, all: any) => {
const pane = getCurrentTab(panes, activeKey);
if (!isDataStudioTabsItemType(pane)) {
return;
}
Object.keys(change).forEach((key) => {
pane.params.taskData[key] = change[key];
});
dispatch({
type: STUDIO_MODEL.saveTabs,
payload: { ...props.tabs }
......@@ -119,7 +126,7 @@ const JobConfig = (props: any) => {
current.type === RUN_MODE.STANDALONE) && (
<>
{currentSession.session ? (
currentSession.sessionConfig && currentSession.sessionConfig.clusterId ? (
currentSession.sessionConfig?.clusterId ? (
<>
<Badge status='success' />
<Text type='success'>{currentSession.sessionConfig.clusterName}</Text>
......
......@@ -17,7 +17,11 @@
*
*/
import { getCurrentData } from '@/pages/DataStudio/function';
import {
getCurrentData,
getCurrentTab,
isDataStudioTabsItemType
} from '@/pages/DataStudio/function';
import { StateType, STUDIO_MODEL } from '@/pages/DataStudio/model';
import { l } from '@/utils/intl';
import { Col, Descriptions, Form, Row } from 'antd';
......@@ -32,17 +36,19 @@ const JobInfo = (props: any) => {
tabs: { panes, activeKey }
} = props;
const current = getCurrentData(panes, activeKey);
const [form] = useForm();
form.setFieldsValue(current);
const onValuesChange = (change: any, all: any) => {
for (let i = 0; i < panes.length; i++) {
if (panes[i].key === activeKey) {
for (const key in change) {
panes[i].params.taskData[key] = all[key];
}
break;
}
const pane = getCurrentTab(panes, activeKey);
if (!isDataStudioTabsItemType(pane)) {
return;
}
Object.keys(change).forEach((key) => {
pane.params.taskData[key] = change[key];
});
dispatch({
type: STUDIO_MODEL.saveTabs,
payload: { ...props.tabs }
......@@ -53,22 +59,22 @@ const JobInfo = (props: any) => {
<div style={{ paddingInline: 8 }}>
<Descriptions bordered size='small' column={1}>
<Descriptions.Item label={l('pages.datastudio.label.jobInfo.id')}>
<Paragraph copyable>{current.id}</Paragraph>
<Paragraph copyable>{current?.id}</Paragraph>
</Descriptions.Item>
<Descriptions.Item label={l('pages.datastudio.label.jobInfo.name')}>
{current.name}
{current?.name}
</Descriptions.Item>
<Descriptions.Item label={l('pages.datastudio.label.jobInfo.dialect')}>
{current.dialect}
{current?.dialect}
</Descriptions.Item>
<Descriptions.Item label={l('pages.datastudio.label.jobInfo.versionId')}>
{current.versionId}
{current?.versionId}
</Descriptions.Item>
<Descriptions.Item label={l('global.table.createTime')}>
{current.createTime}
{current?.createTime}
</Descriptions.Item>
<Descriptions.Item label={l('global.table.updateTime')}>
{current.updateTime}
{current?.updateTime}
</Descriptions.Item>
</Descriptions>
<Form
......
......@@ -24,7 +24,8 @@ import {
MetadataTabsItemType,
STUDIO_MODEL,
TabsItemType,
TabsPageType
TabsPageType,
TaskDataType
} from '@/pages/DataStudio/model';
import { Cluster, DataSources } from '@/types/RegCenter/data';
import { Dispatch } from '@@/plugin-dva/types';
......@@ -146,9 +147,9 @@ export function getCurrentTab(
}
export const getCurrentData = (
panes: DataStudioTabsItemType[],
panes: TabsItemType[],
activeKey: string
): Record<string, any> | undefined => {
): TaskDataType | undefined => {
const item = getCurrentTab(panes, activeKey);
if (isDataStudioTabsItemType(item)) {
return item.params.taskData;
......
......@@ -29,7 +29,13 @@ import LeftContainer from '@/pages/DataStudio/LeftContainer';
import { getDataBase } from '@/pages/DataStudio/LeftContainer/MetaData/service';
import { getTaskData, getTaskDetails } from '@/pages/DataStudio/LeftContainer/Project/service';
import MiddleContainer from '@/pages/DataStudio/MiddleContainer';
import { StateType, TabsItemType, TabsPageType, VIEW } from '@/pages/DataStudio/model';
import {
StateType,
TabsItemType,
TabsPageType,
TaskDataType,
VIEW
} from '@/pages/DataStudio/model';
import RightContainer from '@/pages/DataStudio/RightContainer';
import {
getClusterConfigurationData,
......@@ -86,7 +92,7 @@ const DataStudio = (props: any) => {
const { token } = useToken();
const themeValue = useThemeValue();
const [isModalUpdateTabContentOpen, setIsModalUpdateTabContentOpen] = useState(false);
const [newTabData, setNewTabData] = useState({});
const [newTabData, setNewTabData] = useState<TaskDataType>();
const app = getDvaApp(); // 获取dva的实例
const persist = app._store.persist;
const bottomHeight = bottomContainer.selectKey === '' ? 0 : bottomContainer.height;
......@@ -164,11 +170,17 @@ const DataStudio = (props: any) => {
const params = currentTab.params;
const res = await getTaskDetails(params.taskId);
const changed = Object.keys(res).some(
(key) =>
res[key] !== params.taskData[key] ||
JSON.stringify(res[key]) !== JSON.stringify(params.taskData[key])
);
const changed = Object.keys(params.taskData).some((key) => {
// ignore this property
if (['updateTime', 'createTime', 'jobInstanceId'].includes(key)) {
return false;
}
if (JSON.stringify(res[key]) !== JSON.stringify(params.taskData[key])) {
console.log('key', key, res[key], params.taskData[key]);
return true;
}
});
if (changed) {
setIsModalUpdateTabContentOpen(true);
......@@ -204,6 +216,8 @@ const DataStudio = (props: any) => {
return;
}
if (!newTabData) return;
currentTab.params.taskData = newTabData;
saveTabs({ ...tabs });
setIsModalUpdateTabContentOpen(false);
......@@ -303,8 +317,8 @@ const DataStudio = (props: any) => {
mode='inline'
style={{
height: '100%',
borderInlineStart: '1px solid ' + themeValue.borderColor,
borderBlockStart: '1px solid ' + themeValue.borderColor
borderInlineStart: `1px solid ${themeValue.borderColor}`,
borderBlockStart: `1px solid ${themeValue.borderColor}`
}}
items={RightSide.filter((x) => {
if (!x.isShow) {
......
......@@ -96,9 +96,18 @@ export type MetadataParams = {
// eslint-disable-next-line @typescript-eslint/ban-types
tableInfo: {};
};
export type TaskDataBaseType = {
id: number;
name: string;
statement: string;
};
export type TaskDataType = TaskDataBaseType & Record<string, any>;
export type DataStudioParams = {
taskId: number;
taskData: Record<string, any>;
taskData: TaskDataType;
resultData: Record<string, any>;
};
......
......@@ -20,6 +20,7 @@
import { CircleButtonProps } from '@/components/CallBackButton/CircleBtn';
import Console from '@/pages/DataStudio/BottomContainer/Console';
import Result from '@/pages/DataStudio/BottomContainer/Result';
import TableData from '@/pages/DataStudio/BottomContainer/TableData';
import MetaData from '@/pages/DataStudio/LeftContainer/MetaData';
import Project from '@/pages/DataStudio/LeftContainer/Project';
import { TabsPageSubType, TabsPageType } from '@/pages/DataStudio/model';
......@@ -148,7 +149,8 @@ export const LeftBottomSide = [
{
key: 'menu.datastudio.table-data',
icon: <TableOutlined />,
label: l('menu.datastudio.table-data')
label: l('menu.datastudio.table-data'),
children: <TableData />
},
{
key: 'menu.datastudio.tool',
......
......@@ -174,24 +174,22 @@ const CheckpointTable = (props: JobProps) => {
];
return (
<>
<ProTable<CheckPointsDetailInfo>
columns={columns}
style={{ width: '100%' }}
dataSource={checkpoints?.history}
onDataSourceChange={(_) => actionRef.current?.reload()}
actionRef={actionRef}
rowKey='id'
pagination={{
defaultPageSize: 10,
showSizeChanger: true
}}
toolBarRender={false}
dateFormatter='string'
search={false}
size='small'
/>
</>
<ProTable<CheckPointsDetailInfo>
columns={columns}
style={{ width: '100%' }}
dataSource={checkpoints?.history}
onDataSourceChange={(_) => actionRef.current?.reload()}
actionRef={actionRef}
rowKey='id'
pagination={{
defaultPageSize: 10,
showSizeChanger: true
}}
toolBarRender={false}
dateFormatter='string'
search={false}
size='small'
/>
);
};
......
......@@ -68,27 +68,25 @@ const SavepointTable = (props: JobProps) => {
];
return (
<>
<ProTable<SavePoint>
columns={columns}
style={{ width: '100%' }}
request={(params, sorter, filter) =>
queryList(API_CONSTANTS.GET_SAVEPOINTS, {
...params,
sorter,
filter: { taskId: [jobDetail?.instance.taskId] }
})
}
actionRef={actionRef}
toolBarRender={false}
rowKey='id'
pagination={{
pageSize: 10
}}
search={false}
size='small'
/>
</>
<ProTable<SavePoint>
columns={columns}
style={{ width: '100%' }}
request={(params, sorter, filter) =>
queryList(API_CONSTANTS.GET_SAVEPOINTS, {
...params,
sorter,
filter: { taskId: [jobDetail?.instance.taskId] }
})
}
actionRef={actionRef}
toolBarRender={false}
rowKey='id'
pagination={{
pageSize: 10
}}
search={false}
size='small'
/>
);
};
......
......@@ -92,11 +92,7 @@ const ExceptionTab = (props: JobProps) => {
);
};
return (
<>
<ProCard>{renderLogTab()}</ProCard>
</>
);
return <ProCard>{renderLogTab()}</ProCard>;
};
export default ExceptionTab;
......@@ -54,18 +54,16 @@ const JobManagerLogsTab = (props: JobProps) => {
};
return (
<>
<ProCard>
<Tabs
size={'small'}
items={[
{ label: 'Log', key: 'LOG', children: getLog(log) },
{ label: 'Std Out', key: 'STDOUT', children: getLog(stdout) },
{ label: 'Thread Dump', key: 'DUMP', children: getLog(dump) }
]}
/>
</ProCard>
</>
<ProCard>
<Tabs
size={'small'}
items={[
{ label: 'Log', key: 'LOG', children: getLog(log) },
{ label: 'Std Out', key: 'STDOUT', children: getLog(stdout) },
{ label: 'Thread Dump', key: 'DUMP', children: getLog(dump) }
]}
/>
</ProCard>
);
};
......
......@@ -99,11 +99,7 @@ const TaskManagerLogsTab = (props: JobProps) => {
);
};
return (
<>
<ProCard>{renderLogTab()}</ProCard>
</>
);
return <ProCard>{renderLogTab()}</ProCard>;
};
export default TaskManagerLogsTab;
......@@ -70,9 +70,9 @@ const ProjectForm: React.FC<ProjectFormProps> = (props) => {
*/
const getBranchList = async () => {
const values = form.getFieldsValue();
await getDataByParams(API_CONSTANTS.GIT_BRANCH, { ...values }).then((result: any) =>
setBranches(result)
);
await getDataByParams(API_CONSTANTS.GIT_BRANCH, { ...values }).then((result: any) => {
setBranches(result);
});
};
/**
......
......@@ -236,6 +236,7 @@ export enum API_CONSTANTS {
// flink
FLINK_PROXY = '/api/flink',
FLINK_TABLE_DATA = '/api/subscribe/watch',
// resource
RESOURCE_SHOW_TREE = '/api/resource/showByTree',
......
......@@ -57,7 +57,7 @@ export const ErrorNotification = (
const moreBtn =
description.length > 40 ? (
<Button type='primary' danger onClick={() => ErrorModelWithCode(title, description)}>
{l('global.notifaction.full-error')}
{l('global.notification.full-error')}
</Button>
) : (
<></>
......
......@@ -16,10 +16,9 @@
*
*/
// ================================ About Modal Compents ================================
import ErrorShowModal from '@/components/Modal/ErrorModalShow';
import { l } from '@/utils/intl';
import React from 'react';
import { createRoot } from 'react-dom/client';
/**
......@@ -28,7 +27,10 @@ import { createRoot } from 'react-dom/client';
* @param title The title of the modal.
* @param content The content to display in the modal.
*/
export const ErrorModelWithCode = (title: any = l('global.error'), content: string) => {
export const ErrorModelWithCode = (
title: string | React.JSX.Element = l('global.error'),
content: string = ''
) => {
/** Create a new div element to mount the modal. */
const modalRoot = document.createElement('div');
......@@ -45,27 +47,27 @@ export const ErrorModelWithCode = (title: any = l('global.error'), content: stri
);
};
// @ts-ignore
export const createModelTypes = <T extends any>(
target: T
): [{ [K in keyof T['reducers']]: string }, { [K in keyof T['effects']]: string }] => {
type TargetType = typeof target;
interface BaseModeType {
['reducers']: {};
['effects']: {};
['namespace']: string;
}
type MemberType<T extends BaseModeType, U> = U extends 'effects' ? T['effects'] : T['reducers'];
function getModelTypes<T extends BaseModeType>(
target: T,
type: 'effects' | 'reducers'
): { [K in keyof MemberType<T, typeof type>]: string } {
const reducers = Object.keys(target[type]).map((obj: string) => [
obj,
`${target.namespace}/${obj}`
]);
// @ts-ignore
const MODEL_SYNC: { [K in keyof TargetType['reducers']]: string } = Object.fromEntries(
// @ts-ignore
new Map<keyof TargetType['reducers'], string>(
Object.keys(target['reducers']).map((obj: string) => [obj, `${target.namespace}/${obj}`])
)
);
return Object.fromEntries(new Map<keyof (typeof target)[type], string>(reducers));
}
// @ts-ignore
const MODEL_ASYNC: { [K in keyof TargetType['effects']]: string } = Object.fromEntries(
// @ts-ignore
new Map<keyof TargetType['effects'], string>(
Object.keys(target['effects']).map((obj: string) => [obj, `${target.namespace}/${obj}`])
)
);
return [MODEL_SYNC, MODEL_ASYNC];
export const createModelTypes = <T extends BaseModeType>(
target: T
): [{ [K in keyof T['reducers']]: string }, { [K in keyof T['effects']]: string }] => {
return [getModelTypes(target, 'reducers'), getModelTypes(target, 'effects')];
};
......@@ -144,7 +144,7 @@ const StudioMenu = (props: any) => {
const key = current.key;
const taskKey = (Math.random() * 1000) + '';
notification.success({
message: l('pages.datastudio.editor.submiting','',{jobName: param.jobName}),
message: l('pages.datastudio.editor.submitting','',{jobName: param.jobName}),
description: param.statement.substring(0, 40) + '...',
duration: null,
key: taskKey,
......@@ -186,7 +186,7 @@ const StudioMenu = (props: any) => {
id: current.task.id,
};
notification.success({
message: l('pages.datastudio.editor.async.submiting','',{jobName: current.task.jobName}),
message: l('pages.datastudio.editor.async.submitting','',{jobName: current.task.jobName}),
description: current.task.statement,
duration: null,
key: taskKey,
......
......@@ -92,11 +92,11 @@ export default {
'pages.searchTable.batchApproval': 'Batch Approval',
'pages.datastudio.editor.execute.warn': 'The execution mode of this task is [{type}], which does not support SQL query, please save it manually and use the button on the right - job submission',
'pages.datastudio.editor.submiting': 'The new task [{jobName}] is executing',
'pages.datastudio.editor.submitting': 'The new task [{jobName}] is executing',
'pages.datastudio.editor.exec.success': 'Execution succeeded',
'pages.datastudio.editor.exec.error': 'Execution failed',
'pages.datastudio.editor.async.submit': 'Submit jobs asynchronously',
'pages.datastudio.editor.async.submiting': 'The task [{jobName}] is submitting asynchronously',
'pages.datastudio.editor.async.submitting': 'The task [{jobName}] is submitting asynchronously',
'pages.datastudio.editor.async.submitConfirm': 'Are you sure to asynchronously submit the job [{jobName}] to its configured cluster? Please make sure your work has been saved! ',
'pages.datastudio.editor.async.success': 'Asynchronous submission succeeded',
'pages.datastudio.editor.async.error': 'Asynchronous submission failed',
......
......@@ -93,11 +93,11 @@ export default {
'pages.searchTable.batchApproval': '批量审批',
'pages.datastudio.editor.execute.warn': '该任务执行模式为【{type}】,不支持 SQL 查询,请手动保存后使用右侧按钮——作业提交',
'pages.datastudio.editor.submiting': '新任务【{jobName}】正在执行',
'pages.datastudio.editor.submitting': '新任务【{jobName}】正在执行',
'pages.datastudio.editor.exec.success': '执行成功',
'pages.datastudio.editor.exec.error': '执行失败',
'pages.datastudio.editor.async.submit': '异步提交作业',
'pages.datastudio.editor.async.submiting': '任务【{jobName}】正在异步提交',
'pages.datastudio.editor.async.submitting': '任务【{jobName}】正在异步提交',
'pages.datastudio.editor.async.submitConfirm': '确定异步提交作业【{jobName}】到其配置的集群吗?请确认您的作业是否已经被保存!',
'pages.datastudio.editor.async.success': '异步提交成功',
'pages.datastudio.editor.async.error': '异步提交失败',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment