优化代码

This commit is contained in:
GoEdgeLab
2023-08-08 16:46:17 +08:00
parent 9ed5fab2a8
commit 7c08239ea1
28 changed files with 71 additions and 87 deletions

View File

@@ -130,6 +130,9 @@ func TestGenerate_EAB(t *testing.T) {
} else {
reg, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
}
if err != nil {
t.Fatal(err)
}
myUser.Registration = reg
request := certificate.ObtainRequest{

View File

@@ -92,13 +92,13 @@ func (this *Request) runDNS() (certData []byte, keyData []byte, err error) {
// 注册用户
var resource = this.task.User.GetRegistration()
if resource != nil {
resource, err = client.Registration.QueryRegistration()
_, err = client.Registration.QueryRegistration()
if err != nil {
return nil, nil, err
}
} else {
if this.task.Provider.RequireEAB {
resource, err := client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
resource, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: this.task.Account.EABKid,
HmacEncoded: this.task.Account.EABKey,
@@ -111,7 +111,7 @@ func (this *Request) runDNS() (certData []byte, keyData []byte, err error) {
return nil, nil, err
}
} else {
resource, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
resource, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
return nil, nil, err
}
@@ -165,13 +165,13 @@ func (this *Request) runHTTP() (certData []byte, keyData []byte, err error) {
// 注册用户
var resource = this.task.User.GetRegistration()
if resource != nil {
resource, err = client.Registration.QueryRegistration()
_, err = client.Registration.QueryRegistration()
if err != nil {
return nil, nil, err
}
} else {
if this.task.Provider.RequireEAB {
resource, err := client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
resource, err = client.Registration.RegisterWithExternalAccountBinding(registration.RegisterEABOptions{
TermsOfServiceAgreed: true,
Kid: this.task.Account.EABKid,
HmacEncoded: this.task.Account.EABKey,
@@ -184,7 +184,7 @@ func (this *Request) runHTTP() (certData []byte, keyData []byte, err error) {
return nil, nil, err
}
} else {
resource, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
resource, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
return nil, nil, err
}

View File

@@ -1,6 +1,7 @@
package models
import (
"context"
"encoding/json"
"github.com/TeaOSLab/EdgeAPI/internal/utils"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
@@ -37,7 +38,7 @@ func (this *APINode) DecodeHTTPS(tx *dbs.Tx, cacheMap *utils.CacheMap) (*serverc
return nil, err
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil, err
}
@@ -55,7 +56,7 @@ func (this *APINode) DecodeHTTPS(tx *dbs.Tx, cacheMap *utils.CacheMap) (*serverc
}
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil, err
}
@@ -135,7 +136,7 @@ func (this *APINode) DecodeRestHTTPS(tx *dbs.Tx, cacheMap *utils.CacheMap) (*ser
return nil, err
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil, err
}
@@ -153,7 +154,7 @@ func (this *APINode) DecodeRestHTTPS(tx *dbs.Tx, cacheMap *utils.CacheMap) (*ser
}
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil, err
}

View File

@@ -232,7 +232,7 @@ Loop:
// CreateHTTPAccessLog 写入单条访问日志
func (this *HTTPAccessLogDAO) CreateHTTPAccessLog(tx *dbs.Tx, dao *HTTPAccessLogDAO, accessLog *pb.HTTPAccessLog) error {
var day = ""
var day string
// 注意:如果你修改了 TimeISO8601 的逻辑,这里也需要同步修改
if len(accessLog.TimeISO8601) > 10 {
day = strings.ReplaceAll(accessLog.TimeISO8601[:10], "-", "")

View File

@@ -373,7 +373,7 @@ func (this *HTTPAccessLogManager) findTableWithoutCache(db *dbs.DB, day string,
var lastInt64Id = types.Int64(lastId)
if accessLogRowsPerTable > 0 && lastInt64Id >= accessLogRowsPerTable {
// create next partial table
var nextTableName = ""
var nextTableName string
if accessLogTableMainReg.MatchString(lastTableName) {
nextTableName = prefix + "_0001"
} else if accessLogTablePartialReg.MatchString(lastTableName) {

View File

@@ -674,6 +674,9 @@ func (this *IPItemDAO) NotifyUpdate(tx *dbs.Tx, itemId int64) error {
}
} else {
clusterIds, err := SharedNodeClusterDAO.FindAllEnabledNodeClusterIds(tx)
if err != nil {
return err
}
for _, clusterId := range clusterIds {
err = SharedNodeTaskDAO.CreateClusterTask(tx, nodeconfigs.NodeRoleNode, clusterId, 0, 0, NodeTaskTypeIPItemChanged)
if err != nil {

View File

@@ -1039,9 +1039,7 @@ func (this *NodeDAO) ComposeNodeConfig(tx *dbs.Tx, nodeId int64, dataMap *shared
if err != nil {
return nil, err
}
for _, clusterServer := range clusterServers {
servers = append(servers, clusterServer)
}
servers = append(servers, clusterServers...)
}
for _, server := range servers {
@@ -1063,7 +1061,7 @@ func (this *NodeDAO) ComposeNodeConfig(tx *dbs.Tx, nodeId int64, dataMap *shared
// TODO 根据用户的不同读取不同的全局设置
var settingCacheKey = "SharedSysSettingDAO:" + systemconfigs.SettingCodeServerGlobalConfig
settingJSONCache, ok := cacheMap.Get(settingCacheKey)
var settingJSON = []byte{}
var settingJSON []byte
if ok {
settingJSON = settingJSONCache.([]byte)
} else {
@@ -2124,7 +2122,7 @@ func (this *NodeDAO) FindParentNodeConfigs(tx *dbs.Tx, nodeId int64, groupId int
var secretHash = fmt.Sprintf("%x", sha256.Sum256([]byte(node.UniqueId+"@"+node.Secret)))
for _, clusterId := range node.AllClusterIds() {
parentNodeConfigs, _ := result[clusterId]
var parentNodeConfigs = result[clusterId]
parentNodeConfigs = append(parentNodeConfigs, &nodeconfigs.ParentNodeConfig{
Id: int64(node.Id),
Addrs: addrStrings,

View File

@@ -70,8 +70,7 @@ func (this *Node) DNSRouteCodesForDomainId(dnsDomainId int64) ([]string, error)
if err != nil {
return nil, err
}
domainRoutes, _ := routes[dnsDomainId]
var domainRoutes = routes[dnsDomainId]
if len(domainRoutes) > 0 {
sort.Strings(domainRoutes)
}

View File

@@ -127,6 +127,9 @@ func (this *RegionCountryDAO) CreateCountry(tx *dbs.Tx, name string, dataId stri
pinyinResult = append(pinyinResult, strings.Join(piece, " "))
}
pinyinJSON, err := json.Marshal([]string{strings.Join(pinyinResult, " ")})
if err != nil {
return 0, err
}
op.Pinyin = pinyinJSON
codes := []string{name}

View File

@@ -1,6 +1,7 @@
package models
import (
"context"
"encoding/json"
"github.com/TeaOSLab/EdgeAPI/internal/remotelogs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
@@ -78,7 +79,7 @@ func (this *Server) DecodeHTTPSPorts() (ports []int) {
if err != nil {
return nil
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil
}
@@ -120,7 +121,7 @@ func (this *Server) DecodeTLSPorts() (ports []int) {
if err != nil {
return nil
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil
}

View File

@@ -701,7 +701,7 @@ func (this *SSLCertDAO) buildDomainSearchingQuery(query *dbs.Query, domains []st
}
// 检测 JSON_OVERLAPS() 函数是否可用
var canJSONOverlaps = false
var canJSONOverlaps bool
_, funcErr := this.Instance.FindCol(0, "SELECT JSON_OVERLAPS('[1]', '[1]')")
canJSONOverlaps = funcErr == nil
if canJSONOverlaps {

View File

@@ -522,16 +522,6 @@ func (this *UserBandwidthStatDAO) sumBytesField(useAvg bool) string {
return "SUM(bytes) AS bytes"
}
func (this *UserBandwidthStatDAO) fixUserStat(stat *UserBandwidthStat, useAvg bool) *UserBandwidthStat {
if stat == nil {
return nil
}
if useAvg {
stat.Bytes = stat.AvgBytes
}
return stat
}
// HasFullData 检查一个月是否完整数据
// 是为了兼容以前数据,以前的表中没有缓存流量、请求数等字段
func (this *UserBandwidthStatDAO) HasFullData(tx *dbs.Tx, userId int64, month string) (bool, error) {

View File

@@ -1,6 +1,7 @@
package models
import (
"context"
"encoding/json"
"github.com/TeaOSLab/EdgeAPI/internal/utils"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
@@ -36,7 +37,7 @@ func (this *UserNode) DecodeHTTPS(cacheMap *utils.CacheMap) (*serverconfigs.HTTP
return nil, err
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil, err
}
@@ -54,7 +55,7 @@ func (this *UserNode) DecodeHTTPS(cacheMap *utils.CacheMap) (*serverconfigs.HTTP
}
}
err = config.Init(nil)
err = config.Init(context.TODO())
if err != nil {
return nil, err
}

View File

@@ -61,10 +61,7 @@ func (this *DomainRecordsCache) WriteDomainRecords(providerId int64, domain stri
return
}
var clonedRecords = []*dnstypes.Record{}
for _, record := range records {
clonedRecords = append(clonedRecords, record)
}
var clonedRecords = append([]*dnstypes.Record{}, records...)
this.domainRecordsMap[domain] = &recordList{
version: version,
updatedAt: time.Now().Unix(),

View File

@@ -18,7 +18,7 @@ func (this *BaseProvider) WrapError(err error, domain string, record *dnstypes.R
return err
}
var fullname = ""
var fullname string
if len(record.Name) == 0 {
fullname = domain
} else {

View File

@@ -19,7 +19,6 @@ func TestAES128CFBMethod_Encrypt(t *testing.T) {
dst = dst[:len(src)]
t.Log("dst:", string(dst))
src = make([]byte, len(src))
src, err = method.Decrypt(dst)
if err != nil {
t.Fatal(err)
@@ -64,7 +63,6 @@ func TestAES128CFBMethod_Encrypt2(t *testing.T) {
for _, dst := range sources {
dst2 := append([]byte{}, dst...)
src2 := make([]byte, len(dst2))
src2, err := method.Decrypt(dst2)
if err != nil {
t.Fatal(err)

View File

@@ -10,7 +10,7 @@ func On(event string, callback func()) {
locker.Lock()
defer locker.Unlock()
callbacks, _ := eventsMap[event]
var callbacks = eventsMap[event]
callbacks = append(callbacks, callback)
eventsMap[event] = callbacks
}
@@ -18,9 +18,9 @@ func On(event string, callback func()) {
// Notify 通知事件
func Notify(event string) {
locker.Lock()
callbacks, _ := eventsMap[event]
var callbacks = eventsMap[event]
locker.Unlock()
for _, callback := range callbacks {
callback()
}

View File

@@ -149,8 +149,8 @@ func (this *BaseInstaller) LookupLatestInstaller(filePrefix string) (string, err
func (this *BaseInstaller) InstallHelper(targetDir string, role nodeconfigs.NodeRole) (env *Env, err error) {
var uname = this.uname()
var osName = ""
var archName = ""
var osName string
var archName string
if strings.Contains(uname, "Darwin") {
osName = "darwin"
} else if strings.Contains(uname, "Linux") {

View File

@@ -97,16 +97,12 @@ func (this *HTTPCacheTaskKeyService) ValidateHTTPCacheTaskKeys(ctx context.Conte
}
var serverClusterId = int64(server.ClusterId)
if serverClusterId == 0 {
if clusterId > 0 {
serverClusterId = clusterId
} else {
pbFailResults = append(pbFailResults, &pb.ValidateHTTPCacheTaskKeysResponse_FailKey{
Key: key,
ReasonCode: "requireClusterId",
})
continue
}
if serverClusterId == 0 && clusterId <= 0 {
pbFailResults = append(pbFailResults, &pb.ValidateHTTPCacheTaskKeysResponse_FailKey{
Key: key,
ReasonCode: "requireClusterId",
})
continue
}
}

View File

@@ -34,7 +34,7 @@ type CommandRequestWaiting struct {
func (this *CommandRequestWaiting) Close() {
defer func() {
recover()
_ = recover()
}()
close(this.Chan)
@@ -207,7 +207,7 @@ func (this *NodeService) NodeStream(server pb.NodeService_NodeStreamServer) erro
func(req *pb.NodeStreamMessage) {
// 因为 responseChan.Chan 有被关闭的风险所以我们使用recover防止panic
defer func() {
recover()
_ = recover()
}()
nodeLocker.Lock()

View File

@@ -2917,8 +2917,14 @@ func (this *ServerService) CopyServerConfig(ctx context.Context, req *pb.CopySer
if err != nil {
return nil, err
}
if req.TargetUserId <= 0 {
req.TargetUserId = userId
}
// 此时如果用户为0则同步到未分配用户的服务
// 此时如果用户为0则同步到未分配用户的网站
} else {
// 只能同步到自己的网站
req.TargetUserId = userId
}
err = models.SharedServerDAO.CopyServerConfigToUser(tx, req.ServerId, req.TargetUserId, req.ConfigCode)
if err != nil {

View File

@@ -177,7 +177,7 @@ func (this *ServerBandwidthStatService) FindServerBandwidthStats(ctx context.Con
req.Algo = bandwidthAlgo
}
var stats = []*models.ServerBandwidthStat{}
var stats []*models.ServerBandwidthStat
if len(req.Day) > 0 {
stats, err = models.SharedServerBandwidthStatDAO.FindAllServerStatsWithDay(tx, req.ServerId, req.Day, req.Algo == systemconfigs.BandwidthAlgoAvg)
} else if len(req.Month) > 0 {
@@ -398,7 +398,7 @@ func (this *ServerBandwidthStatService) FindDailyServerBandwidthStatsBetweenDays
return nil, errors.New("invalid dayTo '" + req.DayTo + "'")
}
var pbStats = []*pb.FindDailyServerBandwidthStatsBetweenDaysResponse_Stat{}
var pbStats []*pb.FindDailyServerBandwidthStatsBetweenDaysResponse_Stat
var pbNthStat *pb.FindDailyServerBandwidthStatsBetweenDaysResponse_Stat
if req.ServerId > 0 { // 服务统计
pbStats, err = models.SharedServerBandwidthStatDAO.FindBandwidthStatsBetweenDays(tx, req.ServerId, req.DayFrom, req.DayTo, req.Algo == systemconfigs.BandwidthAlgoAvg)

View File

@@ -424,9 +424,7 @@ func upgradeV0_3_2(db *dbs.DB) error {
if err != nil {
continue
}
if sizeCapacity != nil {
compressionConfig.MinLength = sizeCapacity
}
compressionConfig.MinLength = sizeCapacity
}
var maxLengthBytes = []byte(gzipOne.GetString("maxLength"))
@@ -436,9 +434,7 @@ func upgradeV0_3_2(db *dbs.DB) error {
if err != nil {
continue
}
if sizeCapacity != nil {
compressionConfig.MaxLength = sizeCapacity
}
compressionConfig.MaxLength = sizeCapacity
}
var condsBytes = []byte(gzipOne.GetString("conds"))
@@ -448,9 +444,7 @@ func upgradeV0_3_2(db *dbs.DB) error {
if err != nil {
continue
}
if conds != nil {
compressionConfig.Conds = conds
}
compressionConfig.Conds = conds
}
configJSON, err := json.Marshal(compressionConfig)

View File

@@ -177,7 +177,7 @@ func (this *HealthCheckExecutor) runNode(healthCheckConfig *serverconfigs.Health
// 在线状态发生变化
if healthCheckConfig.AutoDown {
// 发送消息
var message = ""
var message string
var messageType string
var messageLevel string
if result.IsOk {

View File

@@ -122,7 +122,7 @@ func TestList_ManyItems(t *testing.T) {
})
list.GC(time.Now().Unix() + 1)
t.Log("gc", count, "items")
t.Log(time.Now().Sub(now))
t.Log(time.Since(now))
}
func TestList_Map_Performance(t *testing.T) {
@@ -140,7 +140,7 @@ func TestList_Map_Performance(t *testing.T) {
for i := 0; i < 100_000; i++ {
delete(m, int64(i))
}
t.Log(time.Now().Sub(now))
t.Log(time.Since(now))
}
{
@@ -153,7 +153,7 @@ func TestList_Map_Performance(t *testing.T) {
for i := 0; i < 100_000; i++ {
delete(m, uint64(i))
}
t.Log(time.Now().Sub(now))
t.Log(time.Since(now))
}
{
@@ -166,7 +166,7 @@ func TestList_Map_Performance(t *testing.T) {
for i := 0; i < 100_000; i++ {
delete(m, uint32(i))
}
t.Log(time.Now().Sub(now))
t.Log(time.Since(now))
}
}

View File

@@ -25,5 +25,5 @@ func SetRLimit(limit uint64) error {
// set best resource limit value
func SetSuitableRLimit() {
SetRLimit(4096 * 100) // 1M=100Files
_ = SetRLimit(4096 * 100) // 1M=100Files
}

View File

@@ -39,7 +39,7 @@ func (this *ServiceManager) setup() {
this.onceLocker.Do(func() {
logFile := files.NewFile(Tea.Root + "/logs/service.log")
if logFile.Exists() {
logFile.Delete()
_ = logFile.Delete()
}
//logger

View File

@@ -10,8 +10,10 @@ var SharedCache = NewCache()
// Cache TTL缓存
// 最大的缓存时间为30 * 86400
// Piece数据结构
// Piece1 | Piece2 | Piece3 | ...
// [ Item1, Item2, ... ] | ...
//
// Piece1 | Piece2 | Piece3 | ...
// [ Item1, Item2, ... ] | ...
//
// KeyMap列表数据结构
// { timestamp1 => [key1, key2, ...] }, ...
type Cache struct {
@@ -115,19 +117,11 @@ func (this *Cache) Read(key string) (item *Item) {
return this.pieces[uint64Key%this.countPieces].Read(uint64Key)
}
func (this *Cache) readIntKey(key uint64) (value *Item) {
return this.pieces[key%this.countPieces].Read(key)
}
func (this *Cache) Delete(key string) {
uint64Key := HashKey([]byte(key))
this.pieces[uint64Key%this.countPieces].Delete(uint64Key)
}
func (this *Cache) deleteIntKey(key uint64) {
this.pieces[key%this.countPieces].Delete(key)
}
func (this *Cache) Count() (count int) {
for _, piece := range this.pieces {
count += piece.Count()