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