summaryrefslogtreecommitdiff
path: root/src/api
diff options
context:
space:
mode:
authorHaishan <[email protected]>2019-10-01 00:18:13 +0800
committerHaishan <[email protected]>2019-10-01 00:25:15 +0800
commit5f7cf1efc0e61c2ee70c0af8c5a9c90d85cf6e09 (patch)
treef789f832dd085c2f1a0bf744a728543736baf108 /src/api
parentd7b20c47fd1b0a0fbd5961f895a4df2139c5099f (diff)
feat: support use WebSocket for traffic and logs data fetching
Diffstat (limited to 'src/api')
-rw-r--r--src/api/logs.js31
-rw-r--r--src/api/traffic.js32
2 files changed, 63 insertions, 0 deletions
diff --git a/src/api/logs.js b/src/api/logs.js
index 63804f1..3ba4b6d 100644
--- a/src/api/logs.js
+++ b/src/api/logs.js
@@ -59,7 +59,38 @@ function pump(reader, appendLog) {
const apiConfigSnapshot = {};
let controller;
+function getWsUrl(apiConfig) {
+ const { hostname, port, secret, logLevel } = apiConfig;
+ let qs = '?level=' + logLevel;
+ if (typeof secret === 'string' && secret !== '') {
+ qs += '&token=' + secret;
+ }
+ return `ws://${hostname}:${port}${endpoint}${qs}`;
+}
+
+// 1 OPEN
+// other value CLOSED
+// similar to ws readyState but not the same
+// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
+let wsState;
function fetchLogs(apiConfig, appendLog) {
+ if (fetched || wsState === 1) return;
+ wsState = 1;
+ const url = getWsUrl(apiConfig);
+ const ws = new WebSocket(url);
+ ws.addEventListener('error', function(_ev) {
+ wsState = 3;
+ });
+ ws.addEventListener('close', function(_ev) {
+ wsState = 3;
+ fetchLogsWithFetch(apiConfig, appendLog);
+ });
+ ws.addEventListener('message', function(event) {
+ appendData(event.data, appendLog);
+ });
+}
+
+function fetchLogsWithFetch(apiConfig, appendLog) {
if (
controller &&
(apiConfigSnapshot.hostname !== apiConfig.hostname ||
diff --git a/src/api/traffic.js b/src/api/traffic.js
index 3e1c780..a2a9ccc 100644
--- a/src/api/traffic.js
+++ b/src/api/traffic.js
@@ -70,7 +70,39 @@ function pump(reader) {
});
}
+function getWsUrl(apiConfig) {
+ const { hostname, port, secret } = apiConfig;
+ let qs = '';
+ if (typeof secret === 'string' && secret !== '') {
+ qs += '?token=' + secret;
+ }
+ return `ws://${hostname}:${port}${endpoint}${qs}`;
+}
+
+// 1 OPEN
+// other value CLOSED
+// similar to ws readyState but not the same
+// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
+let wsState;
function fetchData(apiConfig) {
+ if (fetched || wsState === 1) return traffic;
+ wsState = 1;
+ const url = getWsUrl(apiConfig);
+ const ws = new WebSocket(url);
+ ws.addEventListener('error', function(_ev) {
+ wsState = 3;
+ });
+ ws.addEventListener('close', function(_ev) {
+ wsState = 3;
+ fetchDataWithFetch(apiConfig);
+ });
+ ws.addEventListener('message', function(event) {
+ parseAndAppend(event.data);
+ });
+ return traffic;
+}
+
+function fetchDataWithFetch(apiConfig) {
if (fetched) return traffic;
fetched = true;
const { url, init } = getURLAndInit(apiConfig);