Unverified Commit 7f78c24a authored by Licho's avatar Licho Committed by GitHub

Print table refactor to sse (#2277)

* 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 * refactor Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * refactor * refactor: rename to print table * refactor: could recevie data * refactor: resize table height * Spotless Apply --------- Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com>
parent fd94c922
......@@ -20,7 +20,7 @@
package org.dinky.controller;
import org.dinky.data.result.Result;
import org.dinky.service.WatchTableService;
import org.dinky.service.PrintTableService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -35,23 +35,23 @@ import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
@RestController
@Api(tags = "Watch Table Controller")
@Api(tags = "Print Table Controller")
@AllArgsConstructor
@RequestMapping("/api")
public class WatchTableController {
public class PrintTableController {
private final WatchTableService watchTableService;
private final PrintTableService printTableService;
@GetMapping(value = "/subscribe/watch", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ApiOperation("Subscribe watch table")
@GetMapping(value = "/subscribe/print", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ApiOperation("Subscribe p table")
public SseEmitter subscribe(@RequestParam String table) {
return watchTableService.registerListenEntry(table);
return printTableService.registerListenEntry(table);
}
@PutMapping("/unSubscribe/watch")
@ApiOperation("UnSubscribe watch table")
@PutMapping("/unSubscribe/print")
@ApiOperation("UnSubscribe print table")
public Result<Void> unsubscribe(@RequestParam String table) {
watchTableService.unRegisterListenEntry(table);
printTableService.unRegisterListenEntry(table);
return Result.succeed();
}
}
......@@ -88,14 +88,14 @@ public class StatementController {
return statementService.selectForProTable(para);
}
@PostMapping("/getWatchTables")
@ApiOperation("Get Watch Tables")
@PostMapping("/getPrintTables")
@ApiOperation("Get Print Tables")
@SuppressWarnings("unchecked")
public Result<List<String>> getWatchTables(@RequestBody String statement) {
public Result<List<String>> getPrintTables(@RequestBody String statement) {
try {
Map<String, String> data = objectMapper.readValue(statement, Map.class);
String ss = data.get("statement");
return Result.succeed(statementService.getWatchTables(ss));
return Result.succeed(statementService.getPrintTables(ss));
} catch (Exception e) {
return Result.failed(e.getMessage());
}
......
......@@ -22,6 +22,7 @@ package org.dinky.data.dto;
import org.dinky.data.model.TaskExtConfig;
import org.dinky.job.JobConfig;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
......@@ -64,7 +65,8 @@ public class StudioExecuteDTO extends AbstractStatementDTO {
public JobConfig getJobConfig() {
Map<String, String> parsedConfig = this.configJson.getCustomConfigMaps();
Map<String, String> parsedConfig =
this.configJson == null ? new HashMap<>(0) : this.configJson.getCustomConfigMaps();
return new JobConfig(
type,
......
......@@ -21,7 +21,7 @@ package org.dinky.service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
public interface WatchTableService {
public interface PrintTableService {
SseEmitter registerListenEntry(String table);
void unRegisterListenEntry(String table);
......
......@@ -33,5 +33,5 @@ public interface StatementService extends ISuperService<Statement> {
boolean insert(Statement statement);
List<String> getWatchTables(String statement);
List<String> getPrintTables(String statement);
}
......@@ -19,14 +19,15 @@
package org.dinky.service.impl;
import org.dinky.service.WatchTableService;
import org.dinky.service.PrintTableService;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Collections;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
......@@ -34,8 +35,8 @@ import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
......@@ -43,15 +44,15 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class WatchTableServiceImpl implements WatchTableService {
public class PrintTableServiceImpl implements PrintTableService {
private final Map<String, Set<Target>> registerTableMap = new ConcurrentHashMap<>();
private static final Pattern FULL_TABLE_NAME_PATTERN = Pattern.compile("^`(\\w+)`\\.`(\\w+)`\\.`(\\w+)`$");
public WatchTableServiceImpl() {
WatchTableListener watcher = new WatchTableListener(this::send);
watcher.start();
public PrintTableServiceImpl() {
PrintTableListener printer = new PrintTableListener(this::send);
printer.start();
}
public void send(String message) {
......@@ -59,30 +60,50 @@ public class WatchTableServiceImpl implements WatchTableService {
String[] data = message.split("\n", 2);
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);
}
});
targets.forEach(d -> d.send(data[1], "data"));
}
} catch (MessagingException e) {
log.error(e.toString());
} catch (Exception e) {
log.error("send message failed: {}", e.getMessage());
}
}
@Override
public SseEmitter registerListenEntry(String table) {
SseEmitter emitter = new SseEmitter();
String fullName = getFullTableName(table);
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 {
targets.add(target);
SseEmitter emitter = getSseEmitter(targets, fullName);
Set<Target> newTargets = new HashSet<>();
newTargets.add(Target.of(emitter, destination));
if (targets != null) {
newTargets.addAll(targets);
}
registerTableMap.put(fullName, newTargets);
return emitter;
}
private SseEmitter getSseEmitter(Set<Target> targets, String fullName) {
SseEmitter emitter = new SseEmitter();
emitter.onCompletion(() -> {
log.info(MessageFormat.format("SseEmitter {0} complete", emitter));
Set<Target> remains = targets.stream()
.filter(t -> !t.getEmitter().equals(emitter))
.collect(Collectors.toSet());
registerTableMap.put(fullName, remains);
});
emitter.onError(e -> {
log.error("SseEmitter error: {}", e.getMessage());
emitter.complete();
});
emitter.onTimeout(() -> {
log.debug("SseEmitter timeout: {}", emitter.getTimeout());
emitter.complete();
});
return emitter;
}
......@@ -134,15 +155,13 @@ public class WatchTableServiceImpl implements WatchTableService {
return new Target(destination, emitter);
}
public boolean send(String message, String type) {
public void send(String message, String type) {
try {
SseEmitter.SseEventBuilder sseEventBuilder = SseEmitter.event();
emitter.send(sseEventBuilder.data(message).name("wt_" + type));
return true;
SseEmitter.SseEventBuilder builder =
SseEmitter.event().data(message).name("pt_" + type);
emitter.send(builder);
} catch (Exception e) {
log.error("send message to {} failed: {}", destination, e.getMessage());
emitter.complete();
return false;
log.debug("SseEmitter {}, send message failed: {}", emitter, e.getMessage());
}
}
......@@ -157,9 +176,22 @@ public class WatchTableServiceImpl implements WatchTableService {
public void complete() {
emitter.complete();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Target target = (Target) o;
return Objects.equals(destination, target.destination) && Objects.equals(emitter, target.emitter);
}
@Override
public int hashCode() {
return Objects.hash(destination, emitter);
}
}
public static class WatchTableListener {
public static class PrintTableListener {
private final Consumer<String> consumer;
public static final int PORT = 7125;
......@@ -168,7 +200,7 @@ public class WatchTableServiceImpl implements WatchTableService {
private final ExecutorService executor;
public WatchTableListener(Consumer<String> consumer) {
public PrintTableListener(Consumer<String> consumer) {
this.consumer = consumer;
this.socket = getDatagramSocket(PORT);
executor = Executors.newSingleThreadExecutor();
......@@ -182,25 +214,27 @@ public class WatchTableServiceImpl implements WatchTableService {
try {
return new DatagramSocket(port);
} catch (SocketException e) {
log.error("WatchTableListener:DatagramSocket init failed, port {}: {}", PORT, e.getMessage());
log.error("PrintTableListener:DatagramSocket init failed, port {}: {}", PORT, e.getMessage());
}
return null;
}
public void run() {
if (socket == null) {
log.warn("WatchTableListener:socket is null, try to initial it");
log.warn("PrintTableListener:socket is null, try to initial it");
socket = getDatagramSocket(PORT);
if (socket == null) return;
}
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());
while (true) {
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("print table receive data:" + e.getMessage());
}
}
}
......
......@@ -20,7 +20,7 @@
package org.dinky.service.impl;
import org.dinky.data.model.Statement;
import org.dinky.explainer.watchTable.WatchStatementExplainer;
import org.dinky.explainer.printTable.PrintStatementExplainer;
import org.dinky.mapper.StatementMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.parser.SqlType;
......@@ -48,14 +48,14 @@ public class StatementServiceImpl extends SuperServiceImpl<StatementMapper, Stat
}
@Override
public List<String> getWatchTables(String statement) {
public List<String> getPrintTables(String statement) {
// TODO: 2023/4/7 this function not support variable sql, because, JobManager and executor
// couple function
// and status and task execute.
final String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement));
return Arrays.stream(statements)
.filter(t -> SqlType.WATCH.equals(Operations.getOperationType(t)))
.flatMap(t -> Arrays.stream(WatchStatementExplainer.splitTableNames(t)))
.filter(t -> SqlType.PRINT.equals(Operations.getOperationType(t)))
.flatMap(t -> Arrays.stream(PrintStatementExplainer.splitTableNames(t)))
.collect(Collectors.toList());
}
}
......@@ -23,15 +23,15 @@ import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class WatchTableServiceImplTest {
class PrintTableServiceImplTest {
@Test
void getDestination() {
String tableName = "`default_catalog`.`default_database`.`Orders`";
String result = WatchTableServiceImpl.getDestination(tableName);
String result = PrintTableServiceImpl.getDestination(tableName);
assertEquals("/topic/table/`default_catalog`.`default_database`.`print_Orders`", result);
result = WatchTableServiceImpl.getDestination("Orders");
result = PrintTableServiceImpl.getDestination("Orders");
assertEquals("/topic/table/`default_catalog`.`default_database`.`print_Orders`", result);
}
}
......@@ -29,7 +29,7 @@ import org.dinky.data.result.ExplainResult;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.executor.CustomTableEnvironment;
import org.dinky.executor.Executor;
import org.dinky.explainer.watchTable.WatchStatementExplainer;
import org.dinky.explainer.printTable.PrintStatementExplainer;
import org.dinky.function.data.model.UDF;
import org.dinky.function.util.UDFUtil;
import org.dinky.interceptor.FlinkInterceptor;
......@@ -137,12 +137,12 @@ public class Explainer {
}
} else if (operationType.equals(SqlType.EXECUTE)) {
execute.add(new StatementParam(statement, operationType));
} else if (operationType.equals(SqlType.WATCH)) {
WatchStatementExplainer watchStatementExplainer = new WatchStatementExplainer(statement);
} else if (operationType.equals(SqlType.PRINT)) {
PrintStatementExplainer printStatementExplainer = new PrintStatementExplainer(statement);
String[] tableNames = watchStatementExplainer.getTableNames();
String[] tableNames = printStatementExplainer.getTableNames();
for (String tableName : tableNames) {
trans.add(new StatementParam(WatchStatementExplainer.getCreateStatement(tableName), SqlType.CTAS));
trans.add(new StatementParam(PrintStatementExplainer.getCreateStatement(tableName), SqlType.CTAS));
}
} else {
UDF udf = UDFUtil.toUDF(statement);
......@@ -353,7 +353,7 @@ public class Explainer {
SqlType operationType = Operations.getOperationType(sql);
if (operationType.equals(SqlType.INSERT)) {
lineageRelList.addAll(executor.getLineage(sql));
} else if (!operationType.equals(SqlType.SELECT) && !operationType.equals(SqlType.WATCH)) {
} else if (!operationType.equals(SqlType.SELECT) && !operationType.equals(SqlType.PRINT)) {
executor.executeSql(sql);
}
} catch (Exception e) {
......
......@@ -17,7 +17,7 @@
*
*/
package org.dinky.explainer.watchTable;
package org.dinky.explainer.printTable;
import java.net.InetAddress;
import java.net.UnknownHostException;
......@@ -26,9 +26,9 @@ import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WatchStatementExplainer {
public class PrintStatementExplainer {
public static final String PATTERN_STR = "WATCH (.+)";
public static final String PATTERN_STR = "PRINT (.+)";
public static final Pattern PATTERN = Pattern.compile(PATTERN_STR, Pattern.CASE_INSENSITIVE);
public static final String CREATE_SQL_TEMPLATE = "CREATE TABLE print_{0} WITH (''connector'' = ''printnet'', "
......@@ -38,7 +38,7 @@ public class WatchStatementExplainer {
private final String statement;
public WatchStatementExplainer(String statement) {
public PrintStatementExplainer(String statement) {
this.statement = statement;
}
......
......@@ -17,22 +17,22 @@
*
*/
package org.dinky.explainer.watchTable;
package org.dinky.explainer.printTable;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
class WatchStatementExplainerTest {
class PrintStatementExplainerTest {
@Test
void getTableNames() {
String sql = "watch VersionT";
WatchStatementExplainer watchStatementExplainer = new WatchStatementExplainer(sql);
assertArrayEquals(new String[] {"VersionT"}, watchStatementExplainer.getTableNames());
String sql = "print VersionT";
PrintStatementExplainer printStatementExplainer = new PrintStatementExplainer(sql);
assertArrayEquals(new String[] {"VersionT"}, printStatementExplainer.getTableNames());
sql = "watch VersionT, Buyers, r, rr, vvv";
WatchStatementExplainer wse = new WatchStatementExplainer(sql);
sql = "print VersionT, Buyers, r, rr, vvv";
PrintStatementExplainer wse = new PrintStatementExplainer(sql);
assertArrayEquals(new String[] {"VersionT", "Buyers", "r", "rr", "vvv"}, wse.getTableNames());
}
......
......@@ -59,7 +59,7 @@ public enum SqlType {
ADD_JAR("ADD_JAR", "^ADD\\s+JAR\\s+\\S+"),
ADD("ADD", "^ADD\\s+CUSTOMJAR\\s+\\S+"),
WATCH("WATCH", "^WATCH.*"),
PRINT("PRINT", "^PRINT.*"),
CTAS("CTAS", "^CREATE\\s.*AS\\sSELECT.*$"),
......
......@@ -54,7 +54,7 @@ class SqlTypeTest {
test("EXECUTE...", SqlType.EXECUTE, true);
test("ADD jar ...", SqlType.ADD_JAR, true);
test("ADD customjar ...", SqlType.ADD, true);
test("WATCH...", SqlType.WATCH, true);
test("PRINT...", SqlType.PRINT, true);
String sql = "CREATE TABLE print_OrdersView WITH ('connector' = 'printnet', 'port'='7125',"
+ " 'hostName' = '172.26.16.1', 'sink.parallelism'='1')\n"
......
......@@ -1143,6 +1143,9 @@ export default {
'pages.datastudio.explain.validate.logic.right': 'Logical Right',
'pages.datastudio.explain.validate.logic.error': 'Logical Error',
// print table
'pages.datastudio.print.table.inputTableName': 'Please select table name',
// footer
'pages.datastudio.footer.memDetails': 'Maximum heap size: {max}\nUsed: {used}M',
'pages.datastudio.footer.codeType': 'Code Type: ',
......
......@@ -1107,6 +1107,9 @@ export default {
'pages.datastudio.explain.validate.logic.right': '逻辑正确',
'pages.datastudio.explain.validate.logic.error': '逻辑有误',
// print table
'pages.datastudio.print.table.inputTableName': '请选择表名',
'pages.datastudio.footer.memDetails': '最大堆大小:{max}\n已使用: {used}M',
'pages.datastudio.footer.codeType': '代码类型:',
'pages.datastudio.footer.lineSeparator': '行分隔符:',
......
......@@ -2,14 +2,15 @@ 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 { l } from '@/utils/intl';
import { connect } from '@@/exports';
import { Modal, Select, Tabs } from 'antd';
import TextArea from 'antd/es/input/TextArea';
import { Tab } from 'rc-tabs/lib/interface.d';
import { useEffect, useState } from 'react';
import * as React from 'react';
import { ReactNode, useEffect, useState } from 'react';
export async function getWatchTables(statement: string) {
return postAll('api/statement/getWatchTables', { statement });
export async function getPrintTables(statement: string) {
return postAll('api/statement/getPrintTables', { statement });
}
/*--- Clear Console ---*/
......@@ -18,7 +19,7 @@ export function clearConsole() {
}
const DataPage = (props: any) => {
const { height, title } = props;
const { style, title } = props;
const [consoleInfo, setConsoleInfo] = useState<string>('');
const [eventSource, setEventSource] = useState<EventSource>();
const [tableName, setTableName] = useState<string>('');
......@@ -27,11 +28,14 @@ const DataPage = (props: any) => {
if (!value) return;
eventSource?.close();
const eventSourceNew = getSseData(API_CONSTANTS.FLINK_TABLE_DATA + '?table=' + value);
eventSourceNew.onmessage = (event: any) => {
setConsoleInfo((preConsoleInfo) => preConsoleInfo + '\n' + event);
eventSourceNew.onerror = (event: any) => {
console.log('EventSource failed:', event);
};
eventSourceNew.addEventListener('pt_data', (event: any) => {
setConsoleInfo((preConsoleInfo) => preConsoleInfo + '\n' + event.data);
});
setEventSource(eventSourceNew);
setTableName(value);
};
......@@ -41,60 +45,62 @@ const DataPage = (props: any) => {
return eventSource?.close();
}, []);
return (
<div style={{ width: '100%' }}>
<TextArea value={consoleInfo} />
</div>
);
return <TextArea value={consoleInfo} style={{ width: style.width, height: style.height }} />;
};
const TableData = (props: any) => {
const { statement } = props;
const [panes, setPanes] = useState<Tab[]>([]);
const { statement, height } = props;
const [panes, setPanes] = useState<{ label: string; key: string; children: ReactNode }[]>([]);
const addTab = async () => {
let title: string;
function onOk(title: string) {
const activeKey = `${panes.length + 1}`;
const newPanes = [...panes];
newPanes.push({
label: title,
children: <DataPage title={title} style={{ width: '100%', height: height - 63 }} />,
key: activeKey
});
setPanes(newPanes);
}
const addTab = async () => {
if (!statement) return;
const result = await getWatchTables(statement);
let tables: [string] = result.datas;
const result = await getPrintTables(statement);
const tables: [string] = result.datas;
let title: string;
Modal.confirm({
title: 'Please select table name',
title: l('pages.datastudio.print.table.inputTableName'),
content: (
<Select
defaultValue=''
style={{ width: 120 }}
style={{ width: '90%' }}
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);
onOk(title);
}
});
};
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}
/>
);
const onEdit = (
targetKey: React.MouseEvent | React.KeyboardEvent | string,
action: 'add' | 'remove'
) => {
switch (action) {
case 'add':
addTab();
break;
case 'remove':
const newPanes = panes.filter((pane) => pane.key !== targetKey);
setPanes(newPanes);
break;
}
};
return <Tabs type='editable-card' onEdit={onEdit} items={panes} />;
};
export default connect(({ Studio }: { Studio: StateType }) => ({
......
......@@ -238,7 +238,7 @@ export enum API_CONSTANTS {
// flink
FLINK_PROXY = '/api/flink',
FLINK_TABLE_DATA = '/api/subscribe/watch',
FLINK_TABLE_DATA = '/api/subscribe/print',
// resource
RESOURCE_SHOW_TREE = '/api/resource/showByTree',
......
---
sidebar_position: 5
id: watch_table
title: WATCH TABLE
id: print_table
title: PRINT TABLE
---
WATCH TABLE 实现埋点功能, 可实现在dinky->表数据标签页动态查看运行时各表数据实时内容,语法结构如下:
PRINT TABLE 实现埋点功能, 可实现在dinky->表数据标签页动态查看运行时各表数据实时内容,语法结构如下:
```sql
WATCH tableName
PRINT tableName
```
表可以是source/view, 但不可以是sink表。
```sql
watch Orders;
print Orders;
```
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