Просмотр исходного кода

feat: save response time & test time (#59)

JustSong 2 лет назад
Родитель
Сommit
225176aae9
3 измененных файлов с 46 добавлено и 13 удалено
  1. 3 2
      controller/channel.go
  2. 12 1
      model/channel.go
  3. 31 10
      web/src/components/ChannelsTable.js

+ 3 - 2
controller/channel.go

@@ -89,7 +89,6 @@ func AddChannel(c *gin.Context) {
 		return
 		return
 	}
 	}
 	channel.CreatedTime = common.GetTimestamp()
 	channel.CreatedTime = common.GetTimestamp()
-	channel.AccessedTime = common.GetTimestamp()
 	keys := strings.Split(channel.Key, "\n")
 	keys := strings.Split(channel.Key, "\n")
 	channels := make([]model.Channel, 0)
 	channels := make([]model.Channel, 0)
 	for _, key := range keys {
 	for _, key := range keys {
@@ -236,7 +235,9 @@ func TestChannel(c *gin.Context) {
 	tik := time.Now()
 	tik := time.Now()
 	err = testChannel(channel, chatRequest)
 	err = testChannel(channel, chatRequest)
 	tok := time.Now()
 	tok := time.Now()
-	consumedTime := float64(tok.Sub(tik).Milliseconds()) / 1000.0
+	milliseconds := tok.Sub(tik).Milliseconds()
+	go channel.UpdateResponseTime(milliseconds)
+	consumedTime := float64(milliseconds) / 1000.0
 	if err != nil {
 	if err != nil {
 		c.JSON(http.StatusOK, gin.H{
 		c.JSON(http.StatusOK, gin.H{
 			"success": false,
 			"success": false,

+ 12 - 1
model/channel.go

@@ -13,7 +13,8 @@ type Channel struct {
 	Name         string `json:"name" gorm:"index"`
 	Name         string `json:"name" gorm:"index"`
 	Weight       int    `json:"weight"`
 	Weight       int    `json:"weight"`
 	CreatedTime  int64  `json:"created_time" gorm:"bigint"`
 	CreatedTime  int64  `json:"created_time" gorm:"bigint"`
-	AccessedTime int64  `json:"accessed_time" gorm:"bigint"`
+	TestTime     int64  `json:"test_time" gorm:"bigint"`
+	ResponseTime int    `json:"response_time"` // in milliseconds
 	BaseURL      string `json:"base_url" gorm:"column:base_url"`
 	BaseURL      string `json:"base_url" gorm:"column:base_url"`
 	Other        string `json:"other"`
 	Other        string `json:"other"`
 }
 }
@@ -71,6 +72,16 @@ func (channel *Channel) Update() error {
 	return err
 	return err
 }
 }
 
 
+func (channel *Channel) UpdateResponseTime(responseTime int64) {
+	err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
+		TestTime:     common.GetTimestamp(),
+		ResponseTime: int(responseTime),
+	}).Error
+	if err != nil {
+		common.SysError("failed to update response time: " + err.Error())
+	}
+}
+
 func (channel *Channel) Delete() error {
 func (channel *Channel) Delete() error {
 	var err error
 	var err error
 	err = DB.Delete(channel).Error
 	err = DB.Delete(channel).Error

+ 31 - 10
web/src/components/ChannelsTable.js

@@ -1,7 +1,7 @@
 import React, { useEffect, useState } from 'react';
 import React, { useEffect, useState } from 'react';
 import { Button, Form, Label, Pagination, Popup, Table } from 'semantic-ui-react';
 import { Button, Form, Label, Pagination, Popup, Table } from 'semantic-ui-react';
 import { Link } from 'react-router-dom';
 import { Link } from 'react-router-dom';
-import { API, copy, showError, showInfo, showSuccess, timestamp2string } from '../helpers';
+import { API, showError, showInfo, showSuccess, timestamp2string } from '../helpers';
 
 
 import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants';
 import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants';
 
 
@@ -120,6 +120,22 @@ const ChannelsTable = () => {
     }
     }
   };
   };
 
 
+  const renderResponseTime = (responseTime) => {
+    let time = responseTime / 1000;
+    time = time.toFixed(2) + " 秒";
+    if (responseTime === 0) {
+      return <Label basic color='grey'>未测试</Label>;
+    } else if (responseTime <= 1000) {
+      return <Label basic color='green'>{time}</Label>;
+    } else if (responseTime <= 3000) {
+      return <Label basic color='olive'>{time}</Label>;
+    } else if (responseTime <= 5000) {
+      return <Label basic color='yellow'>{time}</Label>;
+    } else {
+      return <Label basic color='red'>{time}</Label>;
+    }
+  };
+
   const searchChannels = async () => {
   const searchChannels = async () => {
     if (searchKeyword === '') {
     if (searchKeyword === '') {
       // if keyword is blank, load files instead.
       // if keyword is blank, load files instead.
@@ -139,15 +155,20 @@ const ChannelsTable = () => {
     setSearching(false);
     setSearching(false);
   };
   };
 
 
-  const testChannel = async (id, name) => {
+  const testChannel = async (id, name, idx) => {
     const res = await API.get(`/api/channel/test/${id}/`);
     const res = await API.get(`/api/channel/test/${id}/`);
     const { success, message, time } = res.data;
     const { success, message, time } = res.data;
     if (success) {
     if (success) {
+      let newChannels = [...channels];
+      let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
+      newChannels[realIdx].response_time = time * 1000;
+      newChannels[realIdx].test_time = Date.now() / 1000;
+      setChannels(newChannels);
       showInfo(`通道 ${name} 测试成功,耗时 ${time} 秒。`);
       showInfo(`通道 ${name} 测试成功,耗时 ${time} 秒。`);
     } else {
     } else {
       showError(message);
       showError(message);
     }
     }
-  }
+  };
 
 
   const handleKeywordChange = async (e, { value }) => {
   const handleKeywordChange = async (e, { value }) => {
     setSearchKeyword(value.trim());
     setSearchKeyword(value.trim());
@@ -219,18 +240,18 @@ const ChannelsTable = () => {
             <Table.HeaderCell
             <Table.HeaderCell
               style={{ cursor: 'pointer' }}
               style={{ cursor: 'pointer' }}
               onClick={() => {
               onClick={() => {
-                sortChannel('created_time');
+                sortChannel('response_time');
               }}
               }}
             >
             >
-              创建时间
+              响应时间
             </Table.HeaderCell>
             </Table.HeaderCell>
             <Table.HeaderCell
             <Table.HeaderCell
               style={{ cursor: 'pointer' }}
               style={{ cursor: 'pointer' }}
               onClick={() => {
               onClick={() => {
-                sortChannel('accessed_time');
+                sortChannel('test_time');
               }}
               }}
             >
             >
-              访问时间
+              测试时间
             </Table.HeaderCell>
             </Table.HeaderCell>
             <Table.HeaderCell>操作</Table.HeaderCell>
             <Table.HeaderCell>操作</Table.HeaderCell>
           </Table.Row>
           </Table.Row>
@@ -250,15 +271,15 @@ const ChannelsTable = () => {
                   <Table.Cell>{channel.name ? channel.name : '无'}</Table.Cell>
                   <Table.Cell>{channel.name ? channel.name : '无'}</Table.Cell>
                   <Table.Cell>{renderType(channel.type)}</Table.Cell>
                   <Table.Cell>{renderType(channel.type)}</Table.Cell>
                   <Table.Cell>{renderStatus(channel.status)}</Table.Cell>
                   <Table.Cell>{renderStatus(channel.status)}</Table.Cell>
-                  <Table.Cell>{renderTimestamp(channel.created_time)}</Table.Cell>
-                  <Table.Cell>{renderTimestamp(channel.accessed_time)}</Table.Cell>
+                  <Table.Cell>{renderResponseTime(channel.response_time)}</Table.Cell>
+                  <Table.Cell>{channel.test_time ? renderTimestamp(channel.test_time) : "未测试"}</Table.Cell>
                   <Table.Cell>
                   <Table.Cell>
                     <div>
                     <div>
                       <Button
                       <Button
                         size={'small'}
                         size={'small'}
                         positive
                         positive
                         onClick={() => {
                         onClick={() => {
-                          testChannel(channel.id, channel.name);
+                          testChannel(channel.id, channel.name, idx);
                         }}
                         }}
                       >
                       >
                         测试
                         测试