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