diff --git a/EdgeAPI/internal/clickhouse/httpdns_access_logs_store.go b/EdgeAPI/internal/clickhouse/httpdns_access_logs_store.go index 14f76ce..a794c5c 100644 --- a/EdgeAPI/internal/clickhouse/httpdns_access_logs_store.go +++ b/EdgeAPI/internal/clickhouse/httpdns_access_logs_store.go @@ -39,6 +39,7 @@ type HTTPDNSAccessLogListFilter struct { ClusterId int64 NodeId int64 AppId string + AppIds []string Domain string Status string Keyword string @@ -215,6 +216,20 @@ func (s *HTTPDNSAccessLogsStore) buildConditions(f HTTPDNSAccessLogListFilter) [ } if appID := strings.TrimSpace(f.AppId); appID != "" { conditions = append(conditions, "app_id = '"+escapeString(appID)+"'") + } else if len(f.AppIds) > 0 { + validAppIds := make([]string, 0, len(f.AppIds)) + for _, appID := range f.AppIds { + appID = strings.TrimSpace(appID) + if len(appID) == 0 { + continue + } + validAppIds = append(validAppIds, "'"+escapeString(appID)+"'") + } + if len(validAppIds) == 0 { + conditions = append(conditions, "1 = 0") + } else { + conditions = append(conditions, "app_id IN ("+strings.Join(validAppIds, ",")+")") + } } if domain := strings.TrimSpace(f.Domain); domain != "" { conditions = append(conditions, "domain = '"+escapeString(domain)+"'") diff --git a/EdgeAPI/internal/db/models/httpdns_access_log_dao.go b/EdgeAPI/internal/db/models/httpdns_access_log_dao.go index 9bcbf17..8dc4b01 100644 --- a/EdgeAPI/internal/db/models/httpdns_access_log_dao.go +++ b/EdgeAPI/internal/db/models/httpdns_access_log_dao.go @@ -4,6 +4,7 @@ import ( _ "github.com/go-sql-driver/mysql" "github.com/iwind/TeaGo/Tea" "github.com/iwind/TeaGo/dbs" + "strings" ) type HTTPDNSAccessLogDAO dbs.DAO @@ -52,6 +53,10 @@ func (this *HTTPDNSAccessLogDAO) CreateLog(tx *dbs.Tx, log *HTTPDNSAccessLog) er } func (this *HTTPDNSAccessLogDAO) BuildListQuery(tx *dbs.Tx, day string, clusterId int64, nodeId int64, appId string, domain string, status string, keyword string) *dbs.Query { + return this.BuildListQueryWithAppIds(tx, day, clusterId, nodeId, appId, nil, domain, status, keyword) +} + +func (this *HTTPDNSAccessLogDAO) BuildListQueryWithAppIds(tx *dbs.Tx, day string, clusterId int64, nodeId int64, appId string, appIds []string, domain string, status string, keyword string) *dbs.Query { query := this.Query(tx).DescPk() if len(day) > 0 { query = query.Attr("day", day) @@ -62,6 +67,21 @@ func (this *HTTPDNSAccessLogDAO) BuildListQuery(tx *dbs.Tx, day string, clusterI if nodeId > 0 { query = query.Attr("nodeId", nodeId) } + if len(appIds) > 0 { + validAppIds := make([]string, 0, len(appIds)) + for _, value := range appIds { + value = strings.TrimSpace(value) + if len(value) == 0 { + continue + } + validAppIds = append(validAppIds, value) + } + if len(validAppIds) == 0 { + query = query.Where("1 = 0") + } else { + query = query.Attr("appId", validAppIds) + } + } if len(appId) > 0 { query = query.Attr("appId", appId) } @@ -78,11 +98,24 @@ func (this *HTTPDNSAccessLogDAO) BuildListQuery(tx *dbs.Tx, day string, clusterI } func (this *HTTPDNSAccessLogDAO) CountLogs(tx *dbs.Tx, day string, clusterId int64, nodeId int64, appId string, domain string, status string, keyword string) (int64, error) { - return this.BuildListQuery(tx, day, clusterId, nodeId, appId, domain, status, keyword).Count() + return this.BuildListQueryWithAppIds(tx, day, clusterId, nodeId, appId, nil, domain, status, keyword).Count() } func (this *HTTPDNSAccessLogDAO) ListLogs(tx *dbs.Tx, day string, clusterId int64, nodeId int64, appId string, domain string, status string, keyword string, offset int64, size int64) (result []*HTTPDNSAccessLog, err error) { - _, err = this.BuildListQuery(tx, day, clusterId, nodeId, appId, domain, status, keyword). + _, err = this.BuildListQueryWithAppIds(tx, day, clusterId, nodeId, appId, nil, domain, status, keyword). + Offset(offset). + Limit(size). + Slice(&result). + FindAll() + return +} + +func (this *HTTPDNSAccessLogDAO) CountLogsWithAppIds(tx *dbs.Tx, day string, clusterId int64, nodeId int64, appId string, appIds []string, domain string, status string, keyword string) (int64, error) { + return this.BuildListQueryWithAppIds(tx, day, clusterId, nodeId, appId, appIds, domain, status, keyword).Count() +} + +func (this *HTTPDNSAccessLogDAO) ListLogsWithAppIds(tx *dbs.Tx, day string, clusterId int64, nodeId int64, appId string, appIds []string, domain string, status string, keyword string, offset int64, size int64) (result []*HTTPDNSAccessLog, err error) { + _, err = this.BuildListQueryWithAppIds(tx, day, clusterId, nodeId, appId, appIds, domain, status, keyword). Offset(offset). Limit(size). Slice(&result). diff --git a/EdgeAPI/internal/db/models/httpdns_app_dao.go b/EdgeAPI/internal/db/models/httpdns_app_dao.go index 0af29b7..641dab3 100644 --- a/EdgeAPI/internal/db/models/httpdns_app_dao.go +++ b/EdgeAPI/internal/db/models/httpdns_app_dao.go @@ -85,6 +85,18 @@ func (this *HTTPDNSAppDAO) FindEnabledApp(tx *dbs.Tx, appDbId int64) (*HTTPDNSAp return one.(*HTTPDNSApp), nil } +func (this *HTTPDNSAppDAO) FindEnabledAppWithUser(tx *dbs.Tx, appDbId int64, userId int64) (*HTTPDNSApp, error) { + one, err := this.Query(tx). + Pk(appDbId). + State(HTTPDNSAppStateEnabled). + Attr("userId", userId). + Find() + if one == nil { + return nil, err + } + return one.(*HTTPDNSApp), nil +} + func (this *HTTPDNSAppDAO) FindEnabledAppWithAppId(tx *dbs.Tx, appId string) (*HTTPDNSApp, error) { one, err := this.Query(tx). State(HTTPDNSAppStateEnabled). @@ -96,6 +108,31 @@ func (this *HTTPDNSAppDAO) FindEnabledAppWithAppId(tx *dbs.Tx, appId string) (*H return one.(*HTTPDNSApp), nil } +func (this *HTTPDNSAppDAO) FindEnabledAppWithAppIdAndUser(tx *dbs.Tx, appId string, userId int64) (*HTTPDNSApp, error) { + one, err := this.Query(tx). + State(HTTPDNSAppStateEnabled). + Attr("appId", appId). + Attr("userId", userId). + Find() + if one == nil { + return nil, err + } + return one.(*HTTPDNSApp), nil +} + +func (this *HTTPDNSAppDAO) FindLatestEnabledAppWithNameAndUser(tx *dbs.Tx, name string, userId int64) (*HTTPDNSApp, error) { + one, err := this.Query(tx). + State(HTTPDNSAppStateEnabled). + Attr("name", name). + Attr("userId", userId). + DescPk(). + Find() + if one == nil { + return nil, err + } + return one.(*HTTPDNSApp), nil +} + func (this *HTTPDNSAppDAO) ListEnabledApps(tx *dbs.Tx, offset int64, size int64, keyword string) (result []*HTTPDNSApp, err error) { query := this.Query(tx). State(HTTPDNSAppStateEnabled). @@ -110,6 +147,21 @@ func (this *HTTPDNSAppDAO) ListEnabledApps(tx *dbs.Tx, offset int64, size int64, return } +func (this *HTTPDNSAppDAO) ListEnabledAppsWithUser(tx *dbs.Tx, userId int64, offset int64, size int64, keyword string) (result []*HTTPDNSApp, err error) { + query := this.Query(tx). + State(HTTPDNSAppStateEnabled). + Attr("userId", userId). + AscPk() + if len(keyword) > 0 { + query = query.Where("(name LIKE :kw OR appId LIKE :kw)").Param("kw", "%"+keyword+"%") + } + if size > 0 { + query = query.Offset(offset).Limit(size) + } + _, err = query.Slice(&result).FindAll() + return +} + func (this *HTTPDNSAppDAO) CountEnabledApps(tx *dbs.Tx, keyword string) (int64, error) { query := this.Query(tx).State(HTTPDNSAppStateEnabled) if len(keyword) > 0 { @@ -118,6 +170,14 @@ func (this *HTTPDNSAppDAO) CountEnabledApps(tx *dbs.Tx, keyword string) (int64, return query.Count() } +func (this *HTTPDNSAppDAO) CountEnabledAppsWithUser(tx *dbs.Tx, userId int64, keyword string) (int64, error) { + query := this.Query(tx).State(HTTPDNSAppStateEnabled).Attr("userId", userId) + if len(keyword) > 0 { + query = query.Where("(name LIKE :kw OR appId LIKE :kw)").Param("kw", "%"+keyword+"%") + } + return query.Count() +} + func (this *HTTPDNSAppDAO) FindAllEnabledApps(tx *dbs.Tx) (result []*HTTPDNSApp, err error) { _, err = this.Query(tx). State(HTTPDNSAppStateEnabled). @@ -126,3 +186,28 @@ func (this *HTTPDNSAppDAO) FindAllEnabledApps(tx *dbs.Tx) (result []*HTTPDNSApp, FindAll() return } + +func (this *HTTPDNSAppDAO) FindAllEnabledAppsWithUser(tx *dbs.Tx, userId int64) (result []*HTTPDNSApp, err error) { + _, err = this.Query(tx). + State(HTTPDNSAppStateEnabled). + Attr("userId", userId). + AscPk(). + Slice(&result). + FindAll() + return +} + +func (this *HTTPDNSAppDAO) ListEnabledAppIdsWithUser(tx *dbs.Tx, userId int64) (result []string, err error) { + apps, err := this.FindAllEnabledAppsWithUser(tx, userId) + if err != nil { + return nil, err + } + result = make([]string, 0, len(apps)) + for _, app := range apps { + if app == nil || len(app.AppId) == 0 { + continue + } + result = append(result, app.AppId) + } + return +} diff --git a/EdgeAPI/internal/db/models/httpdns_app_secret_dao.go b/EdgeAPI/internal/db/models/httpdns_app_secret_dao.go index b2d1934..37ca9f0 100644 --- a/EdgeAPI/internal/db/models/httpdns_app_secret_dao.go +++ b/EdgeAPI/internal/db/models/httpdns_app_secret_dao.go @@ -38,6 +38,27 @@ func init() { func (this *HTTPDNSAppSecretDAO) InitAppSecret(tx *dbs.Tx, appDbId int64, signEnabled bool) (string, uint64, error) { signSecret := "ss_" + rands.HexString(12) now := uint64(time.Now().Unix()) + + // 兼容历史数据:如果已存在(可能是停用状态)则直接恢复并更新,避免 UNIQUE(appId) 冲突 + old, err := this.Query(tx). + Attr("appId", appDbId). + Find() + if err != nil { + return "", 0, err + } + if old != nil { + oldSecret := old.(*HTTPDNSAppSecret) + _, err = this.Query(tx). + Pk(oldSecret.Id). + Set("signEnabled", signEnabled). + Set("signSecret", signSecret). + Set("signUpdatedAt", now). + Set("updatedAt", now). + Set("state", HTTPDNSAppSecretStateEnabled). + Update() + return signSecret, now, err + } + var op = NewHTTPDNSAppSecretOperator() op.AppId = appDbId op.SignEnabled = signEnabled @@ -45,7 +66,7 @@ func (this *HTTPDNSAppSecretDAO) InitAppSecret(tx *dbs.Tx, appDbId int64, signEn op.SignUpdatedAt = now op.UpdatedAt = now op.State = HTTPDNSAppSecretStateEnabled - err := this.Save(tx, op) + err = this.Save(tx, op) return signSecret, now, err } diff --git a/EdgeAPI/internal/db/models/httpdns_cluster_dao.go b/EdgeAPI/internal/db/models/httpdns_cluster_dao.go index 872b5d0..087d36b 100644 --- a/EdgeAPI/internal/db/models/httpdns_cluster_dao.go +++ b/EdgeAPI/internal/db/models/httpdns_cluster_dao.go @@ -152,6 +152,22 @@ func (this *HTTPDNSClusterDAO) FindAllEnabledClusters(tx *dbs.Tx) (result []*HTT return } +func (this *HTTPDNSClusterDAO) FindDefaultPrimaryClusterId(tx *dbs.Tx) (int64, error) { + col, err := this.Query(tx). + State(HTTPDNSClusterStateEnabled). + Attr("isDefault", true). + Result("id"). + AscPk(). + FindCol(nil) + if err != nil { + return 0, err + } + if col == nil { + return 0, nil + } + return types.Int64(col), nil +} + func (this *HTTPDNSClusterDAO) UpdateDefaultCluster(tx *dbs.Tx, clusterId int64) error { err := this.Query(tx). State(HTTPDNSClusterStateEnabled). diff --git a/EdgeAPI/internal/installers/installer_httpdns_node.go b/EdgeAPI/internal/installers/installer_httpdns_node.go index 67ff300..f93b600 100644 --- a/EdgeAPI/internal/installers/installer_httpdns_node.go +++ b/EdgeAPI/internal/installers/installer_httpdns_node.go @@ -104,11 +104,16 @@ func (i *HTTPDNSNodeInstaller) Install(dir string, params interface{}, installSt _, _, _ = i.client.Exec("chown " + i.client.User() + " " + filepath.Dir(configFile)) } + listenAddr := strings.TrimSpace(nodeParams.HTTPDNSListenAddr) + if len(listenAddr) == 0 { + listenAddr = ":443" + } + configData := []byte(`rpc.endpoints: [ ${endpoints} ] nodeId: "${nodeId}" secret: "${nodeSecret}" -https.listenAddr: ":443" +https.listenAddr: "${listenAddr}" https.cert: "${certFile}" https.key: "${keyFile}"`) certFileClean := strings.ReplaceAll(certFile, "\\", "/") @@ -117,6 +122,7 @@ https.key: "${keyFile}"`) configData = bytes.ReplaceAll(configData, []byte("${endpoints}"), []byte(nodeParams.QuoteEndpoints())) configData = bytes.ReplaceAll(configData, []byte("${nodeId}"), []byte(nodeParams.NodeId)) configData = bytes.ReplaceAll(configData, []byte("${nodeSecret}"), []byte(nodeParams.Secret)) + configData = bytes.ReplaceAll(configData, []byte("${listenAddr}"), []byte(listenAddr)) configData = bytes.ReplaceAll(configData, []byte("${certFile}"), []byte(certFileClean)) configData = bytes.ReplaceAll(configData, []byte("${keyFile}"), []byte(keyFileClean)) diff --git a/EdgeAPI/internal/installers/params_node.go b/EdgeAPI/internal/installers/params_node.go index 72222f4..ad12fc4 100644 --- a/EdgeAPI/internal/installers/params_node.go +++ b/EdgeAPI/internal/installers/params_node.go @@ -6,12 +6,13 @@ import ( ) type NodeParams struct { - Endpoints []string - NodeId string - Secret string - TLSCertData []byte - TLSKeyData []byte - IsUpgrading bool // 是否为升级 + Endpoints []string + NodeId string + Secret string + TLSCertData []byte + TLSKeyData []byte + HTTPDNSListenAddr string + IsUpgrading bool // 是否为升级 } func (this *NodeParams) Validate() error { diff --git a/EdgeAPI/internal/installers/queue_httpdns_node.go b/EdgeAPI/internal/installers/queue_httpdns_node.go index 0cfc743..d2d5449 100644 --- a/EdgeAPI/internal/installers/queue_httpdns_node.go +++ b/EdgeAPI/internal/installers/queue_httpdns_node.go @@ -1,15 +1,19 @@ -package installers +package installers import ( "encoding/json" "errors" "fmt" + "net" + "strconv" + "strings" "time" "github.com/TeaOSLab/EdgeAPI/internal/db/models" "github.com/TeaOSLab/EdgeAPI/internal/goman" "github.com/TeaOSLab/EdgeAPI/internal/utils" "github.com/TeaOSLab/EdgeAPI/internal/utils/numberutils" + "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs" "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/sslconfigs" "github.com/iwind/TeaGo/logs" "github.com/iwind/TeaGo/maps" @@ -136,14 +140,20 @@ func (q *HTTPDNSNodeQueue) InstallNode(nodeId int64, installStatus *models.NodeI installStatus.ErrorCode = "EMPTY_TLS_CERT" return err } + httpdnsListenAddr, err := q.resolveClusterTLSListenAddr(cluster) + if err != nil { + installStatus.ErrorCode = "INVALID_TLS_LISTEN" + return err + } params := &NodeParams{ - Endpoints: apiEndpoints, - NodeId: node.UniqueId, - Secret: node.Secret, - TLSCertData: tlsCertData, - TLSKeyData: tlsKeyData, - IsUpgrading: isUpgrading, + Endpoints: apiEndpoints, + NodeId: node.UniqueId, + Secret: node.Secret, + TLSCertData: tlsCertData, + TLSKeyData: tlsKeyData, + HTTPDNSListenAddr: httpdnsListenAddr, + IsUpgrading: isUpgrading, } installer := &HTTPDNSNodeInstaller{} @@ -246,6 +256,37 @@ func (q *HTTPDNSNodeQueue) resolveClusterTLSCertPair(cluster *models.HTTPDNSClus return nil, nil, errors.New("cluster tls certificate is not configured") } +func (q *HTTPDNSNodeQueue) resolveClusterTLSListenAddr(cluster *models.HTTPDNSCluster) (string, error) { + const defaultListenAddr = ":443" + + if cluster == nil || len(cluster.TLSPolicy) == 0 { + return defaultListenAddr, nil + } + + tlsConfig, err := serverconfigs.NewTLSProtocolConfigFromJSON(cluster.TLSPolicy) + if err != nil { + return "", fmt.Errorf("decode cluster tls listen failed: %w", err) + } + + for _, listen := range tlsConfig.Listen { + if listen == nil { + continue + } + + if err := listen.Init(); err != nil { + return "", fmt.Errorf("invalid cluster tls listen address '%s': %w", listen.PortRange, err) + } + if listen.MinPort <= 0 { + continue + } + + host := strings.TrimSpace(listen.Host) + return net.JoinHostPort(host, strconv.Itoa(listen.MinPort)), nil + } + + return defaultListenAddr, nil +} + func (q *HTTPDNSNodeQueue) parseSSHInfo(node *models.HTTPDNSNode) (string, int, int64, error) { if node == nil { return "", 0, 0, errors.New("node should not be nil") diff --git a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_access_log.go b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_access_log.go index 6a415ef..be0e527 100644 --- a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_access_log.go +++ b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_access_log.go @@ -4,6 +4,7 @@ import ( "context" "log" "strconv" + "strings" "time" "github.com/TeaOSLab/EdgeAPI/internal/clickhouse" @@ -132,16 +133,43 @@ func (s *HTTPDNSAccessLogService) CreateHTTPDNSAccessLogs(ctx context.Context, r } func (s *HTTPDNSAccessLogService) ListHTTPDNSAccessLogs(ctx context.Context, req *pb.ListHTTPDNSAccessLogsRequest) (*pb.ListHTTPDNSAccessLogsResponse, error) { - _, _, err := s.ValidateAdminAndUser(ctx, true) + _, userId, err := s.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } + allowedAppIds := []string(nil) + if userId > 0 { + if len(strings.TrimSpace(req.GetAppId())) > 0 { + app, err := ensureAppAccessByAppId(s.NullTx(), req.GetAppId(), userId) + if err != nil { + return nil, err + } + if app == nil { + return &pb.ListHTTPDNSAccessLogsResponse{ + Logs: []*pb.HTTPDNSAccessLog{}, + Total: 0, + }, nil + } + } else { + allowedAppIds, err = models.SharedHTTPDNSAppDAO.ListEnabledAppIdsWithUser(s.NullTx(), userId) + if err != nil { + return nil, err + } + if len(allowedAppIds) == 0 { + return &pb.ListHTTPDNSAccessLogsResponse{ + Logs: []*pb.HTTPDNSAccessLog{}, + Total: 0, + }, nil + } + } + } + store := clickhouse.NewHTTPDNSAccessLogsStore() canReadFromClickHouse := s.shouldReadHTTPDNSAccessLogsFromClickHouse() && store.Client().IsConfigured() canReadFromMySQL := s.shouldReadHTTPDNSAccessLogsFromMySQL() if canReadFromClickHouse { - resp, listErr := s.listFromClickHouse(ctx, store, req) + resp, listErr := s.listFromClickHouse(ctx, store, req, allowedAppIds) if listErr == nil { return resp, nil } @@ -158,11 +186,11 @@ func (s *HTTPDNSAccessLogService) ListHTTPDNSAccessLogs(ctx context.Context, req }, nil } - total, err := models.SharedHTTPDNSAccessLogDAO.CountLogs(s.NullTx(), req.GetDay(), req.GetClusterId(), req.GetNodeId(), req.GetAppId(), req.GetDomain(), req.GetStatus(), req.GetKeyword()) + total, err := models.SharedHTTPDNSAccessLogDAO.CountLogsWithAppIds(s.NullTx(), req.GetDay(), req.GetClusterId(), req.GetNodeId(), req.GetAppId(), allowedAppIds, req.GetDomain(), req.GetStatus(), req.GetKeyword()) if err != nil { return nil, err } - logs, err := models.SharedHTTPDNSAccessLogDAO.ListLogs(s.NullTx(), req.GetDay(), req.GetClusterId(), req.GetNodeId(), req.GetAppId(), req.GetDomain(), req.GetStatus(), req.GetKeyword(), req.GetOffset(), req.GetSize()) + logs, err := models.SharedHTTPDNSAccessLogDAO.ListLogsWithAppIds(s.NullTx(), req.GetDay(), req.GetClusterId(), req.GetNodeId(), req.GetAppId(), allowedAppIds, req.GetDomain(), req.GetStatus(), req.GetKeyword(), req.GetOffset(), req.GetSize()) if err != nil { return nil, err } @@ -212,12 +240,13 @@ func (s *HTTPDNSAccessLogService) ListHTTPDNSAccessLogs(ctx context.Context, req }, nil } -func (s *HTTPDNSAccessLogService) listFromClickHouse(ctx context.Context, store *clickhouse.HTTPDNSAccessLogsStore, req *pb.ListHTTPDNSAccessLogsRequest) (*pb.ListHTTPDNSAccessLogsResponse, error) { +func (s *HTTPDNSAccessLogService) listFromClickHouse(ctx context.Context, store *clickhouse.HTTPDNSAccessLogsStore, req *pb.ListHTTPDNSAccessLogsRequest, allowedAppIds []string) (*pb.ListHTTPDNSAccessLogsResponse, error) { filter := clickhouse.HTTPDNSAccessLogListFilter{ Day: req.GetDay(), ClusterId: req.GetClusterId(), NodeId: req.GetNodeId(), AppId: req.GetAppId(), + AppIds: allowedAppIds, Domain: req.GetDomain(), Status: req.GetStatus(), Keyword: req.GetKeyword(), diff --git a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_app.go b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_app.go index 41c238e..a159435 100644 --- a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_app.go +++ b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_app.go @@ -5,8 +5,11 @@ import ( "errors" "github.com/TeaOSLab/EdgeAPI/internal/rpc/services" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeCommon/pkg/systemconfigs" "github.com/iwind/TeaGo/dbs" + "github.com/iwind/TeaGo/types" "strings" + "time" "github.com/TeaOSLab/EdgeAPI/internal/db/models" ) @@ -18,19 +21,44 @@ type HTTPDNSAppService struct { } func (this *HTTPDNSAppService) CreateHTTPDNSApp(ctx context.Context, req *pb.CreateHTTPDNSAppRequest) (*pb.CreateHTTPDNSAppResponse, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } - if len(req.Name) == 0 || len(req.AppId) == 0 { + if userId > 0 { + req.UserId = userId + } + appName := strings.TrimSpace(req.Name) + appId := strings.TrimSpace(req.AppId) + if len(appName) == 0 || len(appId) == 0 { return nil, errors.New("required 'name' and 'appId'") } - if req.PrimaryClusterId <= 0 { - return nil, errors.New("required 'primaryClusterId'") - } var appDbId int64 + now := time.Now().Unix() err = this.RunTx(func(tx *dbs.Tx) error { - exists, err := models.SharedHTTPDNSAppDAO.FindEnabledAppWithAppId(tx, strings.TrimSpace(req.AppId)) + // 用户端防重复提交:短时间内同用户同应用名仅创建一次。 + if req.UserId > 0 { + latest, err := models.SharedHTTPDNSAppDAO.FindLatestEnabledAppWithNameAndUser(tx, appName, req.UserId) + if err != nil { + return err + } + if latest != nil && int64(latest.CreatedAt) >= now-5 { + appDbId = int64(latest.Id) + secret, err := models.SharedHTTPDNSAppSecretDAO.FindEnabledAppSecret(tx, appDbId) + if err != nil { + return err + } + if secret == nil { + _, _, err = models.SharedHTTPDNSAppSecretDAO.InitAppSecret(tx, appDbId, req.SignEnabled) + if err != nil { + return err + } + } + return nil + } + } + + exists, err := models.SharedHTTPDNSAppDAO.FindEnabledAppWithAppId(tx, appId) if err != nil { return err } @@ -38,7 +66,25 @@ func (this *HTTPDNSAppService) CreateHTTPDNSApp(ctx context.Context, req *pb.Cre return errors.New("appId already exists") } - appDbId, err = models.SharedHTTPDNSAppDAO.CreateApp(tx, req.Name, strings.TrimSpace(req.AppId), req.PrimaryClusterId, req.BackupClusterId, req.IsOn, req.UserId) + primaryClusterId := req.PrimaryClusterId + backupClusterId := req.BackupClusterId + if primaryClusterId <= 0 || backupClusterId <= 0 { + defaultPrimaryClusterId, defaultBackupClusterId, err := readHTTPDNSDefaultClusterIds(tx) + if err != nil { + return err + } + if primaryClusterId <= 0 { + primaryClusterId = defaultPrimaryClusterId + } + if backupClusterId <= 0 { + backupClusterId = defaultBackupClusterId + } + } + if primaryClusterId > 0 && backupClusterId == primaryClusterId { + backupClusterId = 0 + } + + appDbId, err = models.SharedHTTPDNSAppDAO.CreateApp(tx, appName, appId, primaryClusterId, backupClusterId, req.IsOn, req.UserId) if err != nil { return err } @@ -54,13 +100,53 @@ func (this *HTTPDNSAppService) CreateHTTPDNSApp(ctx context.Context, req *pb.Cre return &pb.CreateHTTPDNSAppResponse{AppDbId: appDbId}, nil } +func readHTTPDNSDefaultClusterIds(tx *dbs.Tx) (primaryClusterId int64, backupClusterId int64, err error) { + primaryClusterId, err = models.SharedHTTPDNSClusterDAO.FindDefaultPrimaryClusterId(tx) + if err != nil { + return 0, 0, err + } + + backupClusterId = 0 + backupValueJSON, err := models.SharedSysSettingDAO.ReadSetting(tx, systemconfigs.SettingCodeHTTPDNSDefaultBackupClusterId) + if err != nil { + return 0, 0, err + } + if len(backupValueJSON) > 0 { + backupClusterId = types.Int64(string(backupValueJSON)) + } + if backupClusterId > 0 { + backupCluster, err := models.SharedHTTPDNSClusterDAO.FindEnabledCluster(tx, backupClusterId) + if err != nil { + return 0, 0, err + } + if backupCluster == nil || !backupCluster.IsOn { + backupClusterId = 0 + } + } + + if primaryClusterId > 0 { + primaryCluster, err := models.SharedHTTPDNSClusterDAO.FindEnabledCluster(tx, primaryClusterId) + if err != nil { + return 0, 0, err + } + if primaryCluster == nil || !primaryCluster.IsOn { + primaryClusterId = 0 + } + } + + if primaryClusterId > 0 && backupClusterId == primaryClusterId { + backupClusterId = 0 + } + return primaryClusterId, backupClusterId, nil +} + func (this *HTTPDNSAppService) UpdateHTTPDNSApp(ctx context.Context, req *pb.UpdateHTTPDNSAppRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } err = this.RunTx(func(tx *dbs.Tx) error { - oldApp, err := models.SharedHTTPDNSAppDAO.FindEnabledApp(tx, req.AppDbId) + oldApp, err := ensureAppAccess(tx, req.AppDbId, userId) if err != nil { return err } @@ -68,7 +154,20 @@ func (this *HTTPDNSAppService) UpdateHTTPDNSApp(ctx context.Context, req *pb.Upd return errors.New("app not found") } - err = models.SharedHTTPDNSAppDAO.UpdateApp(tx, req.AppDbId, req.Name, req.PrimaryClusterId, req.BackupClusterId, req.IsOn, req.UserId) + targetUserId := req.UserId + if targetUserId <= 0 { + targetUserId = oldApp.UserId + } + if userId > 0 { + targetUserId = userId + } + primaryClusterId := req.PrimaryClusterId + backupClusterId := req.BackupClusterId + if primaryClusterId > 0 && backupClusterId == primaryClusterId { + backupClusterId = 0 + } + + err = models.SharedHTTPDNSAppDAO.UpdateApp(tx, req.AppDbId, req.Name, primaryClusterId, backupClusterId, req.IsOn, targetUserId) if err != nil { return err } @@ -86,12 +185,12 @@ func (this *HTTPDNSAppService) UpdateHTTPDNSApp(ctx context.Context, req *pb.Upd } func (this *HTTPDNSAppService) DeleteHTTPDNSApp(ctx context.Context, req *pb.DeleteHTTPDNSAppRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } err = this.RunTx(func(tx *dbs.Tx) error { - app, err := models.SharedHTTPDNSAppDAO.FindEnabledApp(tx, req.AppDbId) + app, err := ensureAppAccess(tx, req.AppDbId, userId) if err != nil { return err } @@ -146,14 +245,17 @@ func (this *HTTPDNSAppService) DeleteHTTPDNSApp(ctx context.Context, req *pb.Del } func (this *HTTPDNSAppService) FindHTTPDNSApp(ctx context.Context, req *pb.FindHTTPDNSAppRequest) (*pb.FindHTTPDNSAppResponse, error) { - _, _, err := this.ValidateAdminAndUser(ctx, true) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } - app, err := models.SharedHTTPDNSAppDAO.FindEnabledApp(this.NullTx(), req.AppDbId) + app, err := ensureAppAccess(this.NullTx(), req.AppDbId, userId) if err != nil { return nil, err } + if app == nil { + return &pb.FindHTTPDNSAppResponse{}, nil + } secret, err := models.SharedHTTPDNSAppSecretDAO.FindEnabledAppSecret(this.NullTx(), req.AppDbId) if err != nil { return nil, err @@ -162,11 +264,16 @@ func (this *HTTPDNSAppService) FindHTTPDNSApp(ctx context.Context, req *pb.FindH } func (this *HTTPDNSAppService) ListHTTPDNSApps(ctx context.Context, req *pb.ListHTTPDNSAppsRequest) (*pb.ListHTTPDNSAppsResponse, error) { - _, _, err := this.ValidateAdminAndUser(ctx, true) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } - apps, err := models.SharedHTTPDNSAppDAO.ListEnabledApps(this.NullTx(), req.Offset, req.Size, req.Keyword) + var apps []*models.HTTPDNSApp + if userId > 0 { + apps, err = models.SharedHTTPDNSAppDAO.ListEnabledAppsWithUser(this.NullTx(), userId, req.Offset, req.Size, req.Keyword) + } else { + apps, err = models.SharedHTTPDNSAppDAO.ListEnabledApps(this.NullTx(), req.Offset, req.Size, req.Keyword) + } if err != nil { return nil, err } @@ -182,13 +289,19 @@ func (this *HTTPDNSAppService) ListHTTPDNSApps(ctx context.Context, req *pb.List } func (this *HTTPDNSAppService) FindAllHTTPDNSApps(ctx context.Context, req *pb.FindAllHTTPDNSAppsRequest) (*pb.FindAllHTTPDNSAppsResponse, error) { - _, _, validateErr := this.ValidateAdminAndUser(ctx, true) + _, userId, validateErr := this.ValidateAdminAndUser(ctx, true) if validateErr != nil { if _, nodeErr := this.ValidateHTTPDNSNode(ctx); nodeErr != nil { return nil, validateErr } } - apps, err := models.SharedHTTPDNSAppDAO.FindAllEnabledApps(this.NullTx()) + var apps []*models.HTTPDNSApp + var err error + if validateErr == nil && userId > 0 { + apps, err = models.SharedHTTPDNSAppDAO.FindAllEnabledAppsWithUser(this.NullTx(), userId) + } else { + apps, err = models.SharedHTTPDNSAppDAO.FindAllEnabledApps(this.NullTx()) + } if err != nil { return nil, err } @@ -204,12 +317,20 @@ func (this *HTTPDNSAppService) FindAllHTTPDNSApps(ctx context.Context, req *pb.F } func (this *HTTPDNSAppService) UpdateHTTPDNSAppSignEnabled(ctx context.Context, req *pb.UpdateHTTPDNSAppSignEnabledRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } err = this.RunTx(func(tx *dbs.Tx) error { - err := models.SharedHTTPDNSAppSecretDAO.UpdateSignEnabled(tx, req.AppDbId, req.SignEnabled) + app, err := ensureAppAccess(tx, req.AppDbId, userId) + if err != nil { + return err + } + if app == nil { + return errors.New("app not found") + } + + err = models.SharedHTTPDNSAppSecretDAO.UpdateSignEnabled(tx, req.AppDbId, req.SignEnabled) if err != nil { return err } @@ -222,14 +343,21 @@ func (this *HTTPDNSAppService) UpdateHTTPDNSAppSignEnabled(ctx context.Context, } func (this *HTTPDNSAppService) ResetHTTPDNSAppSignSecret(ctx context.Context, req *pb.ResetHTTPDNSAppSignSecretRequest) (*pb.ResetHTTPDNSAppSignSecretResponse, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } var signSecret string var updatedAt int64 err = this.RunTx(func(tx *dbs.Tx) error { - var err error + app, err := ensureAppAccess(tx, req.AppDbId, userId) + if err != nil { + return err + } + if app == nil { + return errors.New("app not found") + } + signSecret, updatedAt, err = models.SharedHTTPDNSAppSecretDAO.ResetSignSecret(tx, req.AppDbId) if err != nil { return err diff --git a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_domain.go b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_domain.go index 1a43d0d..0f93cc3 100644 --- a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_domain.go +++ b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_domain.go @@ -16,7 +16,7 @@ type HTTPDNSDomainService struct { } func (this *HTTPDNSDomainService) CreateHTTPDNSDomain(ctx context.Context, req *pb.CreateHTTPDNSDomainRequest) (*pb.CreateHTTPDNSDomainResponse, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } @@ -25,6 +25,14 @@ func (this *HTTPDNSDomainService) CreateHTTPDNSDomain(ctx context.Context, req * } var domainId int64 err = this.RunTx(func(tx *dbs.Tx) error { + app, err := ensureAppAccess(tx, req.AppDbId, userId) + if err != nil { + return err + } + if app == nil { + return errors.New("app not found") + } + domainId, err = models.SharedHTTPDNSDomainDAO.CreateDomain(tx, req.AppDbId, req.Domain, req.IsOn) if err != nil { return err @@ -38,12 +46,12 @@ func (this *HTTPDNSDomainService) CreateHTTPDNSDomain(ctx context.Context, req * } func (this *HTTPDNSDomainService) DeleteHTTPDNSDomain(ctx context.Context, req *pb.DeleteHTTPDNSDomainRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } err = this.RunTx(func(tx *dbs.Tx) error { - domain, err := models.SharedHTTPDNSDomainDAO.FindEnabledDomain(tx, req.DomainId) + domain, app, err := ensureDomainAccess(tx, req.DomainId, userId) if err != nil { return err } @@ -55,7 +63,7 @@ func (this *HTTPDNSDomainService) DeleteHTTPDNSDomain(ctx context.Context, req * if err != nil { return err } - return notifyHTTPDNSAppTasksByAppDbId(tx, int64(domain.AppId), models.HTTPDNSNodeTaskTypeDomainChanged) + return notifyHTTPDNSAppTasksByAppDbId(tx, int64(app.Id), models.HTTPDNSNodeTaskTypeDomainChanged) }) if err != nil { return nil, err @@ -64,12 +72,12 @@ func (this *HTTPDNSDomainService) DeleteHTTPDNSDomain(ctx context.Context, req * } func (this *HTTPDNSDomainService) UpdateHTTPDNSDomainStatus(ctx context.Context, req *pb.UpdateHTTPDNSDomainStatusRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } err = this.RunTx(func(tx *dbs.Tx) error { - domain, err := models.SharedHTTPDNSDomainDAO.FindEnabledDomain(tx, req.DomainId) + domain, app, err := ensureDomainAccess(tx, req.DomainId, userId) if err != nil { return err } @@ -81,7 +89,7 @@ func (this *HTTPDNSDomainService) UpdateHTTPDNSDomainStatus(ctx context.Context, if err != nil { return err } - return notifyHTTPDNSAppTasksByAppDbId(tx, int64(domain.AppId), models.HTTPDNSNodeTaskTypeDomainChanged) + return notifyHTTPDNSAppTasksByAppDbId(tx, int64(app.Id), models.HTTPDNSNodeTaskTypeDomainChanged) }) if err != nil { return nil, err @@ -90,11 +98,19 @@ func (this *HTTPDNSDomainService) UpdateHTTPDNSDomainStatus(ctx context.Context, } func (this *HTTPDNSDomainService) ListHTTPDNSDomainsWithAppId(ctx context.Context, req *pb.ListHTTPDNSDomainsWithAppIdRequest) (*pb.ListHTTPDNSDomainsWithAppIdResponse, error) { - _, _, validateErr := this.ValidateAdminAndUser(ctx, true) + _, userId, validateErr := this.ValidateAdminAndUser(ctx, true) if validateErr != nil { if _, nodeErr := this.ValidateHTTPDNSNode(ctx); nodeErr != nil { return nil, validateErr } + } else if userId > 0 { + app, err := ensureAppAccess(this.NullTx(), req.AppDbId, userId) + if err != nil { + return nil, err + } + if app == nil { + return &pb.ListHTTPDNSDomainsWithAppIdResponse{}, nil + } } domains, err := models.SharedHTTPDNSDomainDAO.ListEnabledDomainsWithAppId(this.NullTx(), req.AppDbId, req.Keyword) if err != nil { diff --git a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_rule.go b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_rule.go index a8bbd0c..6e397dc 100644 --- a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_rule.go +++ b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_rule.go @@ -16,7 +16,7 @@ type HTTPDNSRuleService struct { } func (this *HTTPDNSRuleService) CreateHTTPDNSCustomRule(ctx context.Context, req *pb.CreateHTTPDNSCustomRuleRequest) (*pb.CreateHTTPDNSCustomRuleResponse, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } @@ -25,8 +25,16 @@ func (this *HTTPDNSRuleService) CreateHTTPDNSCustomRule(ctx context.Context, req } var ruleId int64 err = this.RunTx(func(tx *dbs.Tx) error { + domain, app, err := ensureDomainAccess(tx, req.Rule.DomainId, userId) + if err != nil { + return err + } + if domain == nil || app == nil { + return errors.New("domain not found") + } + rule := &models.HTTPDNSCustomRule{ - AppId: uint32(req.Rule.AppId), + AppId: domain.AppId, DomainId: uint32(req.Rule.DomainId), RuleName: req.Rule.RuleName, LineScope: req.Rule.LineScope, @@ -49,7 +57,7 @@ func (this *HTTPDNSRuleService) CreateHTTPDNSCustomRule(ctx context.Context, req return err } } - return notifyHTTPDNSAppTasksByAppDbId(tx, req.Rule.AppId, models.HTTPDNSNodeTaskTypeRuleChanged) + return notifyHTTPDNSAppTasksByAppDbId(tx, int64(app.Id), models.HTTPDNSNodeTaskTypeRuleChanged) }) if err != nil { return nil, err @@ -58,7 +66,7 @@ func (this *HTTPDNSRuleService) CreateHTTPDNSCustomRule(ctx context.Context, req } func (this *HTTPDNSRuleService) UpdateHTTPDNSCustomRule(ctx context.Context, req *pb.UpdateHTTPDNSCustomRuleRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } @@ -66,7 +74,7 @@ func (this *HTTPDNSRuleService) UpdateHTTPDNSCustomRule(ctx context.Context, req return nil, errors.New("invalid 'rule.id'") } err = this.RunTx(func(tx *dbs.Tx) error { - oldRule, err := models.SharedHTTPDNSCustomRuleDAO.FindEnabledRule(tx, req.Rule.Id) + oldRule, app, err := ensureRuleAccess(tx, req.Rule.Id, userId) if err != nil { return err } @@ -101,15 +109,12 @@ func (this *HTTPDNSRuleService) UpdateHTTPDNSCustomRule(ctx context.Context, req return err } } - err = notifyHTTPDNSAppTasksByAppDbId(tx, int64(oldRule.AppId), models.HTTPDNSNodeTaskTypeRuleChanged) + err = notifyHTTPDNSAppTasksByAppDbId(tx, int64(app.Id), models.HTTPDNSNodeTaskTypeRuleChanged) if err != nil { return err } - targetAppDbId := req.Rule.AppId - if targetAppDbId <= 0 { - targetAppDbId = int64(oldRule.AppId) - } + targetAppDbId := int64(app.Id) return notifyHTTPDNSAppTasksByAppDbId(tx, targetAppDbId, models.HTTPDNSNodeTaskTypeRuleChanged) }) if err != nil { @@ -119,12 +124,12 @@ func (this *HTTPDNSRuleService) UpdateHTTPDNSCustomRule(ctx context.Context, req } func (this *HTTPDNSRuleService) DeleteHTTPDNSCustomRule(ctx context.Context, req *pb.DeleteHTTPDNSCustomRuleRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } err = this.RunTx(func(tx *dbs.Tx) error { - rule, err := models.SharedHTTPDNSCustomRuleDAO.FindEnabledRule(tx, req.RuleId) + rule, app, err := ensureRuleAccess(tx, req.RuleId, userId) if err != nil { return err } @@ -136,7 +141,7 @@ func (this *HTTPDNSRuleService) DeleteHTTPDNSCustomRule(ctx context.Context, req if err != nil { return err } - return notifyHTTPDNSAppTasksByAppDbId(tx, int64(rule.AppId), models.HTTPDNSNodeTaskTypeRuleChanged) + return notifyHTTPDNSAppTasksByAppDbId(tx, int64(app.Id), models.HTTPDNSNodeTaskTypeRuleChanged) }) if err != nil { return nil, err @@ -145,12 +150,12 @@ func (this *HTTPDNSRuleService) DeleteHTTPDNSCustomRule(ctx context.Context, req } func (this *HTTPDNSRuleService) UpdateHTTPDNSCustomRuleStatus(ctx context.Context, req *pb.UpdateHTTPDNSCustomRuleStatusRequest) (*pb.RPCSuccess, error) { - _, err := this.ValidateAdmin(ctx) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } err = this.RunTx(func(tx *dbs.Tx) error { - rule, err := models.SharedHTTPDNSCustomRuleDAO.FindEnabledRule(tx, req.RuleId) + rule, app, err := ensureRuleAccess(tx, req.RuleId, userId) if err != nil { return err } @@ -162,7 +167,7 @@ func (this *HTTPDNSRuleService) UpdateHTTPDNSCustomRuleStatus(ctx context.Contex if err != nil { return err } - return notifyHTTPDNSAppTasksByAppDbId(tx, int64(rule.AppId), models.HTTPDNSNodeTaskTypeRuleChanged) + return notifyHTTPDNSAppTasksByAppDbId(tx, int64(app.Id), models.HTTPDNSNodeTaskTypeRuleChanged) }) if err != nil { return nil, err @@ -171,11 +176,19 @@ func (this *HTTPDNSRuleService) UpdateHTTPDNSCustomRuleStatus(ctx context.Contex } func (this *HTTPDNSRuleService) ListHTTPDNSCustomRulesWithDomainId(ctx context.Context, req *pb.ListHTTPDNSCustomRulesWithDomainIdRequest) (*pb.ListHTTPDNSCustomRulesWithDomainIdResponse, error) { - _, _, validateErr := this.ValidateAdminAndUser(ctx, true) + _, userId, validateErr := this.ValidateAdminAndUser(ctx, true) if validateErr != nil { if _, nodeErr := this.ValidateHTTPDNSNode(ctx); nodeErr != nil { return nil, validateErr } + } else if userId > 0 { + domain, _, err := ensureDomainAccess(this.NullTx(), req.DomainId, userId) + if err != nil { + return nil, err + } + if domain == nil { + return &pb.ListHTTPDNSCustomRulesWithDomainIdResponse{}, nil + } } rules, err := models.SharedHTTPDNSCustomRuleDAO.ListEnabledRulesWithDomainId(this.NullTx(), req.DomainId) if err != nil { diff --git a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_sandbox.go b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_sandbox.go index b853f24..3892a9d 100644 --- a/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_sandbox.go +++ b/EdgeAPI/internal/rpc/services/httpdns/service_httpdns_sandbox.go @@ -60,7 +60,7 @@ type nodeClientInfo struct { } func (this *HTTPDNSSandboxService) TestHTTPDNSResolve(ctx context.Context, req *pb.TestHTTPDNSResolveRequest) (*pb.TestHTTPDNSResolveResponse, error) { - _, _, err := this.ValidateAdminAndUser(ctx, true) + _, userId, err := this.ValidateAdminAndUser(ctx, true) if err != nil { return nil, err } @@ -73,6 +73,9 @@ func (this *HTTPDNSSandboxService) TestHTTPDNSResolve(ctx context.Context, req * if err != nil { return nil, err } + if userId > 0 && app != nil && app.UserId != userId { + return nil, errors.New("access denied") + } if app == nil || !app.IsOn { return &pb.TestHTTPDNSResolveResponse{ Code: "APP_NOT_FOUND_OR_DISABLED", diff --git a/EdgeAPI/internal/rpc/services/httpdns/user_auth_helpers.go b/EdgeAPI/internal/rpc/services/httpdns/user_auth_helpers.go new file mode 100644 index 0000000..87604b4 --- /dev/null +++ b/EdgeAPI/internal/rpc/services/httpdns/user_auth_helpers.go @@ -0,0 +1,81 @@ +package httpdns + +import ( + "errors" + "strings" + + "github.com/TeaOSLab/EdgeAPI/internal/db/models" + "github.com/iwind/TeaGo/dbs" +) + +func ensureAppAccess(tx *dbs.Tx, appDbId int64, userId int64) (*models.HTTPDNSApp, error) { + app, err := models.SharedHTTPDNSAppDAO.FindEnabledApp(tx, appDbId) + if err != nil { + return nil, err + } + if app == nil { + return nil, nil + } + if userId > 0 && app.UserId != userId { + return nil, errors.New("access denied") + } + return app, nil +} + +func ensureAppAccessByAppId(tx *dbs.Tx, appId string, userId int64) (*models.HTTPDNSApp, error) { + appId = strings.TrimSpace(appId) + if len(appId) == 0 { + return nil, nil + } + app, err := models.SharedHTTPDNSAppDAO.FindEnabledAppWithAppId(tx, appId) + if err != nil { + return nil, err + } + if app == nil { + return nil, nil + } + if userId > 0 && app.UserId != userId { + return nil, errors.New("access denied") + } + return app, nil +} + +func ensureDomainAccess(tx *dbs.Tx, domainId int64, userId int64) (*models.HTTPDNSDomain, *models.HTTPDNSApp, error) { + domain, err := models.SharedHTTPDNSDomainDAO.FindEnabledDomain(tx, domainId) + if err != nil { + return nil, nil, err + } + if domain == nil { + return nil, nil, nil + } + + app, err := ensureAppAccess(tx, int64(domain.AppId), userId) + if err != nil { + return nil, nil, err + } + if app == nil { + return nil, nil, nil + } + + return domain, app, nil +} + +func ensureRuleAccess(tx *dbs.Tx, ruleId int64, userId int64) (*models.HTTPDNSCustomRule, *models.HTTPDNSApp, error) { + rule, err := models.SharedHTTPDNSCustomRuleDAO.FindEnabledRule(tx, ruleId) + if err != nil { + return nil, nil, err + } + if rule == nil { + return nil, nil, nil + } + + app, err := ensureAppAccess(tx, int64(rule.AppId), userId) + if err != nil { + return nil, nil, err + } + if app == nil { + return nil, nil, nil + } + + return rule, app, nil +} diff --git a/EdgeAPI/internal/setup/clickhouse_upgrade.go b/EdgeAPI/internal/setup/clickhouse_upgrade.go index 865c5fa..e7690d4 100644 --- a/EdgeAPI/internal/setup/clickhouse_upgrade.go +++ b/EdgeAPI/internal/setup/clickhouse_upgrade.go @@ -42,10 +42,10 @@ func EnsureClickHouseTables() error { firewall_rule_group_id UInt64 DEFAULT 0, firewall_rule_set_id UInt64 DEFAULT 0, firewall_rule_id UInt64 DEFAULT 0, - request_headers String CODEC(ZSTD(3)) DEFAULT '', - request_body String CODEC(ZSTD(3)) DEFAULT '', - response_headers String CODEC(ZSTD(3)) DEFAULT '', - response_body String CODEC(ZSTD(3)) DEFAULT '', + request_headers String DEFAULT '' CODEC(ZSTD(3)), + request_body String DEFAULT '' CODEC(ZSTD(3)), + response_headers String DEFAULT '' CODEC(ZSTD(3)), + response_body String DEFAULT '' CODEC(ZSTD(3)), INDEX idx_trace_id trace_id TYPE bloom_filter(0.01) GRANULARITY 4, INDEX idx_ip ip TYPE bloom_filter(0.01) GRANULARITY 4, INDEX idx_host host TYPE tokenbf_v1(10240, 3, 0) GRANULARITY 4, @@ -74,7 +74,7 @@ SETTINGS index_granularity = 8192`, is_recursive UInt8, error String CODEC(ZSTD(1)), ns_route_codes Array(String), - content_json String CODEC(ZSTD(3)) DEFAULT '', + content_json String DEFAULT '' CODEC(ZSTD(3)), INDEX idx_request_id request_id TYPE bloom_filter(0.01) GRANULARITY 4, INDEX idx_remote_addr remote_addr TYPE bloom_filter(0.01) GRANULARITY 4, INDEX idx_question_name question_name TYPE tokenbf_v1(10240, 3, 0) GRANULARITY 4, diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/appSettings.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/appSettings.go index 6304160..d97444c 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/appSettings.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/appSettings.go @@ -6,8 +6,10 @@ import ( "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/httpdns/httpdnsutils" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeCommon/pkg/systemconfigs" "github.com/iwind/TeaGo/actions" "github.com/iwind/TeaGo/maps" + "github.com/iwind/TeaGo/types" ) type AppSettingsAction struct { @@ -52,30 +54,83 @@ func (this *AppSettingsAction) RunGet(params struct { }, } + clusterResp, err := this.RPC().HTTPDNSClusterRPC().FindAllHTTPDNSClusters(this.AdminContext(), &pb.FindAllHTTPDNSClustersRequest{}) + if err != nil { + this.ErrorPage(err) + return + } + clusters := make([]maps.Map, 0, len(clusterResp.GetClusters())) + clusterDomainMap := map[int64]string{} + clusterNameMap := map[int64]string{} + defaultPrimaryClusterId := int64(0) + for _, cluster := range clusterResp.GetClusters() { + clusterId := cluster.GetId() + clusterName := cluster.GetName() + clusters = append(clusters, maps.Map{ + "id": clusterId, + "name": clusterName, + "serviceDomain": cluster.GetServiceDomain(), + "isDefault": cluster.GetIsDefault(), + }) + clusterDomainMap[clusterId] = cluster.GetServiceDomain() + clusterNameMap[clusterId] = clusterName + if defaultPrimaryClusterId <= 0 && cluster.GetIsDefault() { + defaultPrimaryClusterId = clusterId + } + } + + defaultBackupClusterId := int64(0) + defaultBackupResp, err := this.RPC().SysSettingRPC().ReadSysSetting(this.AdminContext(), &pb.ReadSysSettingRequest{ + Code: string(systemconfigs.SettingCodeHTTPDNSDefaultBackupClusterId), + }) + if err != nil { + this.ErrorPage(err) + return + } + if defaultBackupResp != nil && len(defaultBackupResp.GetValueJSON()) > 0 { + defaultBackupClusterId = types.Int64(string(defaultBackupResp.GetValueJSON())) + } + + primaryClusterId := app.GetInt64("primaryClusterId") + backupClusterId := app.GetInt64("backupClusterId") + settings := maps.Map{ - "appId": app.GetString("appId"), - "appStatus": app.GetBool("isOn"), - "primaryClusterId": app.GetInt64("primaryClusterId"), - "backupClusterId": app.GetInt64("backupClusterId"), - "signEnabled": app.GetBool("signEnabled"), - "signSecretPlain": app.GetString("signSecretPlain"), - "signSecretMasked": app.GetString("signSecretMasked"), - "signSecretUpdatedAt": app.GetString("signSecretUpdated"), + "appId": app.GetString("appId"), + "appStatus": app.GetBool("isOn"), + "primaryClusterId": primaryClusterId, + "backupClusterId": backupClusterId, + "defaultPrimaryClusterId": defaultPrimaryClusterId, + "defaultPrimaryClusterName": clusterNameMap[defaultPrimaryClusterId], + "defaultBackupClusterId": defaultBackupClusterId, + "defaultBackupClusterName": clusterNameMap[defaultBackupClusterId], + "primaryServiceDomain": clusterDomainMap[primaryClusterId], + "backupServiceDomain": clusterDomainMap[backupClusterId], + "signEnabled": app.GetBool("signEnabled"), + "signSecretPlain": app.GetString("signSecretPlain"), + "signSecretMasked": app.GetString("signSecretMasked"), + "signSecretUpdatedAt": app.GetString("signSecretUpdated"), } this.Data["app"] = app this.Data["settings"] = settings + this.Data["clusters"] = clusters this.Show() } func (this *AppSettingsAction) RunPost(params struct { AppId int64 - AppStatus bool + AppStatus bool + PrimaryClusterId int64 + BackupClusterId int64 Must *actions.Must CSRF *actionutils.CSRF }) { params.Must.Field("appId", params.AppId).Gt(0, "请选择应用") + if params.PrimaryClusterId > 0 && params.BackupClusterId > 0 && params.PrimaryClusterId == params.BackupClusterId { + this.FailField("backupClusterId", "备用集群不能与主集群相同") + return + } appResp, err := this.RPC().HTTPDNSAppRPC().FindHTTPDNSApp(this.AdminContext(), &pb.FindHTTPDNSAppRequest{ AppDbId: params.AppId, @@ -92,8 +147,8 @@ func (this *AppSettingsAction) RunPost(params struct { _, err = this.RPC().HTTPDNSAppRPC().UpdateHTTPDNSApp(this.AdminContext(), &pb.UpdateHTTPDNSAppRequest{ AppDbId: params.AppId, Name: appResp.GetApp().GetName(), - PrimaryClusterId: appResp.GetApp().GetPrimaryClusterId(), - BackupClusterId: appResp.GetApp().GetBackupClusterId(), + PrimaryClusterId: params.PrimaryClusterId, + BackupClusterId: params.BackupClusterId, IsOn: params.AppStatus, UserId: appResp.GetApp().GetUserId(), }) diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/create.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/create.go index 4b734ce..46c31b1 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/create.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/create.go @@ -55,6 +55,24 @@ func (this *CreateAction) RunGet(params struct{}) { } this.Data["defaultBackupClusterId"] = defaultBackupClusterId + usersResp, err := this.RPC().UserRPC().ListEnabledUsers(this.AdminContext(), &pb.ListEnabledUsersRequest{ + Offset: 0, + Size: 10_000, + }) + if err != nil { + this.ErrorPage(err) + return + } + users := make([]maps.Map, 0, len(usersResp.GetUsers())) + for _, user := range usersResp.GetUsers() { + users = append(users, maps.Map{ + "id": user.GetId(), + "fullname": user.GetFullname(), + "username": user.GetUsername(), + }) + } + this.Data["users"] = users + this.Show() } diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/init.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/init.go index e705574..fdc2e25 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/init.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/init.go @@ -18,6 +18,7 @@ func init() { Get("/sdk", new(SdkAction)). GetPost("/sdk/upload", new(SdkUploadAction)). Post("/sdk/upload/delete", new(SdkUploadDeleteAction)). + Get("/sdk/check", new(SdkCheckAction)). Get("/sdk/download", new(SdkDownloadAction)). Get("/sdk/doc", new(SdkDocAction)). GetPost("/app/settings", new(AppSettingsAction)). diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/rpc_helpers.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/rpc_helpers.go index dddb9f4..b528091 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/rpc_helpers.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/rpc_helpers.go @@ -7,11 +7,20 @@ import ( "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" - timeutil "github.com/iwind/TeaGo/utils/time" "github.com/iwind/TeaGo/maps" + timeutil "github.com/iwind/TeaGo/utils/time" ) func listAppMaps(parent *actionutils.ParentAction, keyword string) ([]maps.Map, error) { + clusterNameMap, err := loadHTTPDNSClusterNameMap(parent) + if err != nil { + return nil, err + } + userMapByID, err := loadHTTPDNSUserMap(parent) + if err != nil { + return nil, err + } + resp, err := parent.RPC().HTTPDNSAppRPC().ListHTTPDNSApps(parent.AdminContext(), &pb.ListHTTPDNSAppsRequest{ Offset: 0, Size: 10_000, @@ -30,13 +39,22 @@ func listAppMaps(parent *actionutils.ParentAction, keyword string) ([]maps.Map, return nil, err } - result = append(result, appPBToMap(app, int64(len(domainResp.GetDomains())))) + result = append(result, appPBToMap(app, int64(len(domainResp.GetDomains())), clusterNameMap, userMapByID)) } return result, nil } func findAppMap(parent *actionutils.ParentAction, appDbId int64) (maps.Map, error) { + clusterNameMap, err := loadHTTPDNSClusterNameMap(parent) + if err != nil { + return nil, err + } + userMapByID, err := loadHTTPDNSUserMap(parent) + if err != nil { + return nil, err + } + if appDbId > 0 { resp, err := parent.RPC().HTTPDNSAppRPC().FindHTTPDNSApp(parent.AdminContext(), &pb.FindHTTPDNSAppRequest{ AppDbId: appDbId, @@ -51,7 +69,7 @@ func findAppMap(parent *actionutils.ParentAction, appDbId int64) (maps.Map, erro if err != nil { return nil, err } - return appPBToMap(resp.GetApp(), int64(len(domainResp.GetDomains()))), nil + return appPBToMap(resp.GetApp(), int64(len(domainResp.GetDomains())), clusterNameMap, userMapByID), nil } } @@ -259,16 +277,37 @@ func toggleCustomRule(parent *actionutils.ParentAction, ruleId int64, isOn bool) return err } -func appPBToMap(app *pb.HTTPDNSApp, domainCount int64) maps.Map { +func appPBToMap(app *pb.HTTPDNSApp, domainCount int64, clusterNameMap map[int64]string, userMapByID map[int64]maps.Map) maps.Map { signSecret := app.GetSignSecret() + + primaryClusterID := app.GetPrimaryClusterId() + backupClusterID := app.GetBackupClusterId() + primaryClusterMap := maps.Map{"id": primaryClusterID, "name": clusterNameMap[primaryClusterID]} + backupClusterMap := maps.Map{"id": backupClusterID, "name": clusterNameMap[backupClusterID]} + + var userMap maps.Map + if app.GetUserId() > 0 { + userMap = userMapByID[app.GetUserId()] + if userMap == nil { + userMap = maps.Map{ + "id": app.GetUserId(), + "fullname": "用户#" + strconv.FormatInt(app.GetUserId(), 10), + "username": "-", + } + } + } + return maps.Map{ "id": app.GetId(), "name": app.GetName(), "appId": app.GetAppId(), - "clusterId": app.GetPrimaryClusterId(), - "primaryClusterId": app.GetPrimaryClusterId(), - "backupClusterId": app.GetBackupClusterId(), + "clusterId": primaryClusterID, + "primaryClusterId": primaryClusterID, + "backupClusterId": backupClusterID, + "primaryCluster": primaryClusterMap, + "backupCluster": backupClusterMap, "userId": app.GetUserId(), + "user": userMap, "isOn": app.GetIsOn(), "domainCount": domainCount, "sniPolicyText": "隐匿 SNI", @@ -279,6 +318,39 @@ func appPBToMap(app *pb.HTTPDNSApp, domainCount int64) maps.Map { } } +func loadHTTPDNSClusterNameMap(parent *actionutils.ParentAction) (map[int64]string, error) { + resp, err := parent.RPC().HTTPDNSClusterRPC().FindAllHTTPDNSClusters(parent.AdminContext(), &pb.FindAllHTTPDNSClustersRequest{}) + if err != nil { + return nil, err + } + + result := map[int64]string{} + for _, cluster := range resp.GetClusters() { + result[cluster.GetId()] = cluster.GetName() + } + return result, nil +} + +func loadHTTPDNSUserMap(parent *actionutils.ParentAction) (map[int64]maps.Map, error) { + resp, err := parent.RPC().UserRPC().ListEnabledUsers(parent.AdminContext(), &pb.ListEnabledUsersRequest{ + Offset: 0, + Size: 10_000, + }) + if err != nil { + return nil, err + } + + result := map[int64]maps.Map{} + for _, user := range resp.GetUsers() { + result[user.GetId()] = maps.Map{ + "id": user.GetId(), + "fullname": user.GetFullname(), + "username": user.GetUsername(), + } + } + return result, nil +} + func defaultLineField(value string) string { value = strings.TrimSpace(value) if len(value) == 0 { diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_check.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_check.go new file mode 100644 index 0000000..a40db86 --- /dev/null +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_check.go @@ -0,0 +1,67 @@ +package apps + +import ( + "net/url" + "strings" + + "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" +) + +type SdkCheckAction struct { + actionutils.ParentAction +} + +func (this *SdkCheckAction) Init() { + this.Nav("", "", "") +} + +func (this *SdkCheckAction) RunGet(params struct { + Platform string + Version string + Type string +}) { + platform, _, _, filename, err := resolveSDKPlatform(params.Platform) + if err != nil { + this.Data["exists"] = false + this.Data["message"] = err.Error() + this.Success() + return + } + + t := strings.ToLower(strings.TrimSpace(params.Type)) + if t == "doc" { + docPath := findUploadedSDKDocPath(platform, params.Version) + if len(docPath) == 0 { + this.Data["exists"] = false + this.Data["message"] = "Documentation is unavailable, please upload first" + this.Success() + return + } + + downloadURL := "/httpdns/apps/sdk/doc?platform=" + url.QueryEscape(platform) + if len(strings.TrimSpace(params.Version)) > 0 { + downloadURL += "&version=" + url.QueryEscape(strings.TrimSpace(params.Version)) + } + this.Data["exists"] = true + this.Data["url"] = downloadURL + this.Success() + return + } + + archivePath := findSDKArchivePath(filename, params.Version) + if len(archivePath) == 0 { + this.Data["exists"] = false + this.Data["message"] = "SDK package is unavailable, please upload first" + this.Success() + return + } + + downloadURL := "/httpdns/apps/sdk/download?platform=" + url.QueryEscape(platform) + if len(strings.TrimSpace(params.Version)) > 0 { + downloadURL += "&version=" + url.QueryEscape(strings.TrimSpace(params.Version)) + } + downloadURL += "&raw=1" + this.Data["exists"] = true + this.Data["url"] = downloadURL + this.Success() +} diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_doc.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_doc.go index f0f4112..95ea910 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_doc.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_doc.go @@ -1,10 +1,11 @@ package apps import ( - "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "os" "path/filepath" "strings" + + "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" ) type SdkDocAction struct { @@ -17,15 +18,18 @@ func (this *SdkDocAction) Init() { func (this *SdkDocAction) RunGet(params struct { Platform string + Version string }) { platform, _, readmeRelativePath, _, err := resolveSDKPlatform(params.Platform) if err != nil { - this.Fail(err.Error()) + this.Data["exists"] = false + this.Data["message"] = err.Error() + this.Success() return } var data []byte - uploadedDocPath := findUploadedSDKDocPath(platform) + uploadedDocPath := findUploadedSDKDocPath(platform, params.Version) if len(uploadedDocPath) > 0 { data, err = os.ReadFile(uploadedDocPath) } @@ -44,11 +48,18 @@ func (this *SdkDocAction) RunGet(params struct { } if len(data) == 0 || err != nil { - this.Fail("当前服务器未找到 SDK 集成文档,请先在“SDK 集成”页面上传对应平台文档") + this.Data["exists"] = false + this.Data["message"] = "SDK documentation is not found on server, please upload first" + this.Success() return } + downloadName := filepath.Base(uploadedDocPath) + if len(downloadName) == 0 || downloadName == "." || downloadName == string(filepath.Separator) { + downloadName = "httpdns-sdk-" + strings.ToLower(platform) + ".md" + } + this.AddHeader("Content-Type", "text/markdown; charset=utf-8") - this.AddHeader("Content-Disposition", "attachment; filename=\"httpdns-sdk-"+strings.ToLower(platform)+"-README.md\";") + this.AddHeader("Content-Disposition", "attachment; filename=\""+downloadName+"\";") _, _ = this.ResponseWriter.Write(data) } diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_download.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_download.go index 8427521..45a7066 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_download.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_download.go @@ -1,9 +1,11 @@ package apps import ( - "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "io" "os" + "path/filepath" + + "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" ) type SdkDownloadAction struct { @@ -16,30 +18,48 @@ func (this *SdkDownloadAction) Init() { func (this *SdkDownloadAction) RunGet(params struct { Platform string + Version string + Raw int }) { _, _, _, filename, err := resolveSDKPlatform(params.Platform) if err != nil { - this.Fail(err.Error()) + this.Data["exists"] = false + this.Data["message"] = err.Error() + this.Success() return } - archivePath := findSDKArchivePath(filename) + archivePath := findSDKArchivePath(filename, params.Version) if len(archivePath) == 0 { - this.Fail("当前服务器未找到 SDK 包,请先在“SDK 集成”页面上传对应平台包: " + filename) + this.Data["exists"] = false + this.Data["message"] = "SDK archive not found on server, please upload first: " + filename + this.Success() return } fp, err := os.Open(archivePath) if err != nil { - this.Fail("打开 SDK 包失败: " + err.Error()) + this.Data["exists"] = false + this.Data["message"] = "failed to open SDK archive: " + err.Error() + this.Success() return } defer func() { _ = fp.Close() }() - this.AddHeader("Content-Type", "application/zip") - this.AddHeader("Content-Disposition", "attachment; filename=\""+filename+"\";") + downloadName := filepath.Base(archivePath) + if len(downloadName) == 0 || downloadName == "." || downloadName == string(filepath.Separator) { + downloadName = filename + } + + if params.Raw == 1 { + this.AddHeader("Content-Type", "application/octet-stream") + this.AddHeader("X-SDK-Filename", downloadName) + } else { + this.AddHeader("Content-Type", "application/zip") + this.AddHeader("Content-Disposition", "attachment; filename=\""+downloadName+"\";") + } this.AddHeader("X-Accel-Buffering", "no") _, _ = io.Copy(this.ResponseWriter, fp) } diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_helpers.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_helpers.go index 42d75e5..e16d05f 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_helpers.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_helpers.go @@ -2,18 +2,58 @@ package apps import ( "errors" - "github.com/iwind/TeaGo/Tea" "os" "path/filepath" "sort" "strings" "time" + + "github.com/iwind/TeaGo/Tea" ) func sdkUploadDir() string { + dirs := sdkUploadDirs() + if len(dirs) > 0 { + return dirs[0] + } return filepath.Clean(Tea.Root + "/data/httpdns/sdk") } +func sdkUploadDirs() []string { + candidates := []string{ + filepath.Clean(Tea.Root + "/../data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/../edge-admin/data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/../edge-user/data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/../../data/httpdns/sdk"), + } + results := make([]string, 0, len(candidates)) + seen := map[string]bool{} + for _, dir := range candidates { + if len(dir) == 0 || seen[dir] { + continue + } + seen[dir] = true + results = append(results, dir) + } + return results +} + +func sdkUploadSearchDirs() []string { + dirs := sdkUploadDirs() + results := make([]string, 0, len(dirs)) + for _, dir := range dirs { + stat, err := os.Stat(dir) + if err == nil && stat.IsDir() { + results = append(results, dir) + } + } + if len(results) == 0 { + results = append(results, sdkUploadDir()) + } + return results +} + func findFirstExistingDir(paths []string) string { for _, path := range paths { stat, err := os.Stat(path) @@ -27,7 +67,7 @@ func findFirstExistingDir(paths []string) string { func findFirstExistingFile(paths []string) string { for _, path := range paths { stat, err := os.Stat(path) - if err == nil && !stat.IsDir() { + if err == nil && !stat.IsDir() && stat.Size() > 0 { return path } } @@ -45,6 +85,9 @@ func findNewestExistingFile(paths []string) string { if err != nil || stat.IsDir() { continue } + if stat.Size() <= 0 { + continue + } if len(result.path) == 0 || stat.ModTime().After(result.modTime) || (stat.ModTime().Equal(result.modTime) && path > result.path) { result.path = path result.modTime = stat.ModTime() @@ -85,22 +128,23 @@ func resolveSDKPlatform(platform string) (key string, relativeDir string, readme } } -func findSDKArchivePath(downloadFilename string) string { - searchDirs := []string{sdkUploadDir()} +func findSDKArchivePath(downloadFilename string, version string) string { + searchDirs := sdkUploadSearchDirs() - // 1) Exact filename first. - exactFiles := []string{} - for _, dir := range searchDirs { - exactFiles = append(exactFiles, filepath.Join(dir, downloadFilename)) - } - path := findFirstExistingFile(exactFiles) - if len(path) > 0 { - return path - } - - // 2) Version-suffixed archives, e.g. httpdns-sdk-android-v1.4.8.zip + normalizedVersion := strings.TrimSpace(version) base := strings.TrimSuffix(downloadFilename, ".zip") - patternName := base + "-*.zip" + if len(normalizedVersion) > 0 { + versionFiles := []string{} + for _, dir := range searchDirs { + versionFiles = append(versionFiles, filepath.Join(dir, base+"-v"+normalizedVersion+".zip")) + } + if path := findFirstExistingFile(versionFiles); len(path) > 0 { + return path + } + return "" + } + + patternName := base + "-v*.zip" matches := []string{} for _, dir := range searchDirs { found, _ := filepath.Glob(filepath.Join(dir, patternName)) @@ -115,28 +159,52 @@ func findSDKArchivePath(downloadFilename string) string { return findNewestExistingFile(matches) } + exactFiles := []string{} + for _, dir := range searchDirs { + exactFiles = append(exactFiles, filepath.Join(dir, downloadFilename)) + } + if path := findFirstExistingFile(exactFiles); len(path) > 0 { + return path + } + return "" } -func findUploadedSDKDocPath(platform string) string { +func findUploadedSDKDocPath(platform string, version string) string { platform = strings.ToLower(strings.TrimSpace(platform)) if len(platform) == 0 { return "" } - searchDir := sdkUploadDir() - exact := filepath.Join(searchDir, "httpdns-sdk-"+platform+".md") - if file := findFirstExistingFile([]string{exact}); len(file) > 0 { - return file - } - - pattern := filepath.Join(searchDir, "httpdns-sdk-"+platform+"-*.md") - matches, _ := filepath.Glob(pattern) - if len(matches) == 0 { + searchDirs := sdkUploadSearchDirs() + normalizedVersion := strings.TrimSpace(version) + if len(normalizedVersion) > 0 { + exactVersion := []string{} + for _, dir := range searchDirs { + exactVersion = append(exactVersion, filepath.Join(dir, "httpdns-sdk-"+platform+"-v"+normalizedVersion+".md")) + } + if file := findFirstExistingFile(exactVersion); len(file) > 0 { + return file + } return "" } - sort.Strings(matches) - return findNewestExistingFile(matches) + + matches := []string{} + for _, dir := range searchDirs { + pattern := filepath.Join(dir, "httpdns-sdk-"+platform+"-v*.md") + found, _ := filepath.Glob(pattern) + matches = append(matches, found...) + } + if len(matches) > 0 { + sort.Strings(matches) + return findNewestExistingFile(matches) + } + + exact := []string{} + for _, dir := range searchDirs { + exact = append(exact, filepath.Join(dir, "httpdns-sdk-"+platform+".md")) + } + return findFirstExistingFile(exact) } func findLocalSDKDocPath(platform string) string { diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload.go index f7c5d13..44bffd2 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload.go @@ -2,15 +2,16 @@ package apps import ( "errors" - "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" - "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/httpdns/httpdnsutils" - "github.com/iwind/TeaGo/actions" "os" "path/filepath" "sort" "strconv" "strings" "time" + + "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/httpdns/httpdnsutils" + "github.com/iwind/TeaGo/actions" ) type SdkUploadAction struct { @@ -44,7 +45,7 @@ func (this *SdkUploadAction) RunPost(params struct { AppId int64 Platform string Version string - SDKFile *actions.File + SdkFile *actions.File DocFile *actions.File Must *actions.Must @@ -63,7 +64,7 @@ func (this *SdkUploadAction) RunPost(params struct { return } - if params.SDKFile == nil && params.DocFile == nil { + if params.SdkFile == nil && params.DocFile == nil { this.Fail("请至少上传一个文件") return } @@ -75,24 +76,25 @@ func (this *SdkUploadAction) RunPost(params struct { return } - if params.SDKFile != nil { - filename := strings.ToLower(strings.TrimSpace(params.SDKFile.Filename)) + if params.SdkFile != nil { + filename := strings.ToLower(strings.TrimSpace(params.SdkFile.Filename)) if !strings.HasSuffix(filename, ".zip") { this.Fail("SDK 包仅支持 .zip 文件") return } - sdkData, readErr := params.SDKFile.Read() + sdkData, readErr := params.SdkFile.Read() if readErr != nil { this.Fail("读取 SDK 包失败: " + readErr.Error()) return } + if len(sdkData) == 0 { + this.Fail("SDK 包文件为空,请重新上传") + return + } baseName := strings.TrimSuffix(downloadFilename, ".zip") - err = saveSDKUploadFile(uploadDir, downloadFilename, sdkData) - if err == nil { - err = saveSDKUploadFile(uploadDir, baseName+"-v"+version+".zip", sdkData) - } + err = saveSDKUploadFile(uploadDir, baseName+"-v"+version+".zip", sdkData) if err != nil { this.Fail("保存 SDK 包失败: " + err.Error()) return @@ -111,12 +113,12 @@ func (this *SdkUploadAction) RunPost(params struct { this.Fail("读取集成文档失败: " + readErr.Error()) return } - - filename := "httpdns-sdk-" + platform + ".md" - err = saveSDKUploadFile(uploadDir, filename, docData) - if err == nil { - err = saveSDKUploadFile(uploadDir, "httpdns-sdk-"+platform+"-v"+version+".md", docData) + if len(docData) == 0 { + this.Fail("集成文档文件为空,请重新上传") + return } + + err = saveSDKUploadFile(uploadDir, "httpdns-sdk-"+platform+"-v"+version+".md", docData) if err != nil { this.Fail("保存集成文档失败: " + err.Error()) return @@ -151,12 +153,6 @@ func saveSDKUploadFile(baseDir string, filename string, data []byte) error { } func listUploadedSDKFiles() []map[string]interface{} { - dir := sdkUploadDir() - entries, err := os.ReadDir(dir) - if err != nil { - return []map[string]interface{}{} - } - type item struct { Name string Platform string @@ -166,30 +162,45 @@ func listUploadedSDKFiles() []map[string]interface{} { UpdatedAt int64 } - items := make([]item, 0) - for _, entry := range entries { - if entry.IsDir() { - continue - } - name := entry.Name() - platform, version, fileType, ok := parseSDKUploadFilename(name) - if !ok { + byName := map[string]item{} + for _, dir := range sdkUploadSearchDirs() { + entries, err := os.ReadDir(dir) + if err != nil { continue } + for _, entry := range entries { + if entry.IsDir() { + continue + } + name := entry.Name() + platform, version, fileType, ok := parseSDKUploadFilename(name) + if !ok { + continue + } - info, statErr := entry.Info() - if statErr != nil { - continue - } + info, statErr := entry.Info() + if statErr != nil { + continue + } - items = append(items, item{ - Name: name, - Platform: platform, - FileType: fileType, - Version: version, - SizeBytes: info.Size(), - UpdatedAt: info.ModTime().Unix(), - }) + current := item{ + Name: name, + Platform: platform, + FileType: fileType, + Version: version, + SizeBytes: info.Size(), + UpdatedAt: info.ModTime().Unix(), + } + old, exists := byName[name] + if !exists || current.UpdatedAt >= old.UpdatedAt { + byName[name] = current + } + } + } + + items := make([]item, 0, len(byName)) + for _, it := range byName { + items = append(items, it) } sort.Slice(items, func(i, j int) bool { @@ -200,14 +211,14 @@ func listUploadedSDKFiles() []map[string]interface{} { }) result := make([]map[string]interface{}, 0, len(items)) - for _, item := range items { + for _, it := range items { result = append(result, map[string]interface{}{ - "name": item.Name, - "platform": item.Platform, - "fileType": item.FileType, - "version": item.Version, - "sizeText": formatSDKFileSize(item.SizeBytes), - "updatedAt": time.Unix(item.UpdatedAt, 0).Format("2006-01-02 15:04:05"), + "name": it.Name, + "platform": it.Platform, + "fileType": it.FileType, + "version": it.Version, + "sizeText": formatSDKFileSize(it.SizeBytes), + "updatedAt": time.Unix(it.UpdatedAt, 0).Format("2006-01-02 15:04:05"), }) } return result @@ -231,7 +242,7 @@ func parseSDKUploadFilename(filename string) (platform string, version string, f } main := strings.TrimSuffix(strings.TrimPrefix(filename, "httpdns-sdk-"), ext) - version = "latest" + version = "" if idx := strings.Index(main, "-v"); idx > 0 && idx+2 < len(main) { version = main[idx+2:] main = main[:idx] @@ -241,6 +252,9 @@ func parseSDKUploadFilename(filename string) (platform string, version string, f switch main { case "android", "ios", "flutter": platform = main + if len(version) == 0 { + version = "-" + } return platform, version, fileType, true default: return "", "", "", false diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload_delete.go b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload_delete.go index 5a6b906..0e39379 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload_delete.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/apps/sdk_upload_delete.go @@ -1,10 +1,11 @@ package apps import ( - "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "os" "path/filepath" "strings" + + "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" ) type SdkUploadDeleteAction struct { @@ -42,15 +43,16 @@ func (this *SdkUploadDeleteAction) RunPost(params struct { return } - fullPath := filepath.Join(sdkUploadDir(), filename) - _, err := os.Stat(fullPath) - if err != nil { - this.Success() - return - } - if err = os.Remove(fullPath); err != nil { - this.Fail("删除失败: " + err.Error()) - return + for _, dir := range sdkUploadDirs() { + fullPath := filepath.Join(dir, filename) + _, err := os.Stat(fullPath) + if err != nil { + continue + } + if err = os.Remove(fullPath); err != nil { + this.Fail("删除失败: " + err.Error()) + return + } } this.Success() diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/clusters/clusterSettings.go b/EdgeAdmin/internal/web/actions/default/httpdns/clusters/clusterSettings.go index 624ebd0..1f6ef3a 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/clusters/clusterSettings.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/clusters/clusterSettings.go @@ -10,8 +10,10 @@ import ( "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs" "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/sslconfigs" + "github.com/TeaOSLab/EdgeCommon/pkg/systemconfigs" "github.com/iwind/TeaGo/actions" "github.com/iwind/TeaGo/maps" + "github.com/iwind/TeaGo/types" ) type ClusterSettingsAction struct { @@ -41,13 +43,14 @@ func (this *ClusterSettingsAction) RunGet(params struct { } settings := maps.Map{ - "name": cluster.GetString("name"), - "gatewayDomain": cluster.GetString("gatewayDomain"), - "cacheTtl": cluster.GetInt("defaultTTL"), - "fallbackTimeout": cluster.GetInt("fallbackTimeout"), - "installDir": cluster.GetString("installDir"), - "isOn": cluster.GetBool("isOn"), - "isDefaultCluster": cluster.GetBool("isDefault"), + "name": cluster.GetString("name"), + "gatewayDomain": cluster.GetString("gatewayDomain"), + "cacheTtl": cluster.GetInt("defaultTTL"), + "fallbackTimeout": cluster.GetInt("fallbackTimeout"), + "installDir": cluster.GetString("installDir"), + "isOn": cluster.GetBool("isOn"), + "isDefaultCluster": cluster.GetBool("isDefault"), + "isDefaultBackupCluster": false, } if settings.GetInt("cacheTtl") <= 0 { settings["cacheTtl"] = 30 @@ -59,6 +62,19 @@ func (this *ClusterSettingsAction) RunGet(params struct { settings["installDir"] = "/opt/edge-httpdns" } + defaultBackupResp, err := this.RPC().SysSettingRPC().ReadSysSetting(this.AdminContext(), &pb.ReadSysSettingRequest{ + Code: string(systemconfigs.SettingCodeHTTPDNSDefaultBackupClusterId), + }) + if err != nil { + this.ErrorPage(err) + return + } + defaultBackupClusterId := int64(0) + if defaultBackupResp != nil && len(defaultBackupResp.GetValueJSON()) > 0 { + defaultBackupClusterId = types.Int64(string(defaultBackupResp.GetValueJSON())) + } + settings["isDefaultBackupCluster"] = defaultBackupClusterId == params.ClusterId + listenAddresses := []*serverconfigs.NetworkAddressConfig{ { Protocol: serverconfigs.ProtocolHTTPS, @@ -104,14 +120,15 @@ func (this *ClusterSettingsAction) RunGet(params struct { } func (this *ClusterSettingsAction) RunPost(params struct { - ClusterId int64 - Name string - GatewayDomain string - CacheTtl int32 - FallbackTimeout int32 - InstallDir string - IsOn bool - IsDefaultCluster bool + ClusterId int64 + Name string + GatewayDomain string + CacheTtl int32 + FallbackTimeout int32 + InstallDir string + IsOn bool + IsDefaultCluster bool + IsDefaultBackupCluster bool Addresses []byte SslPolicyJSON []byte @@ -137,7 +154,15 @@ func (this *ClusterSettingsAction) RunPost(params struct { params.InstallDir = "/opt/edge-httpdns" } if params.IsDefaultCluster && !params.IsOn { - this.Fail("默认集群必须保持启用状态") + this.Fail("默认主集群必须保持启用状态") + return + } + if params.IsDefaultBackupCluster && !params.IsOn { + this.Fail("默认备用集群必须保持启用状态") + return + } + if params.IsDefaultCluster && params.IsDefaultBackupCluster { + this.Fail("默认主集群和默认备用集群不能是同一个集群") return } @@ -195,5 +220,33 @@ func (this *ClusterSettingsAction) RunPost(params struct { return } + backupClusterValue := int64(0) + if params.IsDefaultBackupCluster { + backupClusterValue = params.ClusterId + } else { + readResp, err := this.RPC().SysSettingRPC().ReadSysSetting(this.AdminContext(), &pb.ReadSysSettingRequest{ + Code: string(systemconfigs.SettingCodeHTTPDNSDefaultBackupClusterId), + }) + if err != nil { + this.ErrorPage(err) + return + } + if readResp != nil && len(readResp.GetValueJSON()) > 0 { + oldBackupClusterId := types.Int64(string(readResp.GetValueJSON())) + if oldBackupClusterId != params.ClusterId { + backupClusterValue = oldBackupClusterId + } + } + } + + _, err = this.RPC().SysSettingRPC().UpdateSysSetting(this.AdminContext(), &pb.UpdateSysSettingRequest{ + Code: string(systemconfigs.SettingCodeHTTPDNSDefaultBackupClusterId), + ValueJSON: []byte(strconv.FormatInt(backupClusterValue, 10)), + }) + if err != nil { + this.ErrorPage(err) + return + } + this.Success() } diff --git a/EdgeAdmin/internal/web/actions/default/httpdns/clusters/create.go b/EdgeAdmin/internal/web/actions/default/httpdns/clusters/create.go index af2c55d..61b0957 100644 --- a/EdgeAdmin/internal/web/actions/default/httpdns/clusters/create.go +++ b/EdgeAdmin/internal/web/actions/default/httpdns/clusters/create.go @@ -1,11 +1,13 @@ package clusters import ( + "strconv" "strings" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/httpdns/httpdnsutils" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeCommon/pkg/systemconfigs" "github.com/iwind/TeaGo/actions" ) @@ -23,13 +25,14 @@ func (this *CreateAction) RunGet(params struct{}) { } func (this *CreateAction) RunPost(params struct { - Name string - GatewayDomain string - CacheTtl int32 - FallbackTimeout int32 - InstallDir string - IsOn bool - IsDefault bool + Name string + GatewayDomain string + CacheTtl int32 + FallbackTimeout int32 + InstallDir string + IsOn bool + IsDefaultPrimary bool + IsDefaultBackup bool Must *actions.Must }) { @@ -49,6 +52,19 @@ func (this *CreateAction) RunPost(params struct { params.Must.Field("name", params.Name).Require("请输入集群名称") params.Must.Field("gatewayDomain", params.GatewayDomain).Require("请输入服务域名") + if params.IsDefaultPrimary && !params.IsOn { + this.Fail("默认主集群必须保持启用状态") + return + } + if params.IsDefaultBackup && !params.IsOn { + this.Fail("默认备用集群必须保持启用状态") + return + } + if params.IsDefaultPrimary && params.IsDefaultBackup { + this.Fail("默认主集群和默认备用集群不能是同一个集群") + return + } + resp, err := this.RPC().HTTPDNSClusterRPC().CreateHTTPDNSCluster(this.AdminContext(), &pb.CreateHTTPDNSClusterRequest{ Name: params.Name, ServiceDomain: params.GatewayDomain, @@ -56,13 +72,24 @@ func (this *CreateAction) RunPost(params struct { FallbackTimeoutMs: params.FallbackTimeout, InstallDir: params.InstallDir, IsOn: params.IsOn, - IsDefault: params.IsDefault, + IsDefault: params.IsDefaultPrimary, }) if err != nil { this.ErrorPage(err) return } + if params.IsDefaultBackup { + _, err = this.RPC().SysSettingRPC().UpdateSysSetting(this.AdminContext(), &pb.UpdateSysSettingRequest{ + Code: string(systemconfigs.SettingCodeHTTPDNSDefaultBackupClusterId), + ValueJSON: []byte(strconv.FormatInt(resp.GetClusterId(), 10)), + }) + if err != nil { + this.ErrorPage(err) + return + } + } + this.Data["clusterId"] = resp.GetClusterId() this.Success() } diff --git a/EdgeAdmin/internal/web/actions/default/users/setting/index.go b/EdgeAdmin/internal/web/actions/default/users/setting/index.go index 11240aa..1fa06a8 100644 --- a/EdgeAdmin/internal/web/actions/default/users/setting/index.go +++ b/EdgeAdmin/internal/web/actions/default/users/setting/index.go @@ -102,6 +102,8 @@ func (this *IndexAction) RunPost(params struct { NsIsOn bool + HttpdnsIsOn bool + Must *actions.Must CSRF *actionutils.CSRF }) { @@ -112,6 +114,15 @@ func (this *IndexAction) RunPost(params struct { Gt(0, "请选择一个集群") var config = userconfigs.DefaultUserRegisterConfig() + { + // 先读取现有配置,避免保存时把未出现在当前表单里的字段重置为默认值 + resp, err := this.RPC().SysSettingRPC().ReadSysSetting(this.AdminContext(), &pb.ReadSysSettingRequest{ + Code: systemconfigs.SettingCodeUserRegisterConfig, + }) + if err == nil && len(resp.ValueJSON) > 0 { + _ = json.Unmarshal(resp.ValueJSON, config) + } + } config.IsOn = params.IsOn config.ComplexPassword = params.ComplexPassword config.RequireVerification = params.RequireVerification @@ -142,6 +153,7 @@ func (this *IndexAction) RunPost(params struct { config.ADIsOn = params.AdIsOn config.NSIsOn = params.NsIsOn + config.HTTPDNSIsOn = params.HttpdnsIsOn configJSON, err := json.Marshal(config) if err != nil { @@ -157,10 +169,15 @@ func (this *IndexAction) RunPost(params struct { return } - if params.FeatureOp != "keep" { + featureOp := params.FeatureOp + if featureOp != "overwrite" && featureOp != "append" && featureOp != "keep" { + featureOp = "keep" + } + + if featureOp != "keep" { _, err = this.RPC().UserRPC().UpdateAllUsersFeatures(this.AdminContext(), &pb.UpdateAllUsersFeaturesRequest{ FeatureCodes: params.Features, - Overwrite: params.FeatureOp == "overwrite", + Overwrite: featureOp == "overwrite", }) if err != nil { this.ErrorPage(err) diff --git a/EdgeAdmin/web/views/@default/httpdns/addPortPopup.html b/EdgeAdmin/web/views/@default/httpdns/addPortPopup.html new file mode 100644 index 0000000..eefd320 --- /dev/null +++ b/EdgeAdmin/web/views/@default/httpdns/addPortPopup.html @@ -0,0 +1,28 @@ +{$layout "layout_popup"} + +

添加端口绑定

+

修改端口绑定

+
+ + + + + + + + + + +
网络协议 + +
端口 * + +

可以是一个数字端口(通常不超过65535),也可以是"地址:端口"的方式。支持端口范围,形式为port1-port2 + HTTP常用端口为80 + HTTPS常用端口为443 +

+
+ +
\ No newline at end of file diff --git a/EdgeAdmin/web/views/@default/httpdns/addPortPopup.js b/EdgeAdmin/web/views/@default/httpdns/addPortPopup.js new file mode 100644 index 0000000..cb2fe54 --- /dev/null +++ b/EdgeAdmin/web/views/@default/httpdns/addPortPopup.js @@ -0,0 +1,47 @@ +Tea.context(function () { + this.success = NotifyPopup; + + this.isUpdating = false + + this.address = "" + this.protocol = this.protocols[0].code + + // 初始化 + // from 用来标记是否为特殊的节点 + if (this.from.length == 0) { + if (this.protocol == "http") { + this.address = "80" + } else if (this.protocol == "https") { + this.address = "443" + } + } + + if (window.parent.UPDATING_ADDR != null) { + this.isUpdating = true + let addr = window.parent.UPDATING_ADDR + this.protocol = addr.protocol + if (addr.host.length == 0) { + this.address = addr.portRange + } else { + this.address = addr.host.quoteIP() + ":" + addr.portRange + } + } + + this.changeProtocol = function () { + if (this.from.length > 0) { + return + } + switch (this.protocol) { + case "http": + this.address = "80" + break + case "https": + this.address = "443" + break + } + } + + this.addPort = function (port) { + this.address = port + } +}); \ No newline at end of file diff --git a/EdgeAdmin/web/views/@default/httpdns/apps/appSettings.html b/EdgeAdmin/web/views/@default/httpdns/apps/appSettings.html index 5e3718f..75a47a6 100644 --- a/EdgeAdmin/web/views/@default/httpdns/apps/appSettings.html +++ b/EdgeAdmin/web/views/@default/httpdns/apps/appSettings.html @@ -67,8 +67,24 @@ - - + + + + + + @@ -86,14 +102,34 @@
App ID{{settings.appId}}主集群 + +

未设置时,按默认主集群处理(当前默认主集群:{{settings.defaultPrimaryClusterName || '-' }})。

+
备集群 + +

未设置时,按默认备用集群处理(当前默认备用集群:{{settings.defaultBackupClusterName || '-' }})。

+
应用启用
+ + + + + + + + + + + + @@ -102,14 +138,9 @@
App ID + {{settings.appId}} + +
主服务域名 + {{settings.primaryServiceDomain}} + 未配置 + +
备用服务域名 + {{settings.backupServiceDomain}} + 未配置 + +
请求验签 - {{settings.signEnabled - ? "已开启" : "已关闭"}} - {{settings.signEnabled ? "关闭请求验签" : "开启请求验签"}} + {{settings.signEnabled ? "已开启" : "已关闭"}} + {{settings.signEnabled ? "关闭请求验签" : "开启请求验签"}}

打开后,服务端会对请求进行签名校验。

{{signSecretVisible ? settings.signSecretPlain : settings.signSecretMasked}} - - - + + +

最近更新:{{settings.signSecretUpdatedAt}}

请求验签已关闭,当前不使用加签 Secret。

diff --git a/EdgeAdmin/web/views/@default/httpdns/apps/create.html b/EdgeAdmin/web/views/@default/httpdns/apps/create.html index c18f4e4..60f814a 100644 --- a/EdgeAdmin/web/views/@default/httpdns/apps/create.html +++ b/EdgeAdmin/web/views/@default/httpdns/apps/create.html @@ -34,10 +34,13 @@
所属用户 - +

可以选择当前应用所属的平台用户。

- \ No newline at end of file + diff --git a/EdgeAdmin/web/views/@default/httpdns/apps/index.html b/EdgeAdmin/web/views/@default/httpdns/apps/index.html index 0d9bc35..30effd9 100644 --- a/EdgeAdmin/web/views/@default/httpdns/apps/index.html +++ b/EdgeAdmin/web/views/@default/httpdns/apps/index.html @@ -1,4 +1,4 @@ -{$layout} +{$layout} {$template "menu"}
@@ -26,16 +26,22 @@ - - + - + + + + + + + + @@ -54,6 +60,26 @@ {{app.appId}} + + +
应用名称 AppID主集群备用集群用户 绑定域名数 状态 操作 + + {{app.primaryCluster.name || ('#' + app.primaryCluster.id)}} + + + - + + + {{app.backupCluster.name || ('#' + app.backupCluster.id)}} + + + - + + + {{app.user.fullname}} ({{app.user.username}}) + + - + {{app.domainCount}} @@ -68,4 +94,4 @@
- \ No newline at end of file + diff --git a/EdgeAdmin/web/views/@default/httpdns/apps/sdk.html b/EdgeAdmin/web/views/@default/httpdns/apps/sdk.html index 71d889e..117e4ef 100644 --- a/EdgeAdmin/web/views/@default/httpdns/apps/sdk.html +++ b/EdgeAdmin/web/views/@default/httpdns/apps/sdk.html @@ -49,8 +49,8 @@
- 下载 SDK - 下载文档 + 下载 SDK + 下载文档
@@ -63,8 +63,8 @@
- 下载 SDK - 下载文档 + 下载 SDK + 下载文档
@@ -77,8 +77,8 @@
- 下载 SDK - 下载文档 + 下载 SDK + 下载文档
diff --git a/EdgeAdmin/web/views/@default/httpdns/apps/sdk.js b/EdgeAdmin/web/views/@default/httpdns/apps/sdk.js new file mode 100644 index 0000000..fcf5fd4 --- /dev/null +++ b/EdgeAdmin/web/views/@default/httpdns/apps/sdk.js @@ -0,0 +1,123 @@ +Tea.context(function () { + this.downloadSDK = function (platform, event) { + this.checkAndDownload(platform, "sdk", event) + } + + this.downloadDoc = function (platform, event) { + this.checkAndDownload(platform, "doc", event) + } + + this.checkAndDownload = function (platform, type, event) { + if (event != null && typeof event.preventDefault == "function") { + event.preventDefault() + } + + this.$get("/httpdns/apps/sdk/check") + .params({ + platform: platform, + type: type + }) + .success(function (resp) { + let data = (resp != null && resp.data != null) ? resp.data : {} + if (!data.exists) { + teaweb.warn(data.message || "当前暂无可下载文件") + return + } + if (typeof data.url == "string" && data.url.length > 0) { + this.downloadByBlob(data.url, platform, type) + return + } + teaweb.warn("下载地址生成失败,请稍后重试") + }.bind(this)) + } + + this.downloadByBlob = function (url, platform, type) { + let defaultFileName = "httpdns-sdk-" + platform + (type == "doc" ? ".md" : ".zip") + + let xhr = new XMLHttpRequest() + xhr.open("GET", url, true) + xhr.responseType = "blob" + + xhr.onload = function () { + if (xhr.status < 200 || xhr.status >= 300) { + teaweb.warn("下载失败(HTTP " + xhr.status + ")") + return + } + if (xhr.status == 204) { + teaweb.warn("下载被浏览器扩展或下载工具拦截,请暂时关闭相关扩展后重试") + return + } + + let contentType = (xhr.getResponseHeader("Content-Type") || "").toLowerCase() + if (contentType.indexOf("application/json") >= 0) { + let reader = new FileReader() + reader.onload = function () { + try { + let json = JSON.parse(reader.result) + teaweb.warn((json && json.message) ? json.message : "下载失败,请稍后重试") + } catch (_e) { + teaweb.warn("下载失败,请稍后重试") + } + } + reader.readAsText(xhr.response) + return + } + + let disposition = xhr.getResponseHeader("Content-Disposition") || "" + let fileName = xhr.getResponseHeader("X-SDK-Filename") || this.parseFileName(disposition) || defaultFileName + if (xhr.response == null || xhr.response.size <= 0) { + teaweb.warn("下载文件为空,请检查已上传 SDK 包是否完整") + return + } + this.saveBlob(xhr.response, fileName) + }.bind(this) + + xhr.onerror = function () { + teaweb.warn("下载失败,请检查网络后重试") + } + + xhr.send() + } + + this.parseFileName = function (disposition) { + if (typeof disposition != "string" || disposition.length == 0) { + return "" + } + + let utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i) + if (utf8Match != null && utf8Match.length > 1) { + try { + return decodeURIComponent(utf8Match[1]) + } catch (_e) { + } + } + + let plainMatch = disposition.match(/filename="?([^";]+)"?/i) + if (plainMatch != null && plainMatch.length > 1) { + return plainMatch[1] + } + + return "" + } + + this.saveBlob = function (blob, fileName) { + if (window.navigator != null && typeof window.navigator.msSaveOrOpenBlob == "function") { + window.navigator.msSaveOrOpenBlob(blob, fileName) + return + } + + let objectURL = window.URL.createObjectURL(blob) + let a = document.createElement("a") + a.style.display = "none" + a.href = objectURL + a.download = fileName + document.body.appendChild(a) + a.click() + setTimeout(function () { + window.URL.revokeObjectURL(objectURL) + if (a.parentNode != null) { + a.parentNode.removeChild(a) + } + }, 30000) + } +}) diff --git a/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.html b/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.html index 08dffc8..fcc619a 100644 --- a/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.html +++ b/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.html @@ -1,4 +1,4 @@ -{$layout} +{$layout} {{app.name}} @@ -34,7 +34,7 @@ 版本号 * -

默认 `1.0.0`。同平台上传会覆盖“最新版本”下载内容。

+

默认 `1.0.0`。同平台+同版本再次上传会覆盖该版本文件。

@@ -90,4 +90,3 @@
暂无上传记录。
- diff --git a/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.js b/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.js index 4adef1a..eb36750 100644 --- a/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.js +++ b/EdgeAdmin/web/views/@default/httpdns/apps/sdkUpload.js @@ -1,4 +1,4 @@ -Tea.context(function () { +Tea.context(function () { this.platform = "android"; this.version = this.defaultVersion || "1.0.0"; this.isUploading = false; diff --git a/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.html b/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.html index 4612613..a70afec 100644 --- a/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.html +++ b/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.html @@ -11,7 +11,6 @@
集群设置
- {$template "/left_menu_with_menu"}
@@ -39,50 +38,65 @@ 节点安装根目录 -

边缘节点安装 HTTPDNS 服务的默认所在目录,此目录将被用于下发配置。通常保持默认即可。

+

边缘节点安装 HTTPDNS 服务的默认目录,通常保持默认即可。

默认解析 TTL
- +
-

SDK 向 HTTPDNS 请求域名解析时,返回的默认缓存有效期 (TTL)。SDK 超时后将重新发起请求。

+

SDK 通过 HTTPDNS 解析域名时返回的默认 TTL。

降级超时容忍度
- + 毫秒
-

HTTPDNS 节点在回源查询其它 DNS 时的最大等待时间。超出此时间将触发服务降级逻辑(返回上一有效缓存或错误)。

+

节点回源查询上游 DNS 时的最大等待时间。

启用当前集群
- +
-

如果取消启用,整个集群的 HTTPDNS 解析服务将停止。

+

取消启用后,该集群不会参与 HTTPDNS 服务。

默认集群
- - + +
-

全局设置。如果应用未单独指定集群,将默认分配和部署到该集群中。

+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ + +

同一时刻最多 1 个默认集群角色,新设置会自动取消旧设置。

@@ -91,15 +105,12 @@ 绑定端口 * - + - - + diff --git a/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.js b/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.js index 2b68ade..e932192 100644 --- a/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.js +++ b/EdgeAdmin/web/views/@default/httpdns/clusters/clusterSettings.js @@ -1,4 +1,4 @@ -Tea.context(function () { +Tea.context(function () { this.success = NotifyReloadSuccess("保存成功") this.activeSection = this.activeSection || "basic" @@ -8,9 +8,38 @@ Tea.context(function () { this.settings = {} } + // 兼容旧字段,转换成统一“默认集群 + 角色”表现 + let isDefaultPrimary = !!this.settings.isDefaultCluster + let isDefaultBackup = !!this.settings.isDefaultBackupCluster + this.settings.defaultClusterEnabled = isDefaultPrimary || isDefaultBackup + this.settings.defaultClusterRole = isDefaultBackup ? "backup" : "primary" + this.syncDefaultCluster = function () { if (!this.settings.isOn) { + this.settings.defaultClusterEnabled = false + this.settings.defaultClusterRole = "primary" this.settings.isDefaultCluster = false + this.settings.isDefaultBackupCluster = false + return + } + this.syncDefaultClusterSelection() + } + + this.syncDefaultClusterSelection = function () { + if (!this.settings.defaultClusterEnabled) { + this.settings.isDefaultCluster = false + this.settings.isDefaultBackupCluster = false + return + } + + if (this.settings.defaultClusterRole === "backup") { + this.settings.isDefaultCluster = false + this.settings.isDefaultBackupCluster = true + } else { + this.settings.defaultClusterRole = "primary" + this.settings.isDefaultCluster = true + this.settings.isDefaultBackupCluster = false } } + }) diff --git a/EdgeAdmin/web/views/@default/httpdns/clusters/create.html b/EdgeAdmin/web/views/@default/httpdns/clusters/create.html index abc8fd2..c8a88d1 100644 --- a/EdgeAdmin/web/views/@default/httpdns/clusters/create.html +++ b/EdgeAdmin/web/views/@default/httpdns/clusters/create.html @@ -1,4 +1,4 @@ -{$layout} +{$layout} {$template "menu"}
@@ -27,7 +27,7 @@
-

SDK 向 HTTPDNS 请求域名解析时,返回的默认缓存有效期 (TTL)。SDK 超时后将重新发起请求。

+

SDK 通过 HTTPDNS 解析域名时返回的默认 TTL。

@@ -37,36 +37,52 @@ 毫秒 -

HTTPDNS 节点在回源查询其它 DNS 时的最大等待时间。超出此时间将触发服务降级逻辑(返回上一有效缓存或错误)。

+

节点回源查询上游 DNS 时的最大等待时间。

节点安装根目录 -

边缘节点安装 HTTPDNS 服务的默认所在目录,此目录将被用于下发配置。通常保持默认即可。

+

边缘节点安装 HTTPDNS 服务的默认目录。

启用当前集群
- +
-

如果取消启用,整个集群的 HTTPDNS 解析服务将不被系统分配。

默认集群
- - + +
-

全局设置。如果应用未单独指定集群,将默认分配和部署到该集群中。

+
+
+
+
+ + +
+
+
+
+ + +
+
+
+
+ + - \ No newline at end of file + diff --git a/EdgeAdmin/web/views/@default/httpdns/clusters/create.js b/EdgeAdmin/web/views/@default/httpdns/clusters/create.js index 68428c0..4b6cb0c 100644 --- a/EdgeAdmin/web/views/@default/httpdns/clusters/create.js +++ b/EdgeAdmin/web/views/@default/httpdns/clusters/create.js @@ -1,4 +1,15 @@ -Tea.context(function () { +Tea.context(function () { + this.isOn = true + this.defaultClusterEnabled = false + this.defaultClusterRole = "primary" + + this.syncDefaultClusterEnabled = function () { + if (!this.isOn) { + this.defaultClusterEnabled = false + this.defaultClusterRole = "primary" + } + } + this.success = function (resp) { let clusterId = 0 if (resp != null && resp.data != null && typeof resp.data.clusterId != "undefined") { diff --git a/EdgeAdmin/web/views/@default/users/setting/index.html b/EdgeAdmin/web/views/@default/users/setting/index.html index 15573fe..ec150b8 100644 --- a/EdgeAdmin/web/views/@default/users/setting/index.html +++ b/EdgeAdmin/web/views/@default/users/setting/index.html @@ -256,5 +256,17 @@
+
+

HTTPDNS服务

+ + + + + +
开通HTTPDNS服务 +

选中表示自动为用户开通HTTPDNS服务。

+
+
+ - \ No newline at end of file + diff --git a/EdgeAdmin/web/views/@default/users/setting/index.js b/EdgeAdmin/web/views/@default/users/setting/index.js index 607dbaa..92e50ab 100644 --- a/EdgeAdmin/web/views/@default/users/setting/index.js +++ b/EdgeAdmin/web/views/@default/users/setting/index.js @@ -7,7 +7,8 @@ Tea.context(function () { this.mobileVerificationMoreOptions = false this.mobileResetPasswordMoreOptions = false - this.featureOp = "overwrite" + // 默认不影响已有用户功能,避免保存注册设置时误改用户功能绑定 + this.featureOp = "keep" this.featuresVisible = false this.showFeatures = function () { @@ -27,4 +28,4 @@ Tea.context(function () { }) return names.join(" / ") } -}) \ No newline at end of file +}) diff --git a/EdgeCommon/pkg/rpc/pb/model_httpdns_app.pb.go b/EdgeCommon/pkg/rpc/pb/model_httpdns_app.pb.go index 0d22baf..4adbe96 100644 --- a/EdgeCommon/pkg/rpc/pb/model_httpdns_app.pb.go +++ b/EdgeCommon/pkg/rpc/pb/model_httpdns_app.pb.go @@ -166,7 +166,7 @@ var File_models_model_httpdns_app_proto protoreflect.FileDescriptor var file_models_model_httpdns_app_proto_rawDesc = []byte{ 0x0a, 0x1e, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x73, 0x2f, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x64, 0x6e, 0x73, 0x5f, 0x61, 0x70, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x12, 0x02, 0x70, 0x62, 0x22, 0xee, 0x02, 0x0a, 0x0a, 0x48, 0x54, 0x54, 0x50, 0x44, 0x4e, 0x53, + 0x12, 0x02, 0x70, 0x62, 0x22, 0x86, 0x03, 0x0a, 0x0a, 0x48, 0x54, 0x54, 0x50, 0x44, 0x4e, 0x53, 0x41, 0x70, 0x70, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x61, 0x70, 0x70, 0x49, 0x64, @@ -189,7 +189,9 @@ var file_models_model_httpdns_app_proto_rawDesc = []byte{ 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, - 0x74, 0x65, 0x64, 0x41, 0x74, 0x42, 0x06, 0x5a, 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, + 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x18, + 0x0d, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x42, 0x06, 0x5a, + 0x04, 0x2e, 0x2f, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } diff --git a/EdgeCommon/pkg/rpc/pb/service_httpdns_app.pb.go b/EdgeCommon/pkg/rpc/pb/service_httpdns_app.pb.go index 4ce3123..f4a34fd 100644 --- a/EdgeCommon/pkg/rpc/pb/service_httpdns_app.pb.go +++ b/EdgeCommon/pkg/rpc/pb/service_httpdns_app.pb.go @@ -724,7 +724,7 @@ var file_service_httpdns_app_proto_rawDesc = []byte{ 0x1e, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x73, 0x2f, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x64, 0x6e, 0x73, 0x5f, 0x61, 0x70, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x73, 0x2f, 0x72, 0x70, 0x63, 0x5f, 0x6d, 0x65, 0x73, 0x73, - 0x61, 0x67, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xcf, 0x01, 0x0a, 0x17, 0x43, + 0x61, 0x67, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe7, 0x01, 0x0a, 0x17, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, 0x54, 0x54, 0x50, 0x44, 0x4e, 0x53, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x61, 0x70, @@ -737,11 +737,13 @@ var file_service_httpdns_app_proto_rawDesc = []byte{ 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x69, 0x73, 0x4f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x52, 0x04, 0x69, 0x73, 0x4f, 0x6e, 0x12, 0x20, 0x0a, 0x0b, 0x73, 0x69, 0x67, 0x6e, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, - 0x0b, 0x73, 0x69, 0x67, 0x6e, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x22, 0x34, 0x0a, 0x18, + 0x0b, 0x73, 0x69, 0x67, 0x6e, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x16, 0x0a, 0x06, + 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x75, 0x73, + 0x65, 0x72, 0x49, 0x64, 0x22, 0x34, 0x0a, 0x18, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, 0x54, 0x54, 0x50, 0x44, 0x4e, 0x53, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x70, 0x70, 0x44, 0x62, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x61, 0x70, 0x70, 0x44, 0x62, - 0x49, 0x64, 0x22, 0xb1, 0x01, 0x0a, 0x17, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x48, 0x54, 0x54, + 0x49, 0x64, 0x22, 0xc9, 0x01, 0x0a, 0x17, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x48, 0x54, 0x54, 0x50, 0x44, 0x4e, 0x53, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x70, 0x70, 0x44, 0x62, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x61, 0x70, 0x70, 0x44, 0x62, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, @@ -752,7 +754,9 @@ var file_service_httpdns_app_proto_rawDesc = []byte{ 0x75, 0x70, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0f, 0x62, 0x61, 0x63, 0x6b, 0x75, 0x70, 0x43, 0x6c, 0x75, 0x73, 0x74, 0x65, 0x72, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x69, 0x73, 0x4f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, - 0x52, 0x04, 0x69, 0x73, 0x4f, 0x6e, 0x22, 0x33, 0x0a, 0x17, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, + 0x52, 0x04, 0x69, 0x73, 0x4f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, + 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x22, 0x33, + 0x0a, 0x17, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x48, 0x54, 0x54, 0x50, 0x44, 0x4e, 0x53, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x61, 0x70, 0x70, 0x44, 0x62, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x61, 0x70, 0x70, 0x44, 0x62, 0x49, 0x64, 0x22, 0x31, 0x0a, 0x15, 0x46, diff --git a/EdgeCommon/pkg/systemconfigs/settings.go b/EdgeCommon/pkg/systemconfigs/settings.go index 45224fd..e7578b3 100644 --- a/EdgeCommon/pkg/systemconfigs/settings.go +++ b/EdgeCommon/pkg/systemconfigs/settings.go @@ -3,18 +3,18 @@ package systemconfigs type SettingCode = string const ( - SettingCodeNodeMonitor SettingCode = "nodeMonitor" // 监控节点状态 - SettingCodeClusterHealthCheck SettingCode = "clusterHealthCheck" // 集群健康检查 - SettingCodeIPListVersion SettingCode = "ipListVersion" // IP名单的版本号 - SettingCodeAdminSecurityConfig SettingCode = "adminSecurityConfig" // 管理员安全设置 - SettingCodeAdminUIConfig SettingCode = "adminUIConfig" // 管理员界面设置 - SettingCodeDatabaseConfigSetting SettingCode = "databaseConfig" // 数据库相关配置 - SettingCodeAccessLogQueue SettingCode = "accessLogQueue" // 访问日志队列 - SettingCodeCheckUpdates SettingCode = "checkUpdates" // 检查自动更新配置 + SettingCodeNodeMonitor SettingCode = "nodeMonitor" // 监控节点状态 + SettingCodeClusterHealthCheck SettingCode = "clusterHealthCheck" // 集群健康检查 + SettingCodeIPListVersion SettingCode = "ipListVersion" // IP名单版本号 + SettingCodeAdminSecurityConfig SettingCode = "adminSecurityConfig" // 管理端安全设置 + SettingCodeAdminUIConfig SettingCode = "adminUIConfig" // 管理端界面设置 + SettingCodeDatabaseConfigSetting SettingCode = "databaseConfig" // 数据库配置 + SettingCodeAccessLogQueue SettingCode = "accessLogQueue" // 访问日志队列 + SettingCodeCheckUpdates SettingCode = "checkUpdates" // 自动更新配置 + SettingCodeUserServerConfig SettingCode = "userServerConfig" // 用户服务设置 + SettingCodeUserRegisterConfig SettingCode = "userRegisterConfig" // 用户注册配置 + SettingCodeUserUIConfig SettingCode = "userUIConfig" // 用户界面配置 + SettingCodeStandaloneInstanceInitialized SettingCode = "standaloneInstanceInitialized" // 单体实例初始化状态 - SettingCodeUserServerConfig SettingCode = "userServerConfig" // 用户服务设置 - SettingCodeUserRegisterConfig SettingCode = "userRegisterConfig" // 用户注册配置 - SettingCodeUserUIConfig SettingCode = "userUIConfig" // 用户界面配置 - - SettingCodeStandaloneInstanceInitialized SettingCode = "standaloneInstanceInitialized" // 单体实例是否已经被初始化:0 未被初始化, 1 已经成功初始化 + SettingCodeHTTPDNSDefaultBackupClusterId SettingCode = "httpdnsDefaultBackupClusterId" // HTTPDNS默认备用集群ID ) diff --git a/EdgeCommon/pkg/userconfigs/user_features.go b/EdgeCommon/pkg/userconfigs/user_features.go index 2df5b35..a881206 100644 --- a/EdgeCommon/pkg/userconfigs/user_features.go +++ b/EdgeCommon/pkg/userconfigs/user_features.go @@ -9,6 +9,7 @@ type UserFeatureCode = string const ( UserFeatureCodePlan UserFeatureCode = "plan" + UserFeatureCodeHTTPDNS UserFeatureCode = "httpdns" UserFeatureCodeServerTCP UserFeatureCode = "server.tcp" UserFeatureCodeServerTCPPort UserFeatureCode = "server.tcp.port" @@ -212,6 +213,12 @@ func FindAllUserFeatures() []*UserFeature { Description: "用户可以购买和管理套餐。", SupportPlan: false, }, + { + Name: "HTTPDNS", + Code: UserFeatureCodeHTTPDNS, + Description: "用户可以使用 HTTPDNS 应用管理、访问日志和解析测试。", + SupportPlan: false, + }, } } diff --git a/EdgeCommon/pkg/userconfigs/user_register_config.go b/EdgeCommon/pkg/userconfigs/user_register_config.go index 175009e..052b56d 100644 --- a/EdgeCommon/pkg/userconfigs/user_register_config.go +++ b/EdgeCommon/pkg/userconfigs/user_register_config.go @@ -52,6 +52,8 @@ type UserRegisterConfig struct { // 开通DNS服务 NSIsOn bool `json:"nsIsOn"` // 是否开启智能DNS服务 + // 开通HTTPDNS服务 + HTTPDNSIsOn bool `json:"httpdnsIsOn"` // 是否开启用户端HTTPDNS服务 // 开通高防服务 ADIsOn bool `json:"adIsOn"` // 是否开启高防服务 @@ -63,6 +65,7 @@ func DefaultUserRegisterConfig() *UserRegisterConfig { ComplexPassword: true, CDNIsOn: true, NSIsOn: false, + HTTPDNSIsOn: false, Features: []string{ UserFeatureCodeServerAccessLog, UserFeatureCodeServerViewAccessLog, diff --git a/EdgeHttpDNS/Android SDK集成文档.md b/EdgeHttpDNS/Android SDK集成文档.md new file mode 100644 index 0000000..9dfca0d --- /dev/null +++ b/EdgeHttpDNS/Android SDK集成文档.md @@ -0,0 +1,165 @@ +# Android SDK 集成文档(Edge HTTPDNS) + +## 1. 版本与依赖 + +- SDK 模块:`EdgeHttpDNS/sdk/android/httpdns-sdk` +- `minSdkVersion`:19 +- `targetSdkVersion`:33 +- `compileSdk`:33 + +将发布包中的 `jar/aar` 放到应用模块 `libs/`,在 `app/build.gradle` 中添加: + +```gradle +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar']) + implementation 'androidx.appcompat:appcompat:1.6.1' +} +``` + +## 2. SNI 行为说明(关键) + +当前 SDK 行为与代码一致: + +1. `/resolve` 请求链路(SDK -> 你的 HTTPDNS 服务域名) +- 走域名 HTTPS +- 默认 TLS 行为(会带 SNI) + +2. 业务请求链路(拿到 CDN IP 后发起业务 HTTPS) +- 使用 `HttpDnsHttpAdapter`:按 IP 建连,`Host` 保留原域名,并清空 SNI(No-SNI) + +## 3. 初始化 SDK(推荐用 V1 客户端) + +### Kotlin + +```kotlin +import com.new.sdk.android.httpdns.HttpDnsV1Client +import com.new.sdk.android.httpdns.HttpDnsService + +val service: HttpDnsService = HttpDnsV1Client.init( + context = applicationContext, + appId = "your-app-id", + primaryServiceHost = "httpdns.example.com", + backupServiceHost = "httpdns-backup.example.com", // 可空字符串 + servicePort = 443, + signSecret = "your-sign-secret" // 可空字符串 +) +``` + +### Java + +```java +import com.new.sdk.android.httpdns.HttpDnsService; +import com.new.sdk.android.httpdns.HttpDnsV1Client; + +HttpDnsService service = HttpDnsV1Client.init( + getApplicationContext(), + "your-app-id", + "httpdns.example.com", + "httpdns-backup.example.com", // 可传 "" + 443, + "your-sign-secret" // 可传 "" +); +``` + +## 4. 解析域名获取 CDN IP + +### Kotlin + +```kotlin +import com.new.sdk.android.httpdns.HTTPDNSResult + +val result: HTTPDNSResult = HttpDnsV1Client.resolveHost( + service = service, + host = "api.example.com", + qtype = "A", // "A" 或 "AAAA" + cip = null // 可选,客户端 IP 透传 +) + +val ips = result.ips ?: emptyArray() +``` + +### Java + +```java +import com.new.sdk.android.httpdns.HTTPDNSResult; + +HTTPDNSResult result = HttpDnsV1Client.resolveHost( + service, + "api.example.com", + "A", + null +); + +String[] ips = result.getIps(); +``` + +## 5. 业务请求接入方式 + +#使用 `HttpDnsHttpAdapter`(IP 直连 + No-SNI) + +业务请求侧做“隐匿 SNI”。该适配器仅支持 HTTPS URL。 + +```kotlin +import com.new.sdk.android.httpdns.HttpDnsV1Client +import com.new.sdk.android.httpdns.network.HttpDnsAdapterOptions +import com.new.sdk.android.httpdns.network.HttpDnsAdapterRequest + +val adapter = HttpDnsV1Client.buildHttpClientAdapter( + service, + HttpDnsAdapterOptions.Builder() + .setConnectTimeoutMillis(3000) + .setReadTimeoutMillis(5000) + .setRequestIpType(com.new.sdk.android.httpdns.RequestIpType.auto) + .build() +) + +val req = HttpDnsAdapterRequest( + "GET", + "https://api.example.com/path?x=1" +) + +val resp = adapter.execute(req) +val code = resp.statusCode +val bodyBytes = resp.body +val usedIp = resp.usedIp +``` + +## 6. 预解析与常用接口 + +```kotlin +service.setPreResolveHosts(listOf("api.example.com", "img.example.com")) + +val r1 = service.getHttpDnsResultForHostSync("api.example.com", com.new.sdk.android.httpdns.RequestIpType.auto) +val r2 = service.getHttpDnsResultForHostSyncNonBlocking("api.example.com", com.new.sdk.android.httpdns.RequestIpType.auto) +``` + +- `Sync`:允许阻塞等待刷新结果(上限受 timeout 等配置影响) +- `NonBlocking`:快速返回当前可用缓存/结果,不阻塞等待 + +## 7. 验证建议 + +1. 验证 `/resolve` +- 抓包看目标应为 `https://:/resolve...` + +2. 验证业务请求(若使用 `HttpDnsHttpAdapter`) +- 目标地址应是 CDN IP +- HTTP `Host` 应为原域名 +- TLS ClientHello 不应携带 SNI(No-SNI) + +## 8. 混淆配置 + +```proguard +-keep class com.new.sdk.android.** { *; } +``` + +## 9. 常见问题 + +1. HTTPDNS 没生效 +- 检查是否真正使用了 SDK 返回 IP(或用了 `HttpDnsHttpAdapter`) +- 检查失败回退逻辑是否总是直接走了系统 DNS + +2. 使用 `HttpDnsHttpAdapter` 仍失败 +- 只支持 HTTPS URL + +3. 线上不要开启不安全证书 +- `HttpDnsAdapterOptions.Builder#setAllowInsecureCertificatesForDebugOnly(true)` 仅限调试环境 \ No newline at end of file diff --git a/EdgeHttpDNS/Changelog及升级指南_v1.4.8.txt b/EdgeHttpDNS/Changelog及升级指南_v1.4.8.txt new file mode 100644 index 0000000..7ef524d --- /dev/null +++ b/EdgeHttpDNS/Changelog及升级指南_v1.4.8.txt @@ -0,0 +1,64 @@ +1.4.8版本Changelog(HTTPDNS功能全量发布) + +1、通过智能解析把用户就近调度到最优节点,显著降低首包时延与连接抖动。 +2、支持按地域、运营商、国内/海外精细分流,提升弱网与跨网访问稳定性。 +3、解析链路内置签名鉴权与请求追踪,增强安全性与可观测性。 +4、无命中规则时自动回源兜底,保障解析连续可用。 +5、支持 A/AAAA 双栈与多记录返回,兼容不同终端网络环境。 +6、提供Android、iOS、Flutter 多端SDK 开箱可用,支持预解析、缓存与同步/非阻塞解析。 +7、提供 IP 直连适配能力(含 Host 保留与 No-SNI 模式),适配复杂 HTTPS 场景。 +8、控制台支持应用/域名/规则全流程配置与在线验证,缩短问题定位和发布周期。 +9、节点支持在线安装升级与日志上报,降低运维复杂度并提升可维护性。 + +1.4.8版本升级步骤 + +1、备份现有配置与数据: + 将 edge-api、edge-admin、edge-user 等组件目录下的 configs 文件夹,以及平台的 MySQL 数据库进行全量备份; + +2、停止旧版本进程(管理端各组件): + killall -9 edge-api + killall -9 edge-admin + killall -9 edge-user + +3、上传并解压新版本包(以 Linux x64 环境为例): + unzip -o edge-admin-linux-amd64-v1.4.8.zip -d /data/ + unzip -o edge-user-linux-amd64-v1.4.8.zip -d /data/ + +4、依次运行edge-api、edge-admin、edge-user + + # 启动 API 服务 + cd /data/edge-api/bin + chmod +x edge-api + nohup ./edge-api 2>&1 & + + # 启动管理后台 + cd /data/edge-admin/bin + chmod +x edge-admin + nohup ./edge-admin 2>&1 & + + # 启动租户控制台 + cd /data/edge-user/bin + chmod +x edge-user + nohup ./edge-user 2>&1 & + +5、检查版本状态: + 登录管理后台,确认系统版本显示为 1.4.8; + +6、配置主备集群: + 进入“HTTPDNS -> 集群列表 -> 集群设置”,按需勾选“默认主集群”或“默认备用集群”角色,以便后续应用自动关联; + +7、在线升级 HTTPDNS 节点: + 进入“HTTPDNS -> 节点列表”,点击对应节点的“详情”,在“安装信息”页面点击 **[在线安装]** 或 **[升级]**。系统会自动下发最新的 edge-httpdns 二进制文件并完成重启。 + +8、验证节点在线状态: + 等待 30 秒左右,确认节点状态恢复为“在线”,并验证硬件负载监控数据是否正常上报。 + +9、业务解析验证: + 使用控制台“解析测试”工具,验证域名在当前环境下是否能正确返回调度的 IP 地址。 + +10、完成升级。 + +特别说明: +1、在线升级模式:Edge HTTPDNS 节点支持通过管理平台一键在线升级,无需手动上传文件和重启进程。 +2、离线安装模式:如节点服务器无法连接控制台,可手动上传 edge-httpdns 压缩包并解压,更新 bin 目录下的程序文件后手动执行 `./edge-httpdns restart` 即可。 +3、SNI 隐匿功能:请确保关联的 CDN 边缘节点也已同步更新至配套版本(会自动升级)。 diff --git a/EdgeHttpDNS/Flutter SDK集成文档.md b/EdgeHttpDNS/Flutter SDK集成文档.md new file mode 100644 index 0000000..b3f787b --- /dev/null +++ b/EdgeHttpDNS/Flutter SDK集成文档.md @@ -0,0 +1,133 @@ +# Flutter SDK 集成文档(Edge HTTPDNS) + +## 1. 版本与依赖 + +- SDK 插件:`EdgeHttpDNS/sdk/flutter/new_httpdns` +- 环境要求:Flutter 2.15+ / Dart 2.15+ + +在 `pubspec.yaml` 中引用本地插件: + +```yaml +dependencies: + new_httpdns: + path: path/to/sdk/flutter/new_httpdns +``` + +执行 `flutter pub get` 完成安装。 + +## 2. SNI 行为说明(关键) + +1. **/resolve 请求链路**(SDK -> 你的 HTTPDNS 服务域名) +- 走标准 HTTPS,默认携带 SNI(用于路由到边缘控制节点)。 + +2. **业务请求链路**(拿到 CDN IP 后发起业务 HTTPS) +- **IP 直连 + No-SNI**:使用 `TrustAPPHttpdnsHttpAdapter` 进行请求。 +- 逻辑:解析域名 -> 拿到 IP 列表 -> `uri.replace(host: ip)` -> `req.headers.host = uri.host` -> **清空 SNI**。 +- 仅支持 HTTPS URL。 + +## 3. 初始化 SDK(推荐用 TrustAPP 封装) + +### Dart + +```dart +import 'package:new_httpdns/new_httpdns.dart'; + +bool ok = await TrustAPPHttpdns.init( + appId: "your-app-id", + primaryServiceHost: "httpdns.example.com", + backupServiceHost: "httpdns-backup.example.com", + servicePort: 443, + secretKey: "your-sign-secret" // 可选,开启签名校验需传入 +); + +if (ok) { + print("Edge HTTPDNS 初始化成功"); +} +``` + +## 4. 解析域名获取 CDN IP + +### Dart + +```dart +// V1 风格解析接口 +Map result = await TrustAPPHttpdns.resolveHost( + "api.example.com", + qtype: 'A', // 可选 'A' 或 'AAAA' + cip: '1.2.3.4' // 可选,模拟客户端 IP +); + +List ipv4s = result['ipv4']; +int ttl = result['ttl']; +``` + +## 5. 业务请求接入方式 + +使用 `TrustAPPHttpdnsHttpAdapter` 实现“SNI 隐匿”业务请求。 + +### Dart + +```dart +final adapter = TrustAPPHttpdns.createHttpAdapter( + options: const TrustAPPHttpdnsAdapterOptions( + connectTimeoutMs: 3000, + readTimeoutMs: 5000, + ipType: 'auto', // auto/ipv4/ipv6 + ) +); + +try { + final res = await adapter.request( + Uri.parse("https://api.example.com/path?x=1"), + method: 'GET', + headers: {'Custom-Header': 'Value'}, + body: null + ); + + print("Status Code: ${res.statusCode}"); + print("Body Length: ${res.body.length}"); + print("Used IP: ${res.usedIp}"); +} catch (e) { + print("请求失败: $e"); +} +``` + +## 6. 其他常用接口 + +```dart +// 1. 设置预解析域名 +await TrustAPPHttpdns.setPreResolveHosts(["api.example.com", "img.example.com"]); + +// 2. 只有开启缓存时可用 +Map> cacheRes = await TrustAPPHttpdns.resolveHostSyncNonBlocking("api.example.com"); + +// 3. 开启持久化缓存(重启 App 后任然可用) +await TrustAPPHttpdns.setPersistentCacheIPEnabled(true); + +// 4. 控制台日志(建议仅调试开启) +await TrustAPPHttpdns.setLogEnabled(true); +``` + +## 7. 验证建议 + +1. **验证 /resolve** +- 观察控制台日志或抓包工具,解析请求应指向 `https://:/resolve...`。 + +2. **验证业务请求** +- 如果使用 `TrustAPPHttpdnsHttpAdapter`,观察抓包: + - TCP 连接 IP 为 CDN 私有/边缘 IP。 + - HTTP `Host` 为原始域名。 + - TLS ClientHello 中 **无 SNI** 扩展。 + +## 8. 平台配置事项 + +- **Android**: 参照 Android SDK 文档配置混淆。 +- **iOS**: 如果是手动集成 Flutter 插件,请确保 iOS 模块已包含依赖的静态库,并设置 `Allow Arbitrary Loads` (如果启用 HTTP)。 + +## 9. 常见问题 + +1. **Flutter 端报错:NO_IP_AVAILABLE** +- SDK 尚未解析出有效结果,请确认域名是否已在控制台添加并配置规则。 + +2. **请求报错:TLS_EMPTY_SNI_FAILED** +- 仅支持 HTTPS 网站。如果所有 IP 尝试均失败,请检查网络权限及服务端防火墙。 diff --git a/EdgeHttpDNS/HTTPDNS用户使用手册.md b/EdgeHttpDNS/HTTPDNS用户使用手册.md new file mode 100644 index 0000000..a755c7b --- /dev/null +++ b/EdgeHttpDNS/HTTPDNS用户使用手册.md @@ -0,0 +1,98 @@ +# Edge HTTPDNS 用户使用手册 + +欢迎使用 Edge HTTPDNS 服务。本文档旨在帮助您快速完成应用创建、域名配置及解析测试,实现精准、安全的业务调度。 + +--- + +## 1. 快速入门流程 +1. **创建应用**:获取接入凭证(AppId 和 SecretKey)。 +2. **添加域名**:登记需要通过 HTTPDNS 解析的业务域名。 +3. **自定义解析规则**:设置域名对应的 IP 地址及智能分流规则。 +4. **解析测试**:通过沙箱工具验证解析是否生效。 +5. **集成 SDK**:将解析功能集成至您的 App 中。 + +--- + +## 2. 应用管理 + +应用是您接入 HTTPDNS 的基础单元。 + +### 2.1 创建应用 +1. 登录用户控制台,点击 **HTTPDNS -> 应用列表**。 +2. 点击 **创建应用**。 +3. 填写应用名称(如“我的安卓App”)。 +4. 系统会自动关联默认的服务域名,无需手动选择。 + +### 2.2 获取接入凭证 +在应用详情页面,您可以找到: +* **AppId**:应用的唯一识别 ID。 +* **SecretKey**:签名密钥。**请务必妥善保管,切勿泄露。** 在 SDK 初始化时使用此密钥可开启“签名鉴权”,防止解析接口被他人盗刷。 + +--- + +## 3. 域名与记录配置 + +### 3.1 添加域名 +1. 进入应用详情页,切换至 **域名管理** 标签。 +2. 点击 **添加域名**,输入您的业务域名(如 `api.example.com`)。 + +### 3.2 自定义解析规则 +**作用**:自定义解析规则允许您根据终端用户的网络环境(如运营商)或物理位置,为其分配最优的访问地址。通过精细化的线路调度,可以有效降低跨境或跨网访问带来的延迟,提升 App 的响应速度。 + +点击域名后的 **解析规则**,进入详细设置: +* **解析类型**:支持 **A 记录 (IPv4)** 和 **AAAA 记录 (IPv6)**。 +* **线路选择**:可选择针对特定运营商(如:移动、电信、联通)或特定地域(如:浙江省、海外)进行精准匹配。若不选择则代表全局默认配置。 +* **解析结果**:填写您的服务器目标 IP 地址。 +* **TTL**:解析结果在客户端缓存的时间。默认为 30 秒,建议保持默认以兼顾调度灵活性。 + +--- + +## 4. 配合 CDN 实现网络加速与安全 + +Edge HTTPDNS 不仅仅提供域名解析功能,更通过与 CDN 节点的深度集成,解决了移动端常见的 **HTTPS SNI 隐匿访问**及 **跨运营商加速**问题。 + +### 4.1 自动获取 CDN 边缘节点 +如果您在系统内开通了 **CDN 加速服务**,只需将业务域名配置在 CDN 平台中,并将其 CNAME 解析指向 CDN 提供的地址: +* **智能调度**:HTTPDNS 会自动识别该域名已接入 CDN,并针对终端用户的地理位置和运营商,智能返回最优的 **CDN 边缘节点 IP**。 +* **无感知兜底**:如果域名未接入 CDN 或未配置解析规则,HTTPDNS 将自动回源查询 **权威 DNS**,并返回业务真实的源站 IP,确保解析永不中断。 + +### 4.2 解决 HTTPS SNI 隐匿问题 +在使用 IP 直连(如 `https://1.2.3.4/path`)访问 HTTPS 业务时,传统的网络库会因为无法获取正确的 Host 导致 SSL 握手失败。 + +**我们的方案:** +* **配合 CDN 节点**:我们的 CDN 节点已针对 HTTPDNS 进行了特殊适配。 +* **SDK 自动适配**:SDK 内部集成了标准适配器。在您的代码中,只需配合解析出的 IP 设置 HTTP 请求头的 `Host` 字段,即可透明地完成 SNI 握手,无需复杂的 SSL 改写逻辑。 +* **稳定性保障**:通过 CDN 节点的全局负载均衡,即使某个节点异常,HTTPDNS 也会实时踢除并将流量导向其他可用节点,确保业务高可用。 + +--- + +## 4. 调试与验证 + +### 4.1 在线解析测试 +在左侧菜单进入 **解析测试**: +1. 选择您创建的 **应用**、**HTTPDNS 服务域名** 和 **待解析域名**。 +2. **模拟客户端 IP**(可选):输入特定地区的 IP,验证该地区的解析结果是否符合预期(地域调度验证)。 +3. 点击 **在线解析**,查看返回的具体 IP 列表。 + +### 4.2 访问日志查询 +在 **访问日志** 中,您可以实时监控解析请求: +* 查看各个 AppId 下域名的解析成功率。 +* 查看请求的来源 IP、耗时以及命中的路由规则。 + +--- + +## 5. 获取 SDK +在 **应用详情 -> SDK下载** 中: +* 您可以下载最新版本的 Android、iOS 或 Flutter SDK 压缩包。 +* 查看配套的 **SDK 集成文档**。 + +--- + +## 6. 常见问题 (FAQ) + +* **Q:为什么我设置了记录,解析测试却返回为空?** + * A:请检查记录是否已启用;或者检查该域名是否已被添加到对应的 AppId 允许列表下。 +* **Q:如何应对冷启动时的解析延迟?** + * A:建议在 SDK 初始化后调用“解析预热”接口,提前将热点域名加载至缓存。 +* **Q:SecretKey 泄露了怎么办?** + * A:请在应用设置中重置 SecretKey,并在 App 代码中同步更新。 diff --git a/EdgeHttpDNS/HTTPDNS管理员配置手册.md b/EdgeHttpDNS/HTTPDNS管理员配置手册.md new file mode 100644 index 0000000..5981f4b --- /dev/null +++ b/EdgeHttpDNS/HTTPDNS管理员配置手册.md @@ -0,0 +1,82 @@ +# Edge HTTPDNS 管理员配置手册 + +本文档汇总了 Edge HTTPDNS 的核心配置流程,重点介绍了集群管理、节点在线安装以及多集群调度的详细操作。 + +--- + +## 1. 集群管理 + +集群是 HTTPDNS 服务的基本组织单元。通过设置“默认”角色,可以实现应用配置的自动关联与 SDK 侧的高可用容灾。 + +### 1.1 默认集群角色定义 +在“集群设置”中,您可以将集群开启为 **“设为默认集群”**,并指派以下角色: + +* **默认主集群**: + * **自动关联**:当在控制台“添加应用”时,系统会自动将该应用关联到此默认主集群。 + * **服务首选**:SDK 初始化后,会优先使用该集群的服务域名进行解析请求。 +* **默认备用集群**: + * **自动容灾**:当默认主集群的节点全部宕机或网络不可达时,SDK 会自动切换至默认备用集群进行解析,确保业务不中断。 + * **自动关联**:与主集群一样,新应用创建时也会自动关联此备用集群信息。 + +> **注意**:同一时刻,系统内仅允许存在一个“默认主集群”和一个“默认备用集群”。新设置的默认集群会自动取消之前的旧设置。 + +### 1.2 核心参数配置 +* **服务域名**:该集群对外提供 HTTPDNS 服务的接入地址。 +* **降级超时容忍度**:指节点回源查询上游 DNS 时的最大等待时间(单位:毫秒)。若超过此阈值未获得结果,将视作解析失败。该选项可在“集群设置”中统一调整。 +* **默认 TTL**:解析结果在客户端缓存的缺省时长(默认 30s)。 +* **TLS 设置**: + * **端口绑定**:通常绑定 `443`。 + * **SSL 证书**:必须配置合法证书,否则 SDK 的 HTTPS 请求将失败。 + * **TLS 版本**:默认支持 TLS 1.1 及以上版本。 + +--- + +## 2. 节点安装与维护 + +节点是处理解析请求的实体。Edge HTTPDNS 支持“在线安装”。 + +### 2.1 在线安装 +1. **创建节点**:在集群下点击“创建节点”,填写名称及公网 IP。 +2. **配置 SSH**:在节点详情中点击“设置 SSH”,输入服务器的 Host、Port 及登录授权。 +3. **启动安装**:在“安装信息”页面点击 **[开始安装]**。 + * 自动下发二进制文件及服务脚本。 + * 自动生成 `configs/api_httpdns.yaml`(包含节点识别需要的 `nodeId` 和 `secret`)。 +4. **实时状态**:安装成功后,节点状态变为 **[在线]**,控制台每 30 秒更新一次节点的 CPU、内存及负载数据。 + +--- + +## 3. 应用与解析规则 + +### 3.1 接入应用管理 +* **AppId/SecretKey**:创建应用后生成的凭证。应用在创建时已根据上述“默认集群”设定自动关联了服务入口。 +* **鉴权配置**:开启“签名鉴权”可配合 SDK 的 `setSecretKey` 接口,杜绝接口被盗刷风险。 + +### 3.2 智能解析策略 +* **线路/地域匹配**:根据来源运营商和地理位置返回最优 IP。 + +--- + +## 4. 调试与监控 + +### 4.1 解析测试 +在 **调试工具 -> 解析测试** 中,您可以模拟客户端请求: +* 支持指定 **目标应用** 与 **所属集群**。 +* 支持模拟 **客户端 IP** 以验证 ECS 掩码及地域调度效果。 +* 实时展示请求 URL、客户端归属地、命中线路以及解析结果(IP 列表与 TTL)。 + +### 4.2 访问日志 +在 **访问日志** 菜单中,可实时查阅所有终端发起的解析请求: +* 记录包括:请求时间、客户端 IP/操作系统、SDK 版本、解析域名、耗时以及最终返回的 IP 结果。 +* 支持按 AppID、域名、状态(成功/失败)或关键字搜索排查。 + +### 4.3 运行日志 +记录服务端及节点的底层运行事件: +* 包括节点心跳、SSL 证书加载、API 连接状态等系统级信息。 +* 分为 Error、Warning、Info 等级别,是排查节点离线或连接故障的首要工具。 + +--- + +## 5. 常见问题 + +* **节点与 API 时间偏离**:若节点时间与 API Server 相差超过 30s,会导致鉴权失败(SIGN_INVALID)。请务必开启 NTP 时间同步。 +* **SDK 无法连接备用集群**:请检查默认备用集群的 SSL 证书是否有效,以及防火墙端口是否开放。 diff --git a/EdgeHttpDNS/bin/edge-httpdns.exe b/EdgeHttpDNS/bin/edge-httpdns.exe new file mode 100644 index 0000000..7e779b7 Binary files /dev/null and b/EdgeHttpDNS/bin/edge-httpdns.exe differ diff --git a/EdgeHttpDNS/iOS SDK集成文档.md b/EdgeHttpDNS/iOS SDK集成文档.md new file mode 100644 index 0000000..ba50ec4 --- /dev/null +++ b/EdgeHttpDNS/iOS SDK集成文档.md @@ -0,0 +1,124 @@ +# iOS SDK 集成文档(Edge HTTPDNS) + +## 1. 版本与依赖 + +- SDK 模块:`EdgeHttpDNS/sdk/ios/NewHttpDNS` +- 支持系统:iOS 11.0+ +- 集成方式: + - **CocoaPods**:在 `Podfile` 中添加 `pod 'NewHTTPDNS', :path => 'path/to/sdk/ios'` + - **手动集成**:将 `NewHttpDNS` 源码或编译后的静态库导入项目,并添加依赖的系统库(Foundation, CFNetwork, SystemConfiguration)。 + +## 2. SNI 行为说明(关键) + +1. **/resolve 请求链路**(SDK -> 你的 HTTPDNS 服务域名) +- 使用标准 HTTPS 请求。 +- 默认携带 SNI(用于通过 WAF/CDN 识别服务域名)。 + +2. **业务请求链路**(拿到 CDN IP 后通过 `HttpdnsEdgeService` 发起业务 HTTPS) +- **IP 直连 + No-SNI**:SDK 会建立与 IP 的连接,并将 `NSURLRequest` 的 `URL` 替换为 IP,同时保留 `Host` 头部为原域名。 +- **证书校验**:由于清空了 SNI,常规 SNI 校验会跳过,需确保后端节点支持 Host 匹配证书。 + +## 3. 初始化 SDK(推荐用 EdgeService 封装) + +### Objective-C + +```objective-c +#import + +HttpdnsEdgeService *service = [[HttpdnsEdgeService alloc] initWithAppId:@"your-app-id" + primaryServiceHost:@"httpdns.example.com" + backupServiceHost:@"httpdns-backup.example.com" + servicePort:443 + signSecret:@"your-sign-secret"]; +``` + +### Swift + +```swift +import NewHttpDNS + +let service = HttpdnsEdgeService(appId: "your-app-id", + primaryServiceHost: "httpdns.example.com", + backupServiceHost: "httpdns-backup.example.com", + servicePort: 443, + signSecret: "your-sign-secret") +``` + +## 4. 解析域名获取 CDN IP + +### Objective-C + +```objective-c +[service resolveHost:@"api.example.com" + queryType:@"A" + completion:^(HttpdnsEdgeResolveResult * _Nullable result, NSError * _Nullable error) { + if (result) { + NSLog(@"IPv4s: %@", result.ipv4s); + NSLog(@"TTL: %ld", (long)result.ttl); + } +}]; +``` + +### Swift + +```swift +service.resolveHost("api.example.com", queryType: "A") { result, error in + if let ips = result?.ipv4s { + print("Resolved IPs: \(ips)") + } +} +``` + +## 5. 业务请求接入方式 + +使用 `HttpdnsEdgeService` 提供的 `requestURL` 方法,自动处理 IP 直连与 SNI 隐藏。 + +### Objective-C + +```objective-c +NSURL *url = [NSURL URLWithString:@"https://api.example.com/path?x=1"]; +[service requestURL:url + method:@"GET" + headers:@{@"Custom-Header": @"Value"} + body:nil + completion:^(NSData * _Nullable data, NSHTTPURLResponse * _Nullable response, NSError * _Nullable error) { + if (!error) { + NSLog(@"Status Code: %ld", (long)response.statusCode); + // 处理 data + } +}]; +``` + +### Swift + +```swift +let url = URL(string: "https://api.example.com/path?x=1")! +service.requestURL(url, method: "GET", headers: ["Custom-Header": "Value"], body: nil) { data, response, error in + if let resp = response { + print("Status Code: \(resp.statusCode)") + } +} +``` + +## 6. 验证建议 + +1. **验证 /resolve** +- 观察网络请求,应指向 `https://httpdns.example.com/resolve?appId=...&dn=...`。 +- 确认返回 JSON 包含 `code: "SUCCESS"`。 + +2. **验证业务请求** +- 确认请求握手阶段不携带 SNI 扩展。 +- 确认请求的 TCP 连接目标为解析出的私有 IP/CDN IP。 + +## 7. 常见问题 + +1. **编译报错:找不到头文件** +- 请确认 `Header Search Paths` 包含 SDK 路径。 +- 如果使用 CocoaPods,请确保执行 `pod install` 并打开 `.xcworkspace`。 + +2. **请求返回 403 (Sign Invalid)** +- 确认控制台已开启“签名校验”,且本地传入的 `signSecret` 与控制台一致。 +- 确认系统时间正常(差值超过 30s 可能导致签名失效)。 + +3. **HTTPS 证书验证失败** +- 检查 `HttpdnsEdgeService` 是否能正确匹配证书,通常是在 No-SNI 模式下通过 `Host` 字段匹配。 diff --git a/EdgeHttpDNS/internal/nodes/resolve_server.go b/EdgeHttpDNS/internal/nodes/resolve_server.go index 0ab8440..31bdc89 100644 --- a/EdgeHttpDNS/internal/nodes/resolve_server.go +++ b/EdgeHttpDNS/internal/nodes/resolve_server.go @@ -130,8 +130,14 @@ func NewResolveServer(quitCh <-chan struct{}, snapshotManager *SnapshotManager) IdleTimeout: 75 * time.Second, MaxHeaderBytes: 8 * 1024, TLSConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, + MinVersion: tls.VersionTLS11, + // /resolve is a small JSON API; pin to HTTP/1.1 to avoid ALPN/h2 handshake variance + // across some clients and middleboxes. + NextProtos: []string{"http/1.1"}, }, + // Disable automatic HTTP/2 upgrade on TLS listeners. This keeps handshake behavior + // deterministic for SDK resolve calls. + TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){}, } return instance diff --git a/EdgeHttpDNS/sdk/.tmp_android_bundle/README.md b/EdgeHttpDNS/sdk/.tmp_android_bundle/README.md new file mode 100644 index 0000000..717b47f --- /dev/null +++ b/EdgeHttpDNS/sdk/.tmp_android_bundle/README.md @@ -0,0 +1,77 @@ +# HTTPDNS Android SDK (SNI Hidden v1.0.0) + +## 1. Init + +```java +import com.Trust.sdk.android.httpdns.HttpDns; +import com.Trust.sdk.android.httpdns.HttpDnsService; +import com.Trust.sdk.android.httpdns.InitConfig; + +String appId = "app1f1ndpo9"; + +new InitConfig.Builder() + .setContext(context) + .setPrimaryServiceHost("httpdns-a.example.com") + .setBackupServiceHost("httpdns-b.example.com") + .setServicePort(443) + .setSecretKey("your-sign-secret") // optional if sign is enabled + .setEnableHttps(true) + .buildFor(appId); + +HttpDnsService httpDnsService = HttpDns.getService(appId); +``` + +## 2. Resolve + +```java +HTTPDNSResult result = httpDnsService.getHttpDnsResultForHostSyncNonBlocking( + "api.business.com", + RequestIpType.auto, + null, + null +); +``` + +## 3. Official HTTP Adapter (IP + Empty-SNI + Host) + +```java +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterOptions; +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterRequest; +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterResponse; +import com.Trust.sdk.android.httpdns.network.HttpDnsHttpAdapter; + +HttpDnsHttpAdapter adapter = HttpDns.buildHttpClientAdapter( + httpDnsService, + new HttpDnsAdapterOptions.Builder() + .setConnectTimeoutMillis(3000) + .setReadTimeoutMillis(5000) + .setRequestIpType(RequestIpType.auto) + .setAllowInsecureCertificatesForDebugOnly(false) + .build() +); + +HttpDnsAdapterResponse response = adapter.execute( + new HttpDnsAdapterRequest("GET", "https://api.business.com/v1/ping") +); +``` + +Behavior is fixed: +- Resolve by `/resolve`. +- Connect to resolved IP over HTTPS. +- Keep `Host` header as business domain. +- No fallback to domain direct request. + +## 4. Public Errors + +- `NO_IP_AVAILABLE` +- `TLS_EMPTY_SNI_FAILED` +- `HOST_ROUTE_REJECTED` +- `RESOLVE_SIGN_INVALID` + +## 5. Removed Public Params + +Do not use legacy public parameters: +- `accountId` +- `serviceDomain` +- `endpoint` +- `aesSecretKey` diff --git a/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-crashdefend-0.0.6.jar b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-crashdefend-0.0.6.jar new file mode 100644 index 0000000..c2547d6 Binary files /dev/null and b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-crashdefend-0.0.6.jar differ diff --git a/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-httpdns-2.6.7.aar b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-httpdns-2.6.7.aar new file mode 100644 index 0000000..6bacaf9 Binary files /dev/null and b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-httpdns-2.6.7.aar differ diff --git a/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-ipdetector-1.2.0.aar b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-ipdetector-1.2.0.aar new file mode 100644 index 0000000..843f9d7 Binary files /dev/null and b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-ipdetector-1.2.0.aar differ diff --git a/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-logger-1.2.0.aar b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-logger-1.2.0.aar new file mode 100644 index 0000000..d3bb217 Binary files /dev/null and b/EdgeHttpDNS/sdk/.tmp_android_bundle/alicloud-android-logger-1.2.0.aar differ diff --git a/EdgeHttpDNS/sdk/.tmp_android_bundle/proguard-rules.pro b/EdgeHttpDNS/sdk/.tmp_android_bundle/proguard-rules.pro new file mode 100644 index 0000000..c1def44 --- /dev/null +++ b/EdgeHttpDNS/sdk/.tmp_android_bundle/proguard-rules.pro @@ -0,0 +1,68 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/ryan/Downloads/adt-bundle-mac-x86_64-20131030/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} +-optimizationpasses 3 +-dontoptimize +-dontusemixedcaseclassnames +-dontskipnonpubliclibraryclasses +-verbose +-overloadaggressively +#-allowaccessmodification +-useuniqueclassmembernames + +-dontwarn com.alibaba.sdk.android.httpdns.net.HttpDnsNetworkDetector + +-keeppackagenames com.alibaba.sdk.android.httpdns +-flattenpackagehierarchy com.alibaba.sdk.android.httpdns +-keep class com.alibaba.sdk.android.httpdns.HttpDns{*;} +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsService{*;} +-keep class com.alibaba.sdk.android.httpdns.impl.ErrorImpl{*;} +-keep interface com.alibaba.sdk.android.httpdns.SyncService{*;} +-keep class com.alibaba.sdk.android.httpdns.InitConfig{*;} +-keep class com.alibaba.sdk.android.httpdns.InitConfig$Builder{*;} +-keep class com.alibaba.sdk.android.httpdns.RequestIpType{*;} +-keep interface com.alibaba.sdk.android.httpdns.DegradationFilter{*;} +-keep interface com.alibaba.sdk.android.httpdns.NotUseHttpDnsFilter{*;} +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsCallback{*;} +-keep class com.alibaba.sdk.android.httpdns.ranking.IPRankingBean{*;} +-keep interface com.alibaba.sdk.android.httpdns.ILogger{*;} +-keep interface com.alibaba.sdk.android.httpdns.CacheTtlChanger{*;} +-keep class com.alibaba.sdk.android.httpdns.NetType{*;} +-keepclasseswithmembers class com.alibaba.sdk.android.httpdns.log.HttpDnsLog { + public static *** setLogger(***); + public static *** removeLogger(***); + public static *** enable(***); +} +-keep class com.alibaba.sdk.android.httpdns.HTTPDNSResult{*;} +-keepclasseswithmembers class com.alibaba.sdk.android.httpdns.HttpDnsSettings { + public static *** setDailyReport(***); + public static *** setNetworkChecker(***); +} + +-keep class com.alibaba.sdk.android.httpdns.net.HttpDnsNetworkDetector { + public ; + public ; +} + +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsSettings$NetworkChecker{*;} +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsSettings$NetworkDetector{*;} +-keep class com.alibaba.sdk.android.httpdns.utils.CommonUtil{ + public ; + public ; +} +-keep enum com.alibaba.sdk.android.httpdns.Region {*;} +-keep class com.alibaba.sdk.android.httpdns.exception.InitException{*;} diff --git a/EdgeHttpDNS/sdk/SOURCE_LOCK.md b/EdgeHttpDNS/sdk/SOURCE_LOCK.md index e1f0194..d99bf50 100644 --- a/EdgeHttpDNS/sdk/SOURCE_LOCK.md +++ b/EdgeHttpDNS/sdk/SOURCE_LOCK.md @@ -6,20 +6,20 @@ Fetched at (UTC): `2026-02-18T09:31:28Z` ## Android SDK -- Upstream repository: `https://github.com/aliyun/alibabacloud-httpdns-android-sdk` +- Upstream repository: `https://github.com/TrustAPP/Trustcloud-httpdns-android-sdk` - Locked commit: `eeb17d677161ec94b5f41a9d6437501ddc24e6d2` - Local path: `EdgeHttpDNS/sdk/android` ## iOS SDK -- Upstream repository: `https://github.com/aliyun/alibabacloud-httpdns-ios-sdk` +- Upstream repository: `https://github.com/TrustAPP/Trustcloud-httpdns-ios-sdk` - Locked commit: `19f5bacd1d1399a00ba654bb72ababb3e91d0a3a` - Local path: `EdgeHttpDNS/sdk/ios` ## Flutter Plugin SDK -- Upstream repository: `https://github.com/aliyun/alicloud-flutter-demo` +- Upstream repository: `https://github.com/TrustAPP/Trust-flutter-demo` - Locked commit: `588b807e5480d8592c57d439a6b1c52e8c313569` -- Imported subtree: `httpdns_flutter_demo/packages/aliyun_httpdns` -- Local path: `EdgeHttpDNS/sdk/flutter/aliyun_httpdns` +- Imported subtree: `httpdns_flutter_demo/packages/TrustAPP_httpdns` +- Local path: `EdgeHttpDNS/sdk/flutter/TrustAPP_httpdns` diff --git a/EdgeHttpDNS/sdk/THIRD_PARTY_NOTICES.md b/EdgeHttpDNS/sdk/THIRD_PARTY_NOTICES.md index 1ce5e94..062c88e 100644 --- a/EdgeHttpDNS/sdk/THIRD_PARTY_NOTICES.md +++ b/EdgeHttpDNS/sdk/THIRD_PARTY_NOTICES.md @@ -1,27 +1,27 @@ # Third-Party Notices for EdgeHttpDNS SDK Sources -This directory includes third-party source snapshots imported from Alibaba Cloud open-source repositories. +This directory includes third-party source snapshots imported from Trust Cloud open-source repositories. ## 1) Android SDK (`EdgeHttpDNS/sdk/android`) -- Source: `https://github.com/aliyun/alibabacloud-httpdns-android-sdk` +- Source: `https://github.com/TrustAPP/Trustcloud-httpdns-android-sdk` - Commit: `eeb17d677161ec94b5f41a9d6437501ddc24e6d2` - License file in imported source: - `EdgeHttpDNS/sdk/android/LICENSE` - Observed license: MIT License -## 2) Flutter plugin (`EdgeHttpDNS/sdk/flutter/aliyun_httpdns`) +## 2) Flutter plugin (`EdgeHttpDNS/sdk/flutter/TrustAPP_httpdns`) -- Source: `https://github.com/aliyun/alicloud-flutter-demo` +- Source: `https://github.com/TrustAPP/Trust-flutter-demo` - Commit: `588b807e5480d8592c57d439a6b1c52e8c313569` -- Imported subtree: `httpdns_flutter_demo/packages/aliyun_httpdns` +- Imported subtree: `httpdns_flutter_demo/packages/TrustAPP_httpdns` - License file in imported source: - - `EdgeHttpDNS/sdk/flutter/aliyun_httpdns/LICENSE` + - `EdgeHttpDNS/sdk/flutter/TrustAPP_httpdns/LICENSE` - Observed license: MIT License ## 3) iOS SDK (`EdgeHttpDNS/sdk/ios`) -- Source: `https://github.com/aliyun/alibabacloud-httpdns-ios-sdk` +- Source: `https://github.com/TrustAPP/Trustcloud-httpdns-ios-sdk` - Commit: `19f5bacd1d1399a00ba654bb72ababb3e91d0a3a` - Current status: - No standalone top-level `LICENSE` file was found in the upstream repository snapshot imported here. diff --git a/EdgeHttpDNS/sdk/android/README.md b/EdgeHttpDNS/sdk/android/README.md index ce9312b..717b47f 100644 --- a/EdgeHttpDNS/sdk/android/README.md +++ b/EdgeHttpDNS/sdk/android/README.md @@ -1,11 +1,11 @@ -# HTTPDNS Android SDK (SNI Hidden v1.0.0) +# HTTPDNS Android SDK (SNI Hidden v1.0.0) ## 1. Init ```java -import com.alibaba.sdk.android.httpdns.HttpDns; -import com.alibaba.sdk.android.httpdns.HttpDnsService; -import com.alibaba.sdk.android.httpdns.InitConfig; +import com.Trust.sdk.android.httpdns.HttpDns; +import com.Trust.sdk.android.httpdns.HttpDnsService; +import com.Trust.sdk.android.httpdns.InitConfig; String appId = "app1f1ndpo9"; @@ -35,10 +35,10 @@ HTTPDNSResult result = httpDnsService.getHttpDnsResultForHostSyncNonBlocking( ## 3. Official HTTP Adapter (IP + Empty-SNI + Host) ```java -import com.alibaba.sdk.android.httpdns.network.HttpDnsAdapterOptions; -import com.alibaba.sdk.android.httpdns.network.HttpDnsAdapterRequest; -import com.alibaba.sdk.android.httpdns.network.HttpDnsAdapterResponse; -import com.alibaba.sdk.android.httpdns.network.HttpDnsHttpAdapter; +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterOptions; +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterRequest; +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterResponse; +import com.Trust.sdk.android.httpdns.network.HttpDnsHttpAdapter; HttpDnsHttpAdapter adapter = HttpDns.buildHttpClientAdapter( httpDnsService, diff --git a/EdgeHttpDNS/sdk/android/app/build.gradle b/EdgeHttpDNS/sdk/android/app/build.gradle index 269ea3b..a50f3cb 100644 --- a/EdgeHttpDNS/sdk/android/app/build.gradle +++ b/EdgeHttpDNS/sdk/android/app/build.gradle @@ -26,7 +26,7 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } forTest { - // 注意这里的配置,并不是需要编译forTest的app,而是避免httpdns-sdk在AndroidStudio改为end2end运行测试时 BuildVariants报错 + // 娉ㄦ剰杩欓噷鐨勯厤缃紝骞朵笉鏄渶瑕佺紪璇慺orTest鐨刟pp锛岃€屾槸閬垮厤httpdns-sdk鍦ˋndroidStudio鏀逛负end2end杩愯娴嬭瘯鏃?BuildVariants鎶ラ敊 initWith release debuggable true } @@ -67,7 +67,7 @@ android { } end2end { - // 注意这里的配置,并不是需要编译end2end的app,而是避免httpdns-sdk在AndroidStudio改为end2end运行测试时 BuildVariants报错 + // 娉ㄦ剰杩欓噷鐨勯厤缃紝骞朵笉鏄渶瑕佺紪璇慹nd2end鐨刟pp锛岃€屾槸閬垮厤httpdns-sdk鍦ˋndroidStudio鏀逛负end2end杩愯娴嬭瘯鏃?BuildVariants鎶ラ敊 } } } diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsActivity.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsActivity.java index 649f123..9afe155 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsActivity.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsActivity.java @@ -33,10 +33,10 @@ public class HttpDnsActivity extends BaseActivity { public static final String SCHEMA_HTTP = "http://"; public static final String TAOBAO_URL = "www.taobao.com"; - public static final String ALIYUN_URL = "www.aliyun.com"; + public static final String Aliyun_URL = "www.Aliyun.com"; public static final String[] hosts = new String[]{ - TAOBAO_URL, ALIYUN_URL + TAOBAO_URL, Aliyun_URL }; public static String getUrl(String schema, String host) { @@ -44,15 +44,15 @@ public class HttpDnsActivity extends BaseActivity { } /** - * 要请求的schema + * 瑕佽姹傜殑schema */ private String schema = SCHEMA_HTTPS; /** - * 要请求的域名 + * 瑕佽姹傜殑鍩熷悕 */ - private String host = ALIYUN_URL; + private String host = Aliyun_URL; /** - * 要解析的ip类型 + * 瑕佽В鏋愮殑ip绫诲瀷 */ private RequestIpType requestIpType = RequestIpType.v4; @@ -69,77 +69,77 @@ public class HttpDnsActivity extends BaseActivity { okHttpRequest = new OkHttpRequest(this); networkRequest = httpUrlConnectionRequest; - addFourButton("切换实例", v -> { + addFourButton("鍒囨崲瀹炰緥", v -> { MyApp.getInstance().changeHolder(); - sendLog("httpdns实例已切换"); - }, "获取配置", v -> { + sendLog("httpdns瀹炰緥宸插垏鎹?); + }, "鑾峰彇閰嶇疆", v -> { sendLog(MyApp.getInstance().getCurrentHolder().getCurrentConfig()); - sendLog("要解析的域名是" + host); - sendLog("要解析的ip类型是" + requestIpType.name()); - sendLog("要模拟请求的url是" + getUrl(schema, host)); - sendLog("模拟请求的网络框架是" + (networkRequest == httpUrlConnectionRequest ? " HttpUrlConnection" : "OkHttp")); - }, "清除配置缓存", v -> { + sendLog("瑕佽В鏋愮殑鍩熷悕鏄? + host); + sendLog("瑕佽В鏋愮殑ip绫诲瀷鏄? + requestIpType.name()); + sendLog("瑕佹ā鎷熻姹傜殑url鏄? + getUrl(schema, host)); + sendLog("妯℃嫙璇锋眰鐨勭綉缁滄鏋舵槸" + (networkRequest == httpUrlConnectionRequest ? " HttpUrlConnection" : "OkHttp")); + }, "娓呴櫎閰嶇疆缂撳瓨", v -> { MyApp.getInstance().getCurrentHolder().cleanSp(); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "配置缓存清除, 重启生效"); - }, "清除日志", v -> cleanLog()); + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "閰嶇疆缂撳瓨娓呴櫎, 閲嶅惎鐢熸晥"); + }, "娓呴櫎鏃ュ織", v -> cleanLog()); - addTwoButton("开启https", v -> { + addTwoButton("寮€鍚痟ttps", v -> { MyApp.getInstance().getCurrentHolder().setEnableHttps(true); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "开启https"); - }, "关闭https", v -> { + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "寮€鍚痟ttps"); + }, "鍏抽棴https", v -> { MyApp.getInstance().getCurrentHolder().setEnableHttps(false); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "关闭https"); + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "鍏抽棴https"); }); - addTwoButton("允许过期IP", v -> { + addTwoButton("鍏佽杩囨湡IP", v -> { MyApp.getInstance().getCurrentHolder().setEnableExpiredIp(true); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "允许过期IP"); - }, "不允许过期IP", v -> { + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "鍏佽杩囨湡IP"); + }, "涓嶅厑璁歌繃鏈烮P", v -> { MyApp.getInstance().getCurrentHolder().setEnableExpiredIp(false); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "不允许过期IP"); + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "涓嶅厑璁歌繃鏈烮P"); }); - addTwoButton("允许持久化缓存", v -> { + addTwoButton("鍏佽鎸佷箙鍖栫紦瀛?, v -> { MyApp.getInstance().getCurrentHolder().setEnableCacheIp(true); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "允许持久化缓存"); - }, "不允许持久化缓存", v -> { + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "鍏佽鎸佷箙鍖栫紦瀛?); + }, "涓嶅厑璁告寔涔呭寲缂撳瓨", v -> { MyApp.getInstance().getCurrentHolder().setEnableCacheIp(false); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "不允许持久化缓存"); + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "涓嶅厑璁告寔涔呭寲缂撳瓨"); }); - addThreeButton("设置中国大陆", v -> { + addThreeButton("璁剧疆涓浗澶ч檰", v -> { MyApp.getInstance().getCurrentHolder().setRegion(null); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "切换到中国大陆"); - }, "设置中国香港", v -> { + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "鍒囨崲鍒颁腑鍥藉ぇ闄?); + }, "璁剧疆涓浗棣欐腐", v -> { MyApp.getInstance().getCurrentHolder().setRegion("hk"); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "切换到中国香港"); - }, "设置新加坡", v -> { + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "鍒囨崲鍒颁腑鍥介娓?); + }, "璁剧疆鏂板姞鍧?, v -> { MyApp.getInstance().getCurrentHolder().setRegion("sg"); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "切换到新加坡"); + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "鍒囨崲鍒版柊鍔犲潯"); }); - addEditTextButton("超时时长 ms", "设置超时ms", view -> { + addEditTextButton("瓒呮椂鏃堕暱 ms", "璁剧疆瓒呮椂ms", view -> { EditText et = (EditText) view; int timeout = Integer.parseInt(et.getEditableText().toString()); MyApp.getInstance().getCurrentHolder().setTimeout(timeout); - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "设置超时 " + timeout); + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "璁剧疆瓒呮椂 " + timeout); }); - addTwoButton("开启降级", v -> { - // 注意:降级过滤器现在需要通过InitConfig设置,重启应用生效 - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "降级功能需要通过InitConfig配置"); - }, "关闭降级", v -> { - // 注意:降级过滤器现在需要通过InitConfig设置,重启应用生效 - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "降级功能需要通过InitConfig配置"); + addTwoButton("寮€鍚檷绾?, v -> { + // 娉ㄦ剰锛氶檷绾ц繃婊ゅ櫒鐜板湪闇€瑕侀€氳繃InitConfig璁剧疆锛岄噸鍚簲鐢ㄧ敓鏁? + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "闄嶇骇鍔熻兘闇€瑕侀€氳繃InitConfig閰嶇疆"); + }, "鍏抽棴闄嶇骇", v -> { + // 娉ㄦ剰锛氶檷绾ц繃婊ゅ櫒鐜板湪闇€瑕侀€氳繃InitConfig璁剧疆锛岄噸鍚簲鐢ㄧ敓鏁? + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "闄嶇骇鍔熻兘闇€瑕侀€氳繃InitConfig閰嶇疆"); }); - addTwoButton("开启网络变化后预解析", v -> { - // 注意:此功能现在需要通过InitConfig设置,重启应用生效 - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "网络变化后预解析需要通过InitConfig配置"); - }, "关闭网络变化后预解析", v -> { - // 注意:此功能现在需要通过InitConfig设置,重启应用生效 - sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "网络变化后预解析需要通过InitConfig配置"); + addTwoButton("寮€鍚綉缁滃彉鍖栧悗棰勮В鏋?, v -> { + // 娉ㄦ剰锛氭鍔熻兘鐜板湪闇€瑕侀€氳繃InitConfig璁剧疆锛岄噸鍚簲鐢ㄧ敓鏁? + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "缃戠粶鍙樺寲鍚庨瑙f瀽闇€瑕侀€氳繃InitConfig閰嶇疆"); + }, "鍏抽棴缃戠粶鍙樺寲鍚庨瑙f瀽", v -> { + // 娉ㄦ剰锛氭鍔熻兘鐜板湪闇€瑕侀€氳繃InitConfig璁剧疆锛岄噸鍚簲鐢ㄧ敓鏁? + sendLog(MyApp.getInstance().getCurrentHolder().getAccountId() + "缃戠粶鍙樺寲鍚庨瑙f瀽闇€瑕侀€氳繃InitConfig閰嶇疆"); }); addView(R.layout.item_autocomplete_edittext_button, view -> { @@ -147,21 +147,21 @@ public class HttpDnsActivity extends BaseActivity { final EditText etOne = view.findViewById(R.id.etOne); Button btnOne = view.findViewById(R.id.btnOne); - actvOne.setHint("请输入域名"); + actvOne.setHint("璇疯緭鍏ュ煙鍚?); ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, hosts); actvOne.setAdapter(adapter); - etOne.setHint("请输入自定义ttl"); + etOne.setHint("璇疯緭鍏ヨ嚜瀹氫箟ttl"); - btnOne.setText("指定域名ttl s"); + btnOne.setText("鎸囧畾鍩熷悕ttl s"); btnOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String host = actvOne.getEditableText().toString(); int ttl = Integer.parseInt(etOne.getEditableText().toString()); MyApp.getInstance().getCurrentHolder().setHostTtl(host, ttl); - sendLog("指定域名" + host + "的ttl为" + ttl + "秒"); + sendLog("鎸囧畾鍩熷悕" + host + "鐨則tl涓? + ttl + "绉?); } }); }); @@ -171,124 +171,124 @@ public class HttpDnsActivity extends BaseActivity { final EditText etOne = view.findViewById(R.id.etOne); Button btnOne = view.findViewById(R.id.btnOne); - actvOne.setHint("域名"); + actvOne.setHint("鍩熷悕"); ArrayAdapter adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, hosts); actvOne.setAdapter(adapter); - etOne.setHint("请输入端口"); + etOne.setHint("璇疯緭鍏ョ鍙?); - btnOne.setText("添加ipRanking配置"); + btnOne.setText("娣诲姞ipRanking閰嶇疆"); btnOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String host = actvOne.getEditableText().toString(); int port = Integer.parseInt(etOne.getEditableText().toString()); MyApp.getInstance().getCurrentHolder().addIpProbeItem(new IPRankingBean(host, port)); - sendLog("添加域名" + host + " 探测"); + sendLog("娣诲姞鍩熷悕" + host + " 鎺㈡祴"); } }); }); - addAutoCompleteTextViewButton(hosts, "主站域名", "添加主站域名", view -> { + addAutoCompleteTextViewButton(hosts, "涓荤珯鍩熷悕", "娣诲姞涓荤珯鍩熷悕", view -> { AutoCompleteTextView actvOne = (AutoCompleteTextView) view; String host = actvOne.getEditableText().toString(); MyApp.getInstance().getCurrentHolder().addHostWithFixedIp(host); - sendLog("添加主站域名" + host); + sendLog("娣诲姞涓荤珯鍩熷悕" + host); }); - addAutoCompleteTextViewButton(hosts, "域名", "删除指定域名的缓存", view -> { + addAutoCompleteTextViewButton(hosts, "鍩熷悕", "鍒犻櫎鎸囧畾鍩熷悕鐨勭紦瀛?, view -> { AutoCompleteTextView actvOne = (AutoCompleteTextView) view; String host = actvOne.getEditableText().toString(); ArrayList list = new ArrayList<>(); list.add(host); MyApp.getInstance().getService().cleanHostCache(list); - sendLog("清除指定host的缓存" + host); + sendLog("娓呴櫎鎸囧畾host鐨勭紦瀛? + host); }); - addOneButton("清除所有缓存", v -> { + addOneButton("娓呴櫎鎵€鏈夌紦瀛?, v -> { MyApp.getInstance().getService().cleanHostCache(null); - sendLog("清除所有缓存"); + sendLog("娓呴櫎鎵€鏈夌紦瀛?); }); - addFourButton("获取当前网络状态", v -> { + addFourButton("鑾峰彇褰撳墠缃戠粶鐘舵€?, v -> { NetType type = HttpDnsNetworkDetector.getInstance().getNetType(getApplicationContext()); - sendLog("获取网络状态 " + type.name()); - }, "禁用网络状态缓存", v -> { + sendLog("鑾峰彇缃戠粶鐘舵€?" + type.name()); + }, "绂佺敤缃戠粶鐘舵€佺紦瀛?, v -> { HttpDnsNetworkDetector.getInstance().disableCache(true); - sendLog("网络状态 禁用缓存 "); - }, "开启网络状态缓存", v -> { + sendLog("缃戠粶鐘舵€?绂佺敤缂撳瓨 "); + }, "寮€鍚綉缁滅姸鎬佺紦瀛?, v -> { HttpDnsNetworkDetector.getInstance().disableCache(false); - sendLog("网络状态 开启缓存 "); - }, "清除网络状态缓存", v -> { + sendLog("缃戠粶鐘舵€?寮€鍚紦瀛?"); + }, "娓呴櫎缃戠粶鐘舵€佺紦瀛?, v -> { HttpDnsNetworkDetector.getInstance().cleanCache(false); - sendLog("网络状态清除缓存 "); + sendLog("缃戠粶鐘舵€佹竻闄ょ紦瀛?"); }); - addTwoButton("禁止读取IP", v -> { + addTwoButton("绂佹璇诲彇IP", v -> { HttpDnsNetworkDetector.getInstance().setCheckInterface(false); - sendLog("查询网络状态时 禁止读取IP"); - }, "允许读取IP", v -> { + sendLog("鏌ヨ缃戠粶鐘舵€佹椂 绂佹璇诲彇IP"); + }, "鍏佽璇诲彇IP", v -> { HttpDnsNetworkDetector.getInstance().setCheckInterface(true); - sendLog("查询网络状态时 允许读取IP"); + sendLog("鏌ヨ缃戠粶鐘舵€佹椂 鍏佽璇诲彇IP"); }); - addAutoCompleteTextViewButton(hosts, "域名", "设置检测网络使用的域名", view -> { + addAutoCompleteTextViewButton(hosts, "鍩熷悕", "璁剧疆妫€娴嬬綉缁滀娇鐢ㄧ殑鍩熷悕", view -> { AutoCompleteTextView actvOne = (AutoCompleteTextView) view; String host = actvOne.getEditableText().toString(); HttpDnsNetworkDetector.getInstance().setHostToCheckNetType(host); - sendLog("设置检测网络状态使用的域名为" + host); + sendLog("璁剧疆妫€娴嬬綉缁滅姸鎬佷娇鐢ㄧ殑鍩熷悕涓? + host); }); - addTwoButton("模拟请求使用https请求", v -> { + addTwoButton("妯℃嫙璇锋眰浣跨敤https璇锋眰", v -> { schema = SCHEMA_HTTPS; - sendLog("测试url使用https"); - }, "模拟请求使用http请求", v -> { + sendLog("娴嬭瘯url浣跨敤https"); + }, "妯℃嫙璇锋眰浣跨敤http璇锋眰", v -> { schema = SCHEMA_HTTP; - sendLog("测试url使用http"); + sendLog("娴嬭瘯url浣跨敤http"); }); addTwoButton("HttpUrlConnection", v -> { networkRequest = httpUrlConnectionRequest; - sendLog("指定网络实现方式为HttpUrlConnection"); + sendLog("鎸囧畾缃戠粶瀹炵幇鏂瑰紡涓篐ttpUrlConnection"); }, "Okhttp", v -> { networkRequest = okHttpRequest; - sendLog("指定网络实现方式为okhttp"); + sendLog("鎸囧畾缃戠粶瀹炵幇鏂瑰紡涓簅khttp"); }); - addFourButton("指定v4", v -> { + addFourButton("鎸囧畾v4", v -> { requestIpType = RequestIpType.v4; - sendLog("要解析的IP类型指定为ipv4"); - }, "指定v6", v -> { + sendLog("瑕佽В鏋愮殑IP绫诲瀷鎸囧畾涓篿pv4"); + }, "鎸囧畾v6", v -> { requestIpType = RequestIpType.v6; - sendLog("要解析的IP类型指定为ipv6"); - }, "都解析", v -> { + sendLog("瑕佽В鏋愮殑IP绫诲瀷鎸囧畾涓篿pv6"); + }, "閮借В鏋?, v -> { requestIpType = RequestIpType.both; - sendLog("要解析的IP类型指定为ipv4和ipv6"); - }, "自动判断", v -> { + sendLog("瑕佽В鏋愮殑IP绫诲瀷鎸囧畾涓篿pv4鍜宨pv6"); + }, "鑷姩鍒ゆ柇", v -> { requestIpType = RequestIpType.auto; - sendLog("要解析的IP类型根据网络情况自动判断"); + sendLog("瑕佽В鏋愮殑IP绫诲瀷鏍规嵁缃戠粶鎯呭喌鑷姩鍒ゆ柇"); }); - addAutoCompleteTextViewButton(hosts, "域名", "指定要解析的域名", new OnButtonClick() { + addAutoCompleteTextViewButton(hosts, "鍩熷悕", "鎸囧畾瑕佽В鏋愮殑鍩熷悕", new OnButtonClick() { @Override public void onBtnClick(View view) { AutoCompleteTextView actvOne = (AutoCompleteTextView) view; host = actvOne.getEditableText().toString(); - sendLog("要解析的域名" + host); + sendLog("瑕佽В鏋愮殑鍩熷悕" + host); } }); - addTwoButton("异步解析", v -> worker.execute(new Runnable() { + addTwoButton("寮傛瑙f瀽", v -> worker.execute(new Runnable() { @Override public void run() { - sendLog("开始发起网络请求"); - sendLog("网络实现方式为" + (networkRequest == httpUrlConnectionRequest ? "HttpUrlConnection" : "okhttp")); + sendLog("寮€濮嬪彂璧风綉缁滆姹?); + sendLog("缃戠粶瀹炵幇鏂瑰紡涓? + (networkRequest == httpUrlConnectionRequest ? "HttpUrlConnection" : "okhttp")); String url = getUrl(schema, host); sendLog("url is " + url); - sendLog("httpdns 使用 异步解析api"); - sendLog("指定解析ip类型为" + requestIpType.name()); + sendLog("httpdns 浣跨敤 寮傛瑙f瀽api"); + sendLog("鎸囧畾瑙f瀽ip绫诲瀷涓? + requestIpType.name()); networkRequest.updateHttpDnsConfig(true, requestIpType); try { String response = networkRequest.httpGet(url); @@ -298,40 +298,40 @@ public class HttpDnsActivity extends BaseActivity { response = response.substring(0, 30) + "..."; } } - sendLog("请求结束 response is " + response + " 完整记录请看logcat日志"); + sendLog("璇锋眰缁撴潫 response is " + response + " 瀹屾暣璁板綍璇风湅logcat鏃ュ織"); } catch (Exception e) { e.printStackTrace(); - sendLog("请求结束 发生异常 " + e.getClass().getName() + e.getMessage() + " 完整记录请看logcat日志"); + sendLog("璇锋眰缁撴潫 鍙戠敓寮傚父 " + e.getClass().getName() + e.getMessage() + " 瀹屾暣璁板綍璇风湅logcat鏃ュ織"); } } - }), "同步解析", v -> worker.execute(() -> { - sendLog("开始发起网络请求"); - sendLog("网络实现方式为" + (networkRequest == httpUrlConnectionRequest ? "HttpUrlConnection" : "okhttp")); + }), "鍚屾瑙f瀽", v -> worker.execute(() -> { + sendLog("寮€濮嬪彂璧风綉缁滆姹?); + sendLog("缃戠粶瀹炵幇鏂瑰紡涓? + (networkRequest == httpUrlConnectionRequest ? "HttpUrlConnection" : "okhttp")); String url = getUrl(schema, host); sendLog("url is " + url); - sendLog("httpdns 使用 同步解析api"); - sendLog("指定解析ip类型为" + requestIpType.name()); + sendLog("httpdns 浣跨敤 鍚屾瑙f瀽api"); + sendLog("鎸囧畾瑙f瀽ip绫诲瀷涓? + requestIpType.name()); networkRequest.updateHttpDnsConfig(false, requestIpType); try { String response = networkRequest.httpGet(url); if (response != null && response.length() > 30) { response = response.substring(0, 30) + "..."; } - sendLog("请求结束 response is " + response + " 完整记录请看logcat日志"); + sendLog("璇锋眰缁撴潫 response is " + response + " 瀹屾暣璁板綍璇风湅logcat鏃ュ織"); } catch (Exception e) { e.printStackTrace(); - sendLog("请求结束 发生异常 " + e.getClass().getName() + e.getMessage() + " 完整记录请看logcat日志"); + sendLog("璇锋眰缁撴潫 鍙戠敓寮傚父 " + e.getClass().getName() + e.getMessage() + " 瀹屾暣璁板綍璇风湅logcat鏃ュ織"); } })); - addThreeButton("发起预解析", v -> worker.execute(() -> { + addThreeButton("鍙戣捣棰勮В鏋?, v -> worker.execute(() -> { ArrayList tmp = new ArrayList<>(); Collections.addAll(tmp, hosts); MyApp.getInstance().getService().setPreResolveHosts(tmp, requestIpType); - sendLog("已发起预解析请求"); - }), "跳转SDNS测试界面", - v -> startActivity(new Intent(HttpDnsActivity.this, SDNSActivity.class)), "跳转Webview测试界面", new View.OnClickListener() { + sendLog("宸插彂璧烽瑙f瀽璇锋眰"); + }), "璺宠浆SDNS娴嬭瘯鐣岄潰", + v -> startActivity(new Intent(HttpDnsActivity.this, SDNSActivity.class)), "璺宠浆Webview娴嬭瘯鐣岄潰", new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HttpDnsActivity.this, WebViewActivity.class)); @@ -340,17 +340,18 @@ public class HttpDnsActivity extends BaseActivity { final String[] validHosts = new String[]{ - "www.aliyun.com", + "www.Aliyun.com", "www.taobao.com" }; - addTwoButton("并发异步请求", v -> { + addTwoButton("骞跺彂寮傛璇锋眰", v -> { ThreadUtil.multiThreadTest(validHosts, 100, 20, 10 * 60 * 1000, true, requestIpType); - sendLog("异步api并发测试开始,大约耗时10分钟,请最后查看logcat日志,确认结果,建议关闭httpdns日志,避免日志量过大"); - }, "并发同步请求", v -> { + sendLog("寮傛api骞跺彂娴嬭瘯寮€濮嬶紝澶х害鑰楁椂10鍒嗛挓锛岃鏈€鍚庢煡鐪媗ogcat鏃ュ織锛岀‘璁ょ粨鏋滐紝寤鸿鍏抽棴httpdns鏃ュ織锛岄伩鍏嶆棩蹇楅噺杩囧ぇ"); + }, "骞跺彂鍚屾璇锋眰", v -> { ThreadUtil.multiThreadTest(validHosts, 100, 20, 10 * 60 * 1000, false, requestIpType); - sendLog("同步api并发测试开始,大约耗时10分钟,请最后查看logcat日志,确认结果,建议关闭httpdns日志,避免日志量过大"); + sendLog("鍚屾api骞跺彂娴嬭瘯寮€濮嬶紝澶х害鑰楁椂10鍒嗛挓锛岃鏈€鍚庢煡鐪媗ogcat鏃ュ織锛岀‘璁ょ粨鏋滐紝寤鸿鍏抽棴httpdns鏃ュ織锛岄伩鍏嶆棩蹇楅噺杩囧ぇ"); }); } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsHolder.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsHolder.java index 2026ff5..89d50fc 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsHolder.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/HttpDnsHolder.java @@ -21,8 +21,8 @@ import java.util.Iterator; import java.util.List; /** - * 保存Httpdns 及 相关配置, - * 方便修改 + * 淇濆瓨Httpdns 鍙?鐩稿叧閰嶇疆锛? + * 鏂逛究淇敼 */ public class HttpDnsHolder { @@ -74,7 +74,7 @@ public class HttpDnsHolder { } /** - * 初始化httpdns的配置 + * 鍒濆鍖杊ttpdns鐨勯厤缃? * * @param context */ @@ -94,7 +94,7 @@ public class HttpDnsHolder { } }); - // 初始化httpdns 的配置,此步骤需要在第一次获取HttpDnsService实例之前 + // 鍒濆鍖杊ttpdns 鐨勯厤缃紝姝ゆ楠ら渶瑕佸湪绗竴娆¤幏鍙朒ttpDnsService瀹炰緥涔嬪墠 new InitConfig.Builder() .setEnableExpiredIp(enableExpiredIp) .setEnableCacheIp(enableCacheIp) @@ -126,7 +126,7 @@ public class HttpDnsHolder { public void setEnableExpiredIp(final boolean enableExpiredIp) { this.enableExpiredIp = enableExpiredIp; - // 注意:此配置需要重启应用生效,因为现在通过InitConfig设置 + // 娉ㄦ剰锛氭閰嶇疆闇€瑕侀噸鍚簲鐢ㄧ敓鏁堬紝鍥犱负鐜板湪閫氳繃InitConfig璁剧疆 SpUtil.writeSp(context, getSpName(accountId), new SpUtil.OnGetSpEditor() { @Override public void onGetSpEditor(SharedPreferences.Editor editor) { @@ -137,7 +137,7 @@ public class HttpDnsHolder { public void setEnableCacheIp(final boolean enableCacheIp) { this.enableCacheIp = enableCacheIp; - // 注意:此配置需要重启应用生效,因为现在通过InitConfig设置 + // 娉ㄦ剰锛氭閰嶇疆闇€瑕侀噸鍚簲鐢ㄧ敓鏁堬紝鍥犱负鐜板湪閫氳繃InitConfig璁剧疆 SpUtil.writeSp(context, getSpName(accountId), new SpUtil.OnGetSpEditor() { @Override public void onGetSpEditor(SharedPreferences.Editor editor) { @@ -148,7 +148,7 @@ public class HttpDnsHolder { public void setTimeout(final int timeout) { this.timeout = timeout; - // 注意:此配置需要重启应用生效,因为现在通过InitConfig设置 + // 娉ㄦ剰锛氭閰嶇疆闇€瑕侀噸鍚簲鐢ㄧ敓鏁堬紝鍥犱负鐜板湪閫氳繃InitConfig璁剧疆 SpUtil.writeSp(context, getSpName(accountId), new SpUtil.OnGetSpEditor() { @Override public void onGetSpEditor(SharedPreferences.Editor editor) { @@ -159,7 +159,7 @@ public class HttpDnsHolder { public void setEnableHttps(final boolean enableHttps) { this.enableHttps = enableHttps; - // 注意:此配置需要重启应用生效,因为现在通过InitConfig设置 + // 娉ㄦ剰锛氭閰嶇疆闇€瑕侀噸鍚簲鐢ㄧ敓鏁堬紝鍥犱负鐜板湪閫氳繃InitConfig璁剧疆 SpUtil.writeSp(context, getSpName(accountId), new SpUtil.OnGetSpEditor() { @Override public void onGetSpEditor(SharedPreferences.Editor editor) { @@ -184,7 +184,7 @@ public class HttpDnsHolder { this.hostListWithFixedIp = new ArrayList<>(); } this.hostListWithFixedIp.add(host); - // 重启生效 + // 閲嶅惎鐢熸晥 SpUtil.writeSp(context, getSpName(accountId), new SpUtil.OnGetSpEditor() { @Override public void onGetSpEditor(SharedPreferences.Editor editor) { @@ -198,7 +198,7 @@ public class HttpDnsHolder { this.ipRankingList = new ArrayList<>(); } this.ipRankingList.add(ipProbeItem); - // 注意:此配置需要重启应用生效,因为现在通过InitConfig设置 + // 娉ㄦ剰锛氭閰嶇疆闇€瑕侀噸鍚簲鐢ㄧ敓鏁堬紝鍥犱负鐜板湪閫氳繃InitConfig璁剧疆 SpUtil.writeSp(context, getSpName(accountId), new SpUtil.OnGetSpEditor() { @Override public void onGetSpEditor(SharedPreferences.Editor editor) { @@ -232,15 +232,15 @@ public class HttpDnsHolder { public String getCurrentConfig() { StringBuilder sb = new StringBuilder(); - sb.append("当前配置 accountId : ").append(accountId).append("\n") - .append("是否允许过期IP : ").append(enableExpiredIp).append("\n") - .append("是否开启本地缓存 : ").append(enableCacheIp).append("\n") - .append("是否开启HTTPS : ").append(enableHttps).append("\n") - .append("当前region设置 : ").append(region).append("\n") - .append("当前超时设置 : ").append(timeout).append("\n") - .append("当前探测配置 : ").append(convertProbeList(ipRankingList)).append("\n") - .append("当前缓存配置 : ").append(convertTtlCache(ttlCache)).append("\n") - .append("当前主站域名配置 : ").append(convertHostList(hostListWithFixedIp)).append("\n") + sb.append("褰撳墠閰嶇疆 accountId : ").append(accountId).append("\n") + .append("鏄惁鍏佽杩囨湡IP : ").append(enableExpiredIp).append("\n") + .append("鏄惁寮€鍚湰鍦扮紦瀛?: ").append(enableCacheIp).append("\n") + .append("鏄惁寮€鍚疕TTPS : ").append(enableHttps).append("\n") + .append("褰撳墠region璁剧疆 : ").append(region).append("\n") + .append("褰撳墠瓒呮椂璁剧疆 : ").append(timeout).append("\n") + .append("褰撳墠鎺㈡祴閰嶇疆 : ").append(convertProbeList(ipRankingList)).append("\n") + .append("褰撳墠缂撳瓨閰嶇疆 : ").append(convertTtlCache(ttlCache)).append("\n") + .append("褰撳墠涓荤珯鍩熷悕閰嶇疆 : ").append(convertHostList(hostListWithFixedIp)).append("\n") ; return sb.toString(); } @@ -340,3 +340,4 @@ public class HttpDnsHolder { return null; } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/MyApp.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/MyApp.java index 3ab1ea2..7936ae9 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/MyApp.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/MyApp.java @@ -23,8 +23,8 @@ public class MyApp extends Application { return instance; } - private final HttpDnsHolder holderA = new HttpDnsHolder("请替换为测试用A实例的accountId", "请替换为测试用A实例的secret"); - private final HttpDnsHolder holderB = new HttpDnsHolder("请替换为测试用B实例的accountId", null); + private final HttpDnsHolder holderA = new HttpDnsHolder("璇锋浛鎹负娴嬭瘯鐢ˋ瀹炰緥鐨刟ccountId", "璇锋浛鎹负娴嬭瘯鐢ˋ瀹炰緥鐨剆ecret"); + private final HttpDnsHolder holderB = new HttpDnsHolder("璇锋浛鎹负娴嬭瘯鐢˙瀹炰緥鐨刟ccountId", null); private HttpDnsHolder current = holderA; @@ -33,9 +33,9 @@ public class MyApp extends Application { super.onCreate(); instance = this; - // 开启logcat 日志 默认关闭, 开发测试过程中可以开启 + // 寮€鍚痩ogcat 鏃ュ織 榛樿鍏抽棴, 寮€鍙戞祴璇曡繃绋嬩腑鍙互寮€鍚? HttpDnsLog.enable(true); - // 注入日志接口,接受httpdns的日志,开发测试过程中可以开启, 基础日志需要先enable才生效,一些错误日志不需要 + // 娉ㄥ叆鏃ュ織鎺ュ彛锛屾帴鍙梙ttpdns鐨勬棩蹇楋紝寮€鍙戞祴璇曡繃绋嬩腑鍙互寮€鍚? 鍩虹鏃ュ織闇€瑕佸厛enable鎵嶇敓鏁堬紝涓€浜涢敊璇棩蹇椾笉闇€瑕? HttpDnsLog.setLogger(new ILogger() { @Override public void log(String msg) { @@ -43,7 +43,7 @@ public class MyApp extends Application { } }); - // 初始化httpdns的配置 + // 鍒濆鍖杊ttpdns鐨勯厤缃? holderA.init(this); holderB.init(this); @@ -90,3 +90,4 @@ public class MyApp extends Application { } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/NetworkRequest.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/NetworkRequest.java index cbade10..fc54dde 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/NetworkRequest.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/NetworkRequest.java @@ -5,12 +5,12 @@ import com.alibaba.sdk.android.httpdns.RequestIpType; public interface NetworkRequest { /** - * 设置httpdns的配置 + * 璁剧疆httpdns鐨勯厤缃? */ void updateHttpDnsConfig(boolean async, RequestIpType requestIpType); /** - * get请求 + * get璇锋眰 * * @param url * @return @@ -18,3 +18,4 @@ public interface NetworkRequest { String httpGet(String url) throws Exception; } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/SDNSActivity.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/SDNSActivity.java index 7c44fb6..296f7ba 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/SDNSActivity.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/SDNSActivity.java @@ -11,17 +11,17 @@ import com.aliyun.ams.httpdns.demo.base.BaseActivity; import java.util.HashMap; -import static com.aliyun.ams.httpdns.demo.HttpDnsActivity.ALIYUN_URL; +import static com.aliyun.ams.httpdns.demo.HttpDnsActivity.Aliyun_URL; public class SDNSActivity extends BaseActivity { private final HashMap globalParams = new HashMap<>(); /** - * 要请求的域名 + * 瑕佽姹傜殑鍩熷悕 */ - private String host = HttpDnsActivity.ALIYUN_URL; + private String host = HttpDnsActivity.Aliyun_URL; /** - * 要解析的ip类型 + * 瑕佽В鏋愮殑ip绫诲瀷 */ private RequestIpType requestIpType = RequestIpType.v4; @@ -29,7 +29,7 @@ public class SDNSActivity extends BaseActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - addEditTextEditTextButton("key", "value", "添加全局配置", new OnButtonClickMoreView() { + addEditTextEditTextButton("key", "value", "娣诲姞鍏ㄥ眬閰嶇疆", new OnButtonClickMoreView() { @Override public void onBtnClick(View[] views) { EditText etOne = (EditText) views[0]; @@ -40,56 +40,56 @@ public class SDNSActivity extends BaseActivity { globalParams.put(key, value); - // 注意:SDNS全局参数现在需要通过InitConfig设置,重启应用生效 - sendLog("添加全局参数 " + key + " : " + value); + // 娉ㄦ剰锛歋DNS鍏ㄥ眬鍙傛暟鐜板湪闇€瑕侀€氳繃InitConfig璁剧疆锛岄噸鍚簲鐢ㄧ敓鏁? + sendLog("娣诲姞鍏ㄥ眬鍙傛暟 " + key + " : " + value); } }); - addOneButton("清除全局配置", new View.OnClickListener() { + addOneButton("娓呴櫎鍏ㄥ眬閰嶇疆", new View.OnClickListener() { @Override public void onClick(View v) { globalParams.clear(); - // 注意:SDNS全局参数现在需要通过InitConfig设置,重启应用生效 - sendLog("清除全局参数"); + // 娉ㄦ剰锛歋DNS鍏ㄥ眬鍙傛暟鐜板湪闇€瑕侀€氳繃InitConfig璁剧疆锛岄噸鍚簲鐢ㄧ敓鏁? + sendLog("娓呴櫎鍏ㄥ眬鍙傛暟"); } }); - addFourButton("指定v4", new View.OnClickListener() { + addFourButton("鎸囧畾v4", new View.OnClickListener() { @Override public void onClick(View v) { requestIpType = RequestIpType.v4; - sendLog("要解析的IP类型指定为ipv4"); + sendLog("瑕佽В鏋愮殑IP绫诲瀷鎸囧畾涓篿pv4"); } - }, "指定v6", new View.OnClickListener() { + }, "鎸囧畾v6", new View.OnClickListener() { @Override public void onClick(View v) { requestIpType = RequestIpType.v6; - sendLog("要解析的IP类型指定为ipv6"); + sendLog("瑕佽В鏋愮殑IP绫诲瀷鎸囧畾涓篿pv6"); } - }, "都解析", new View.OnClickListener() { + }, "閮借В鏋?, new View.OnClickListener() { @Override public void onClick(View v) { requestIpType = RequestIpType.both; - sendLog("要解析的IP类型指定为ipv4和ipv6"); + sendLog("瑕佽В鏋愮殑IP绫诲瀷鎸囧畾涓篿pv4鍜宨pv6"); } - }, "自动判断", new View.OnClickListener() { + }, "鑷姩鍒ゆ柇", new View.OnClickListener() { @Override public void onClick(View v) { requestIpType = RequestIpType.auto; - sendLog("要解析的IP类型根据网络情况自动判断"); + sendLog("瑕佽В鏋愮殑IP绫诲瀷鏍规嵁缃戠粶鎯呭喌鑷姩鍒ゆ柇"); } }); - addAutoCompleteTextViewButton(HttpDnsActivity.hosts, "域名", "指定要解析的域名", new OnButtonClick() { + addAutoCompleteTextViewButton(HttpDnsActivity.hosts, "鍩熷悕", "鎸囧畾瑕佽В鏋愮殑鍩熷悕", new OnButtonClick() { @Override public void onBtnClick(View view) { AutoCompleteTextView actvOne = (AutoCompleteTextView) view; host = actvOne.getEditableText().toString(); - sendLog("要解析的域名" + host); + sendLog("瑕佽В鏋愮殑鍩熷悕" + host); } }); - addEditTextEditTextButton("key", "value", "发起请求", new OnButtonClickMoreView() { + addEditTextEditTextButton("key", "value", "鍙戣捣璇锋眰", new OnButtonClickMoreView() { @Override public void onBtnClick(View[] views) { EditText etOne = (EditText) views[0]; @@ -102,31 +102,32 @@ public class SDNSActivity extends BaseActivity { map.put(key, value); - sendLog("发起SDNS请求 requestIpType is " + requestIpType.name()); - HTTPDNSResult result = MyApp.getInstance().getService().getIpsByHostAsync(host, requestIpType, map, "测试SDNS"); - sendLog("结果 " + result); + sendLog("鍙戣捣SDNS璇锋眰 requestIpType is " + requestIpType.name()); + HTTPDNSResult result = MyApp.getInstance().getService().getIpsByHostAsync(host, requestIpType, map, "娴嬭瘯SDNS"); + sendLog("缁撴灉 " + result); } }); - addTwoButton("scale1参数请求", new View.OnClickListener() { + addTwoButton("scale1鍙傛暟璇锋眰", new View.OnClickListener() { @Override public void onClick(View v) { HashMap map = new HashMap<>(); map.put("scale", "scale1"); - sendLog("发起SDNS请求 requestIpType is " + requestIpType.name() + " scale : scale1"); - HTTPDNSResult result = MyApp.getInstance().getService().getIpsByHostAsync(host, requestIpType, map, "测试1"); - sendLog("结果 " + result); + sendLog("鍙戣捣SDNS璇锋眰 requestIpType is " + requestIpType.name() + " scale : scale1"); + HTTPDNSResult result = MyApp.getInstance().getService().getIpsByHostAsync(host, requestIpType, map, "娴嬭瘯1"); + sendLog("缁撴灉 " + result); } - }, "scale2参数请求", new View.OnClickListener() { + }, "scale2鍙傛暟璇锋眰", new View.OnClickListener() { @Override public void onClick(View v) { HashMap map = new HashMap<>(); map.put("scale", "scale2"); - sendLog("发起SDNS请求 requestIpType is " + requestIpType.name() + " scale : scale2"); - HTTPDNSResult result = MyApp.getInstance().getService().getIpsByHostAsync(host, requestIpType, map, "测试2"); - sendLog("结果 " + result); + sendLog("鍙戣捣SDNS璇锋眰 requestIpType is " + requestIpType.name() + " scale : scale2"); + HTTPDNSResult result = MyApp.getInstance().getService().getIpsByHostAsync(host, requestIpType, map, "娴嬭瘯2"); + sendLog("缁撴灉 " + result); } }); } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/WebViewActivity.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/WebViewActivity.java index 3ed8572..2341bf4 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/WebViewActivity.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/WebViewActivity.java @@ -55,10 +55,10 @@ public class WebViewActivity extends Activity { public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) { - webView.goBack();//返回上个页面 + webView.goBack();//杩斿洖涓婁釜椤甸潰 return true; } - return super.onKeyDown(keyCode, event);//退出Activity + return super.onKeyDown(keyCode, event);//閫€鍑篈ctivity } private void initBar() { @@ -86,7 +86,7 @@ public class WebViewActivity extends Activity { Map headerFields = request.getRequestHeaders(); String url = request.getUrl().toString(); Log.e(TAG, "url:" + url); - // 无法拦截body,拦截方案只能正常处理不带body的请求; + // 鏃犳硶鎷︽埅body锛屾嫤鎴柟妗堝彧鑳芥甯稿鐞嗕笉甯ody鐨勮姹傦紱 if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) && method.equalsIgnoreCase("get")) { try { @@ -97,7 +97,7 @@ public class WebViewActivity extends Activity { return super.shouldInterceptRequest(view, request); } - // 注*:对于POST请求的Body数据,WebResourceRequest接口中并没有提供,这里无法处理 + // 娉?锛氬浜嶱OST璇锋眰鐨凚ody鏁版嵁锛學ebResourceRequest鎺ュ彛涓苟娌℃湁鎻愪緵锛岃繖閲屾棤娉曞鐞? String contentType = connection.getContentType(); String mime = getMime(contentType); String charset = getCharset(contentType); @@ -110,18 +110,18 @@ public class WebViewActivity extends Activity { Log.e(TAG, "mime:" + mime + "; charset:" + charset); - // 无mime类型的请求不拦截 + // 鏃爉ime绫诲瀷鐨勮姹備笉鎷︽埅 if (TextUtils.isEmpty(mime)) { Log.e(TAG, "no MIME"); return super.shouldInterceptRequest(view, request); } else { - // 二进制资源无需编码信息 + // 浜岃繘鍒惰祫婧愭棤闇€缂栫爜淇℃伅 if (!TextUtils.isEmpty(charset) || (isBinaryRes(mime))) { WebResourceResponse resourceResponse = new WebResourceResponse(mime, charset, httpURLConnection.getInputStream()); resourceResponse.setStatusCodeAndReasonPhrase(statusCode, response); Map responseHeader = new HashMap(); for (String key : headerKeySet) { - // HttpUrlConnection可能包含key为null的报头,指向该http请求状态码 + // HttpUrlConnection鍙兘鍖呭惈key涓簄ull鐨勬姤澶达紝鎸囧悜璇ttp璇锋眰鐘舵€佺爜 responseHeader.put(key, httpURLConnection.getHeaderField(key)); } resourceResponse.setResponseHeaders(responseHeader); @@ -142,7 +142,7 @@ public class WebViewActivity extends Activity { @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { - // API < 21 只能拦截URL参数 + // API < 21 鍙兘鎷︽埅URL鍙傛暟 return super.shouldInterceptRequest(view, url); } }); @@ -153,7 +153,7 @@ public class WebViewActivity extends Activity { /** - * 从contentType中获取MIME类型 + * 浠巆ontentType涓幏鍙朚IME绫诲瀷 * * @param contentType * @return @@ -166,7 +166,7 @@ public class WebViewActivity extends Activity { } /** - * 从contentType中获取编码信息 + * 浠巆ontentType涓幏鍙栫紪鐮佷俊鎭? * * @param contentType * @return @@ -191,7 +191,7 @@ public class WebViewActivity extends Activity { /** - * 是否是二进制资源,二进制资源可以不需要编码信息 + * 鏄惁鏄簩杩涘埗璧勬簮锛屼簩杩涘埗璧勬簮鍙互涓嶉渶瑕佺紪鐮佷俊鎭? */ private boolean isBinaryRes(String mime) { if (mime.startsWith("image") @@ -209,10 +209,10 @@ public class WebViewActivity extends Activity { URL url = null; try { url = new URL(path); - // 异步接口获取IP + // 寮傛鎺ュ彛鑾峰彇IP String ip = MyApp.getInstance().getService().getIpByHostAsync(url.getHost()); if (ip != null) { - // 通过HTTPDNS获取IP成功,进行URL替换和HOST头设置 + // 閫氳繃HTTPDNS鑾峰彇IP鎴愬姛锛岃繘琛孶RL鏇挎崲鍜孒OST澶磋缃? Log.d(TAG, "Get IP: " + ip + " for host: " + url.getHost() + " from HTTPDNS successfully!"); String newUrl = path.replaceFirst(url.getHost(), ip); conn = (HttpURLConnection) new URL(newUrl).openConnection(); @@ -222,7 +222,7 @@ public class WebViewActivity extends Activity { conn.setRequestProperty(field.getKey(), field.getValue()); } } - // 设置HTTP请求头Host域 + // 璁剧疆HTTP璇锋眰澶碒ost鍩? conn.setRequestProperty("Host", url.getHost()); } else { return null; @@ -235,9 +235,9 @@ public class WebViewActivity extends Activity { WebviewTlsSniSocketFactory sslSocketFactory = new WebviewTlsSniSocketFactory( (HttpsURLConnection)conn); - // sni场景,创建SSLScocket + // sni鍦烘櫙锛屽垱寤篠SLScocket httpsURLConnection.setSSLSocketFactory(sslSocketFactory); - // https场景,证书校验 + // https鍦烘櫙锛岃瘉涔︽牎楠? httpsURLConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { @@ -251,7 +251,7 @@ public class WebViewActivity extends Activity { } int code = conn.getResponseCode();// Network block if (needRedirect(code)) { - // 原有报头中含有cookie,放弃拦截 + // 鍘熸湁鎶ュご涓惈鏈塩ookie锛屾斁寮冩嫤鎴? if (containCookie(headers)) { return null; } @@ -264,7 +264,7 @@ public class WebViewActivity extends Activity { if (location != null) { if (!(location.startsWith("http://") || location .startsWith("https://"))) { - //某些时候会省略host,只返回后面的path,所以需要补全url + //鏌愪簺鏃跺€欎細鐪佺暐host锛屽彧杩斿洖鍚庨潰鐨刾ath锛屾墍浠ラ渶瑕佽ˉ鍏╱rl URL originalUrl = new URL(path); location = originalUrl.getProtocol() + "://" + originalUrl.getHost() + location; @@ -272,7 +272,7 @@ public class WebViewActivity extends Activity { Log.e(TAG, "code: " + code + "; location: " + location + "; path " + path); return recursiveRequest(location, headers, path); } else { - // 无法获取location信息,让浏览器获取 + // 鏃犳硶鑾峰彇location淇℃伅锛岃娴忚鍣ㄨ幏鍙? return null; } } else { @@ -297,7 +297,7 @@ public class WebViewActivity extends Activity { /** - * header中是否含有cookie + * header涓槸鍚﹀惈鏈塩ookie */ private boolean containCookie(Map headers) { for (Map.Entry headerField : headers.entrySet()) { @@ -400,3 +400,4 @@ public class WebViewActivity extends Activity { } } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/base/BaseActivity.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/base/BaseActivity.java index a821464..330455f 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/base/BaseActivity.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/base/BaseActivity.java @@ -66,7 +66,7 @@ public class BaseActivity extends Activity { } /** - * 发送日志到界面 + * 鍙戦€佹棩蹇楀埌鐣岄潰 * * @param log */ @@ -261,3 +261,4 @@ public class BaseActivity extends Activity { void onBtnClick(View[] views); } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/http/HttpUrlConnectionRequest.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/http/HttpUrlConnectionRequest.java index 24563ff..4b71ba7 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/http/HttpUrlConnectionRequest.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/http/HttpUrlConnectionRequest.java @@ -33,7 +33,7 @@ import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; /** - * 使用HttpUrlConnection 实现请求 + * 浣跨敤HttpUrlConnection 瀹炵幇璇锋眰 */ public class HttpUrlConnectionRequest implements NetworkRequest { @@ -55,7 +55,7 @@ public class HttpUrlConnectionRequest implements NetworkRequest { @Override public String httpGet(String url) throws Exception { - Log.d(TAG, "使用httpUrlConnection 请求" + url + " 异步接口 " + async + " ip类型 " + type.name()); + Log.d(TAG, "浣跨敤httpUrlConnection 璇锋眰" + url + " 寮傛鎺ュ彛 " + async + " ip绫诲瀷 " + type.name()); HttpURLConnection conn = getConnection(url); InputStream in = null; @@ -67,13 +67,13 @@ public class HttpUrlConnectionRequest implements NetworkRequest { streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); errStr = readStringFrom(streamReader).toString(); } - Log.d(TAG, "请求失败 " + conn.getResponseCode() + " err " + errStr); + Log.d(TAG, "璇锋眰澶辫触 " + conn.getResponseCode() + " err " + errStr); throw new Exception("Status Code : " + conn.getResponseCode() + " Msg : " + errStr); } else { in = conn.getInputStream(); streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String responseStr = readStringFrom(streamReader).toString(); - Log.d(TAG, "请求成功 " + responseStr); + Log.d(TAG, "璇锋眰鎴愬姛 " + responseStr); return responseStr; } } @@ -82,29 +82,29 @@ public class HttpUrlConnectionRequest implements NetworkRequest { final String host = new URL(url).getHost(); HttpURLConnection conn = null; HTTPDNSResult result; - /* 切换为新版标准api */ + /* 鍒囨崲涓烘柊鐗堟爣鍑哸pi */ if (async) { result = MyApp.getInstance().getService().getHttpDnsResultForHostAsync(host, type); } else { result = MyApp.getInstance().getService().getHttpDnsResultForHostSync(host, type); } - Log.d(TAG, "httpdns 解析 " + host + " 结果为 " + result + " ttl is " + Util.getTtl(result)); + Log.d(TAG, "httpdns 瑙f瀽 " + host + " 缁撴灉涓?" + result + " ttl is " + Util.getTtl(result)); - // 这里需要根据实际情况选择使用ipv6地址 还是 ipv4地址, 下面示例的代码优先使用了ipv6地址 + // 杩欓噷闇€瑕佹牴鎹疄闄呮儏鍐甸€夋嫨浣跨敤ipv6鍦板潃 杩樻槸 ipv4鍦板潃锛?涓嬮潰绀轰緥鐨勪唬鐮佷紭鍏堜娇鐢ㄤ簡ipv6鍦板潃 if (result.getIpv6s() != null && result.getIpv6s().length > 0 && HttpDnsNetworkDetector.getInstance().getNetType(context) != NetType.v4) { String newUrl = url.replace(host, "[" + result.getIpv6s()[0] + "]"); conn = (HttpURLConnection) new URL(newUrl).openConnection(); conn.setRequestProperty("Host", host); - Log.d(TAG, "使用ipv6地址 " + newUrl); + Log.d(TAG, "浣跨敤ipv6鍦板潃 " + newUrl); } else if (result.getIps() != null && result.getIps().length > 0 && HttpDnsNetworkDetector.getInstance().getNetType(context) != NetType.v6) { String newUrl = url.replace(host, result.getIps()[0]); conn = (HttpURLConnection) new URL(newUrl).openConnection(); conn.setRequestProperty("Host", host); - Log.d(TAG, "使用ipv4地址 " + newUrl); + Log.d(TAG, "浣跨敤ipv4鍦板潃 " + newUrl); } if (conn == null) { - Log.d(TAG, "httpdns 未返回解析结果,走localdns"); + Log.d(TAG, "httpdns 鏈繑鍥炶В鏋愮粨鏋滐紝璧發ocaldns"); conn = (HttpURLConnection) new URL(url).openConnection(); } conn.setConnectTimeout(30000); @@ -115,9 +115,9 @@ public class HttpUrlConnectionRequest implements NetworkRequest { WebviewTlsSniSocketFactory sslSocketFactory = new WebviewTlsSniSocketFactory( (HttpsURLConnection)conn); - // sni场景,创建SSLSocket + // sni鍦烘櫙锛屽垱寤篠SLSocket httpsURLConnection.setSSLSocketFactory(sslSocketFactory); - // https场景,证书校验 + // https鍦烘櫙锛岃瘉涔︽牎楠? httpsURLConnection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { @@ -131,14 +131,14 @@ public class HttpUrlConnectionRequest implements NetworkRequest { } int code = conn.getResponseCode();// Network block if (needRedirect(code)) { - //临时重定向和永久重定向location的大小写有区分 + //涓存椂閲嶅畾鍚戝拰姘镐箙閲嶅畾鍚憀ocation鐨勫ぇ灏忓啓鏈夊尯鍒? String location = conn.getHeaderField("Location"); if (location == null) { location = conn.getHeaderField("location"); } if (!(location.startsWith("http://") || location .startsWith("https://"))) { - //某些时候会省略host,只返回后面的path,所以需要补全url + //鏌愪簺鏃跺€欎細鐪佺暐host锛屽彧杩斿洖鍚庨潰鐨刾ath锛屾墍浠ラ渶瑕佽ˉ鍏╱rl URL originalUrl = new URL(url); location = originalUrl.getProtocol() + "://" + originalUrl.getHost() + location; @@ -255,3 +255,4 @@ public class HttpUrlConnectionRequest implements NetworkRequest { return sb; } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/okhttp/OkHttpRequest.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/okhttp/OkHttpRequest.java index 820e4b7..75b9b95 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/okhttp/OkHttpRequest.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/okhttp/OkHttpRequest.java @@ -27,7 +27,7 @@ import okhttp3.Request; import okhttp3.Response; /** - * okhttp实现网络请求 + * okhttp瀹炵幇缃戠粶璇锋眰 */ public class OkHttpRequest implements NetworkRequest { @@ -39,35 +39,35 @@ public class OkHttpRequest implements NetworkRequest { public OkHttpRequest(final Context context) { client = new OkHttpClient.Builder() - // 这里配置连接池,是为了方便测试httpdns能力,正式代码请不要配置 + // 杩欓噷閰嶇疆杩炴帴姹狅紝鏄负浜嗘柟渚挎祴璇昲ttpdns鑳藉姏锛屾寮忎唬鐮佽涓嶈閰嶇疆 .connectionPool(new ConnectionPool(0, 10 * 1000, TimeUnit.MICROSECONDS)) .dns(new Dns() { @Override public List lookup(String hostname) throws UnknownHostException { HTTPDNSResult result; - /* 切换为新版标准api */ + /* 鍒囨崲涓烘柊鐗堟爣鍑哸pi */ if (async) { result = MyApp.getInstance().getService().getHttpDnsResultForHostAsync(hostname, type); } else { result = MyApp.getInstance().getService().getHttpDnsResultForHostSync(hostname, type); } - Log.d(TAG, "httpdns 解析 " + hostname + " 结果为 " + result + " ttl is " + Util.getTtl(result)); + Log.d(TAG, "httpdns 瑙f瀽 " + hostname + " 缁撴灉涓?" + result + " ttl is " + Util.getTtl(result)); List inetAddresses = new ArrayList<>(); - // 这里需要根据实际情况选择使用ipv6地址 还是 ipv4地址, 下面示例的代码优先使用了ipv6地址 + // 杩欓噷闇€瑕佹牴鎹疄闄呮儏鍐甸€夋嫨浣跨敤ipv6鍦板潃 杩樻槸 ipv4鍦板潃锛?涓嬮潰绀轰緥鐨勪唬鐮佷紭鍏堜娇鐢ㄤ簡ipv6鍦板潃 Log.d(TAG, "netType is: " + HttpDnsNetworkDetector.getInstance().getNetType(context)); if (result.getIpv6s() != null && result.getIpv6s().length > 0 && HttpDnsNetworkDetector.getInstance().getNetType(context) != NetType.v4) { for (int i = 0; i < result.getIpv6s().length; i++) { inetAddresses.addAll(Arrays.asList(InetAddress.getAllByName(result.getIpv6s()[i]))); } - Log.d(TAG, "使用ipv6地址" + inetAddresses); + Log.d(TAG, "浣跨敤ipv6鍦板潃" + inetAddresses); } else if (result.getIps() != null && result.getIps().length > 0 && HttpDnsNetworkDetector.getInstance().getNetType(context) != NetType.v6) { for (int i = 0; i < result.getIps().length; i++) { inetAddresses.addAll(Arrays.asList(InetAddress.getAllByName(result.getIps()[i]))); } - Log.d(TAG, "使用ipv4地址" + inetAddresses); + Log.d(TAG, "浣跨敤ipv4鍦板潃" + inetAddresses); } if (inetAddresses.size() == 0) { - Log.d(TAG, "httpdns 未返回IP,走localdns"); + Log.d(TAG, "httpdns 鏈繑鍥濱P锛岃蛋localdns"); return Dns.SYSTEM.lookup(hostname); } return inetAddresses; @@ -84,14 +84,15 @@ public class OkHttpRequest implements NetworkRequest { @Override public String httpGet(String url) throws Exception { - Log.d(TAG, "使用okhttp 请求" + url + " 异步接口 " + async + " ip类型 " + type.name()); + Log.d(TAG, "浣跨敤okhttp 璇锋眰" + url + " 寮傛鎺ュ彛 " + async + " ip绫诲瀷 " + type.name()); Response response = client.newCall(new Request.Builder().url(url).build()).execute(); int code = response.code(); String body = response.body().string(); - Log.d(TAG, "使用okhttp 请求结果 code " + code + " body " + body); + Log.d(TAG, "浣跨敤okhttp 璇锋眰缁撴灉 code " + code + " body " + body); if (code != HttpURLConnection.HTTP_OK) { - throw new Exception("请求失败 code " + code + " body " + body); + throw new Exception("璇锋眰澶辫触 code " + code + " body " + body); } return body; } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/SpUtil.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/SpUtil.java index bf9c21a..e2843e0 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/SpUtil.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/SpUtil.java @@ -25,3 +25,4 @@ public class SpUtil { void onGetSpEditor(SharedPreferences.Editor editor); } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/ThreadUtil.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/ThreadUtil.java index f5efccf..f16c805 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/ThreadUtil.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/ThreadUtil.java @@ -26,14 +26,14 @@ public class ThreadUtil { } final int tmpValidCount = validCount; Log.d(MyApp.TAG, - threadCount + "线程并发,执行" + executeTime + ", 总域名" + hostCount + "个,有效" - + validCount + "个"); + threadCount + "绾跨▼骞跺彂锛屾墽琛? + executeTime + ", 鎬诲煙鍚? + hostCount + "涓紝鏈夋晥" + + validCount + "涓?); new Thread(new Runnable() { @Override public void run() { final ArrayList hosts = new ArrayList<>(hostCount); for (int i = 0; i < hostCount - tmpValidCount; i++) { - hosts.add("test" + i + ".aliyun.com"); + hosts.add("test" + i + ".Aliyun.com"); } hosts.addAll(Arrays.asList(validHosts).subList(0, tmpValidCount)); @@ -125,3 +125,4 @@ public class ThreadUtil { }).start(); } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/Util.java b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/Util.java index 04ea839..3dd49f2 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/Util.java +++ b/EdgeHttpDNS/sdk/android/app/src/main/java/com/aliyun/ams/httpdns/demo/utils/Util.java @@ -6,8 +6,8 @@ import java.lang.reflect.Field; public class Util { /** - * 获取ttl, - * 此方法是用于测试自定义ttl是否生效 + * 鑾峰彇ttl锛? + * 姝ゆ柟娉曟槸鐢ㄤ簬娴嬭瘯鑷畾涔塼tl鏄惁鐢熸晥 */ public static int getTtl(HTTPDNSResult result) { try { @@ -22,3 +22,4 @@ public class Util { return -1; } } + diff --git a/EdgeHttpDNS/sdk/android/app/src/main/res/layout/activity_webview.xml b/EdgeHttpDNS/sdk/android/app/src/main/res/layout/activity_webview.xml index 872f292..eb9ec73 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/res/layout/activity_webview.xml +++ b/EdgeHttpDNS/sdk/android/app/src/main/res/layout/activity_webview.xml @@ -31,7 +31,7 @@ android:id="@+id/bar_more" android:layout_width="wrap_content" android:layout_height="match_parent" - android:text="更多" + android:text="鏇村" android:textSize="16sp" android:gravity="center" android:paddingLeft="10dp" diff --git a/EdgeHttpDNS/sdk/android/app/src/main/res/values/strings.xml b/EdgeHttpDNS/sdk/android/app/src/main/res/values/strings.xml index 93e2b57..13e45d8 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/res/values/strings.xml +++ b/EdgeHttpDNS/sdk/android/app/src/main/res/values/strings.xml @@ -1,31 +1,31 @@ - 【阿里云HttpDns】Demo程序 + 銆愰樋閲屼簯HttpDns銆慏emo绋嬪簭 Settings - 普通解析 - 解析淘宝域名 - 解析apple域名 - 解析豆瓣域名 - HTTPS开关 - 设置超时 - 允许过期域名 - 开启持久化缓存 - 降级策略 - 预解析 + 鏅€氳В鏋?/string> + 瑙f瀽娣樺疂鍩熷悕 + 瑙f瀽apple鍩熷悕 + 瑙f瀽璞嗙摚鍩熷悕 + HTTPS寮€鍏?/string> + 璁剧疆瓒呮椂 + 鍏佽杩囨湡鍩熷悕 + 寮€鍚寔涔呭寲缂撳瓨 + 闄嶇骇绛栫暐 + 棰勮В鏋?/string> region - 同步解析 - 同步解析并发 - 并发解析 + 鍚屾瑙f瀽 + 鍚屾瑙f瀽骞跺彂 + 骞跺彂瑙f瀽 - 关于我们 - 帮助中心 - 清除当前消息 + 鍏充簬鎴戜滑 + 甯姪涓績 + 娓呴櫎褰撳墠娑堟伅 - + All Rights Reserved. - 阿里云(软件)有限公司版权所有 - Copyright © 2009 - 2016 Aliyun.com + 闃块噷浜?杞欢)鏈夐檺鍏徃鐗堟潈鎵€鏈?/string> + Copyright 漏 2009 - 2016 Aliyun.com 1.1.3 - - Q : 什么是用户体验Demo?\nA : 用户体验Demo就是阿里云平台为您自动创建的、用来体验HttpDns服务和反馈建议用的一个小Demo,让您体验便捷、高效的HttpDns服务。\n\nQ : 如何联系我们?\nA : App Demo相关问题,请搜索钉钉群号:11777313 + + Q : 浠€涔堟槸鐢ㄦ埛浣撻獙Demo锛焅nA : 鐢ㄦ埛浣撻獙Demo灏辨槸闃块噷浜戝钩鍙颁负鎮ㄨ嚜鍔ㄥ垱寤虹殑銆佺敤鏉ヤ綋楠孒ttpDns鏈嶅姟鍜屽弽棣堝缓璁敤鐨勪竴涓皬Demo锛岃鎮ㄤ綋楠屼究鎹枫€侀珮鏁堢殑HttpDns鏈嶅姟銆俓n\nQ : 濡備綍鑱旂郴鎴戜滑锛焅nA : App Demo鐩稿叧闂锛岃鎼滅储閽夐拤缇ゅ彿锛?1777313 diff --git a/EdgeHttpDNS/sdk/android/app/src/main/res/xml/network_security_config.xml b/EdgeHttpDNS/sdk/android/app/src/main/res/xml/network_security_config.xml index f18e1f0..178cbdf 100644 --- a/EdgeHttpDNS/sdk/android/app/src/main/res/xml/network_security_config.xml +++ b/EdgeHttpDNS/sdk/android/app/src/main/res/xml/network_security_config.xml @@ -1,8 +1,8 @@ - + - + - \ No newline at end of file + diff --git a/EdgeHttpDNS/sdk/android/demo/build.gradle b/EdgeHttpDNS/sdk/android/demo/build.gradle index 110e39a..7555499 100644 --- a/EdgeHttpDNS/sdk/android/demo/build.gradle +++ b/EdgeHttpDNS/sdk/android/demo/build.gradle @@ -22,9 +22,9 @@ android { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" buildConfigField "String", "HTTPDNS_VERSION", "\"${gradle.httpVersion}\"" - buildConfigField "String", "ACCOUNT_ID", "\"请替换为测试用实例的accountId\"" - buildConfigField "String", "SECRET_KEY", "\"请替换为测试用实例的secret\"" - buildConfigField "String", "AES_SECRET_KEY", "\"请替换为测试用实例的aes\"" + buildConfigField "String", "ACCOUNT_ID", "\"璇锋浛鎹负娴嬭瘯鐢ㄥ疄渚嬬殑accountId\"" + buildConfigField "String", "SECRET_KEY", "\"璇锋浛鎹负娴嬭瘯鐢ㄥ疄渚嬬殑secret\"" + buildConfigField "String", "AES_SECRET_KEY", "\"璇锋浛鎹负娴嬭瘯鐢ㄥ疄渚嬬殑aes\"" } buildTypes { @@ -40,7 +40,7 @@ android { } forTest { - // 注意这里的配置,并不是需要编译forTest的app,而是避免httpdns-sdk在AndroidStudio改为end2end运行测试时 BuildVariants报错 + // 娉ㄦ剰杩欓噷鐨勯厤缃紝骞朵笉鏄渶瑕佺紪璇慺orTest鐨刟pp锛岃€屾槸閬垮厤httpdns-sdk鍦ˋndroidStudio鏀逛负end2end杩愯娴嬭瘯鏃?BuildVariants鎶ラ敊 initWith release debuggable true } @@ -92,7 +92,7 @@ android { } end2end { - // 注意这里的配置,并不是需要编译end2end的app,而是避免httpdns-sdk在AndroidStudio改为end2end运行测试时 BuildVariants报错 + // 娉ㄦ剰杩欓噷鐨勯厤缃紝骞朵笉鏄渶瑕佺紪璇慹nd2end鐨刟pp锛岃€屾槸閬垮厤httpdns-sdk鍦ˋndroidStudio鏀逛负end2end杩愯娴嬭瘯鏃?BuildVariants鎶ラ敊 } } diff --git a/EdgeHttpDNS/sdk/android/demo/src/androidTest/java/com/alibaba/ams/emas/demo/ExampleInstrumentedTest.kt b/EdgeHttpDNS/sdk/android/demo/src/androidTest/java/com/alibaba/ams/emas/demo/ExampleInstrumentedTest.kt index 3556324..7c658d9 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/androidTest/java/com/alibaba/ams/emas/demo/ExampleInstrumentedTest.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/androidTest/java/com/alibaba/ams/emas/demo/ExampleInstrumentedTest.kt @@ -21,4 +21,5 @@ class ExampleInstrumentedTest { val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.alibaba.ams.emas.demo", appContext.packageName) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/BatchResolveCacheHolder.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/BatchResolveCacheHolder.kt index 304e92d..2828b3c 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/BatchResolveCacheHolder.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/BatchResolveCacheHolder.kt @@ -11,7 +11,7 @@ object BatchResolveCacheHolder { if (cacheData == null) { batchResolveBothList.add("www.baidu.com") batchResolveBothList.add("m.baidu.com") - batchResolveBothList.add("www.aliyun.com") + batchResolveBothList.add("www.Aliyun.com") batchResolveBothList.add("www.taobao.com") batchResolveBothList.add("www.163.com") batchResolveBothList.add("www.sohu.com") @@ -88,4 +88,5 @@ object BatchResolveCacheHolder { jsonObject.put("auto", autoArray) return jsonObject.toString() } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsApplication.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsApplication.kt index 1801f6f..b6ecabe 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsApplication.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsApplication.kt @@ -13,4 +13,5 @@ class HttpDnsApplication : Application() { } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsServiceHolder.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsServiceHolder.kt index 907d2c9..0c1d46d 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsServiceHolder.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/HttpDnsServiceHolder.kt @@ -34,4 +34,5 @@ object HttpDnsServiceHolder { return dnsService } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/MainActivity.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/MainActivity.kt index 17431b1..80dc162 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/MainActivity.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/MainActivity.kt @@ -48,4 +48,5 @@ class MainActivity : AppCompatActivity() { } } } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/PreResolveCacheHolder.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/PreResolveCacheHolder.kt index 1db0fc5..76e99cb 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/PreResolveCacheHolder.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/PreResolveCacheHolder.kt @@ -89,4 +89,5 @@ object PreResolveCacheHolder { return jsonObject.toString() } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/SingleLiveData.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/SingleLiveData.kt index e6d7419..db7f81b 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/SingleLiveData.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/SingleLiveData.kt @@ -45,3 +45,4 @@ class SingleLiveData : MutableLiveData() { value = null } } + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/TtlCacheHolder.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/TtlCacheHolder.kt index 532dd0e..3d11333 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/TtlCacheHolder.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/TtlCacheHolder.kt @@ -47,4 +47,5 @@ object TtlCacheHolder { return jsonObject.toString() } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/Util.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/Util.kt index 2bf195c..b04129f 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/Util.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/Util.kt @@ -113,7 +113,7 @@ fun String?.toBlackList(): MutableList? { fun getAccountPreference(context: Context): SharedPreferences { return context.getSharedPreferences( - "aliyun_httpdns_${BuildConfig.ACCOUNT_ID}", + "Aliyun_httpdns_${BuildConfig.ACCOUNT_ID}", Context.MODE_PRIVATE ) } @@ -138,3 +138,4 @@ fun readStringFrom(streamReader: BufferedReader): StringBuilder { } return sb } + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/constant/Constant.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/constant/Constant.kt index b497330..bb0b22c 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/constant/Constant.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/constant/Constant.kt @@ -51,4 +51,5 @@ const val KEY_PRE_RESOLVE_HOST_LIST = "pre_resolve_host_list" const val KEY_SDNS_GLOBAL_PARAMS = "sdns_global_params" -const val KEY_BATCH_RESOLVE_HOST_LIST = "batch_resolve_host_list" \ No newline at end of file +const val KEY_BATCH_RESOLVE_HOST_LIST = "batch_resolve_host_list" + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/HttpURLConnectionRequest.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/HttpURLConnectionRequest.kt index c2f0780..e0e8c42 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/HttpURLConnectionRequest.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/HttpURLConnectionRequest.kt @@ -52,7 +52,7 @@ class HttpURLConnectionRequest(private val context: Context, private val request var ipURL: String? = null dnsService?.let { - //替换为最新的api + //鏇挎崲涓烘渶鏂扮殑api Log.d("HttpURLConnection", "start lookup $host via $resolveMethod") var httpDnsResult = HTTPDNSResult("", null, null, null, false, false) if (resolveMethod == "getHttpDnsResultForHostSync(String host, RequestIpType type)") { @@ -83,7 +83,7 @@ class HttpURLConnectionRequest(private val context: Context, private val request } } - Log.d("HttpURLConnection", "httpdns $host 解析结果 $httpDnsResult") + Log.d("HttpURLConnection", "httpdns $host 瑙f瀽缁撴灉 $httpDnsResult") val ipStackType = HttpDnsNetworkDetector.getInstance().getNetType(context) val isV6 = ipStackType == NetType.v6 || ipStackType == NetType.both val isV4 = ipStackType == NetType.v4 || ipStackType == NetType.both @@ -104,9 +104,9 @@ class HttpURLConnectionRequest(private val context: Context, private val request if (conn is HttpsURLConnection) { val sslSocketFactory = TLSSNISocketFactory(conn) - // SNI场景,创建SSLSocket + // SNI鍦烘櫙锛屽垱寤篠SLSocket conn.sslSocketFactory = sslSocketFactory - // https场景,证书校验 + // https鍦烘櫙锛岃瘉涔︽牎楠? conn.hostnameVerifier = HostnameVerifier { _, session -> val requestHost = conn.getRequestProperty("Host") ?:conn.getURL().host HttpsURLConnection.getDefaultHostnameVerifier().verify(requestHost, session) @@ -115,13 +115,13 @@ class HttpURLConnectionRequest(private val context: Context, private val request val responseCode = conn.responseCode if (needRedirect(responseCode)) { - //临时重定向和永久重定向location的大小写有区分 + //涓存椂閲嶅畾鍚戝拰姘镐箙閲嶅畾鍚憀ocation鐨勫ぇ灏忓啓鏈夊尯鍒? var location = conn.getHeaderField("Location") if (location == null) { location = conn.getHeaderField("location") } if (!(location!!.startsWith("http://") || location.startsWith("https://"))) { - //某些时候会省略host,只返回后面的path,所以需要补全url + //鏌愪簺鏃跺€欎細鐪佺暐host锛屽彧杩斿洖鍚庨潰鐨刾ath锛屾墍浠ラ渶瑕佽ˉ鍏╱rl val originalUrl = URL(url) location = (originalUrl.protocol + "://" + originalUrl.host + location) @@ -135,4 +135,5 @@ class HttpURLConnectionRequest(private val context: Context, private val request return code in 300..399 } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/IRequest.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/IRequest.kt index a202464..1c78dfb 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/IRequest.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/IRequest.kt @@ -8,4 +8,5 @@ import com.alibaba.ams.emas.demo.ui.resolve.Response */ interface IRequest { fun get(url: String): Response -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpClientSingleton.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpClientSingleton.kt index ca0a77b..1ff338e 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpClientSingleton.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpClientSingleton.kt @@ -74,7 +74,7 @@ import java.util.concurrent.TimeUnit override fun lookup(hostname: String): List { Log.d(tag, "start lookup $hostname via $mResolveMethod") val dnsService = HttpDnsServiceHolder.getHttpDnsService(mContext.get()!!) - //修改为最新的通俗易懂的api + //淇敼涓烘渶鏂扮殑閫氫織鏄撴噦鐨刟pi var httpDnsResult: HTTPDNSResult? = null val inetAddresses = mutableListOf() if (mResolveMethod == "getHttpDnsResultForHostSync(String host, RequestIpType type)") { @@ -113,11 +113,11 @@ import java.util.concurrent.TimeUnit } } - Log.d(tag, "httpdns $hostname 解析结果 $httpDnsResult") + Log.d(tag, "httpdns $hostname 瑙f瀽缁撴灉 $httpDnsResult") httpDnsResult?.let { processDnsResult(it, inetAddresses) } if (inetAddresses.isEmpty()) { - Log.d(tag, "httpdns 未返回IP,走local dns") + Log.d(tag, "httpdns 鏈繑鍥濱P锛岃蛋local dns") return Dns.SYSTEM.lookup(hostname) } return inetAddresses @@ -147,3 +147,4 @@ import java.util.concurrent.TimeUnit } } } + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpLog.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpLog.kt index aa1eb25..adb4c2c 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpLog.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpLog.kt @@ -7,4 +7,5 @@ class OkHttpLog: HttpLoggingInterceptor.Logger { override fun log(message: String) { Log.d("Okhttp", message) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpRequest.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpRequest.kt index 0964c10..3144bf2 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpRequest.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/OkHttpRequest.kt @@ -23,4 +23,5 @@ class OkHttpRequest constructor( .use { response -> return Response(response.code, response.body?.string()) } } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/TLSSNISocketFactory.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/TLSSNISocketFactory.kt index 5a514ad..5d74453 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/TLSSNISocketFactory.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/net/TLSSNISocketFactory.kt @@ -80,4 +80,5 @@ class TLSSNISocketFactory(connection: HttpsURLConnection): SSLSocketFactory() { override fun getSupportedCipherSuites(): Array { return arrayOfNulls(0) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingFragment.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingFragment.kt index 33e6881..14732ca 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingFragment.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingFragment.kt @@ -175,4 +175,5 @@ class BasicSettingFragment : Fragment(), IBasicShowDialog { _binding?.initHttpdns?.isClickable = false }) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingViewModel.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingViewModel.kt index 2f03d7c..438d6fe 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingViewModel.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/BasicSettingViewModel.kt @@ -37,54 +37,54 @@ class BasicSettingViewModel(application: Application) : AndroidViewModel(applica var secretKeySetByConfig = true /** - * 是否开启鉴权模式 + * 鏄惁寮€鍚壌鏉冩ā寮? */ var enableAuthMode = true /** - * 是否开启加密模式 + * 鏄惁寮€鍚姞瀵嗘ā寮? */ var enableEncryptMode = true /** - * 是否允许过期IP + * 鏄惁鍏佽杩囨湡IP */ var enableExpiredIP = false /** - * 是否开启本地缓存 + * 鏄惁寮€鍚湰鍦扮紦瀛? */ var enableCacheIP = false /** - * 是否允许HTTPS + * 鏄惁鍏佽HTTPS */ var enableHttps = false /** - * 是否开启降级 + * 鏄惁寮€鍚檷绾? */ var enableDegrade = false /** - * 是否允许网络切换自动刷新 + * 鏄惁鍏佽缃戠粶鍒囨崲鑷姩鍒锋柊 */ var enableAutoRefresh = false /** - * 是否允许打印日志 + * 鏄惁鍏佽鎵撳嵃鏃ュ織 */ var enableLog = false /** - * 当前Region + * 褰撳墠Region */ var currentRegion = SingleLiveData().apply { value = "" } /** - * 当前超时 + * 褰撳墠瓒呮椂 */ var currentTimeout = SingleLiveData().apply { value = "2000ms" @@ -188,7 +188,7 @@ class BasicSettingViewModel(application: Application) : AndroidViewModel(applica } fun setRegion() { - //弹窗选择region + //寮圭獥閫夋嫨region showDialog?.showSelectRegionDialog() } @@ -253,21 +253,21 @@ class BasicSettingViewModel(application: Application) : AndroidViewModel(applica val timeout = preferences.getInt(KEY_TIMEOUT, 2000) val region = preferences.getString(KEY_REGION, "cn") val enableDegradationLocalDns = preferences.getBoolean(KEY_ENABLE_DEGRADE, false); - //自定义ttl + //鑷畾涔塼tl val ttlCacheStr = preferences.getString(KEY_TTL_CHANGER, null) TtlCacheHolder.convertTtlCacheData(ttlCacheStr) - //IP探测 + //IP鎺㈡祴 val ipRankingItemJson = preferences.getString(KEY_IP_RANKING_ITEMS, null) - //主站域名 + //涓荤珯鍩熷悕 val hostListWithFixedIpJson = preferences.getString(KEY_HOST_WITH_FIXED_IP, null) val tagsJson = preferences.getString(KEY_TAGS, null) - //预解析 + //棰勮В鏋? val preResolveHostList = preferences.getString(KEY_PRE_RESOLVE_HOST_LIST, null) preResolveHostList?.let { Log.d("httpdns:HttpDnsApplication", "pre resolve list: $it") } PreResolveCacheHolder.convertPreResolveCacheData(preResolveHostList) - //批量解析 + //鎵归噺瑙f瀽 val batchResolveHostList = preferences.getString(KEY_BATCH_RESOLVE_HOST_LIST, null) BatchResolveCacheHolder.convertBatchResolveCacheData(batchResolveHostList) @@ -358,4 +358,5 @@ class BasicSettingViewModel(application: Application) : AndroidViewModel(applica private fun getString(resId: Int, vararg args: String): String { return getApplication().getString(resId, *args) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/IBasicShowDialog.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/IBasicShowDialog.kt index e3da043..47a7af7 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/IBasicShowDialog.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/basic/IBasicShowDialog.kt @@ -14,4 +14,5 @@ interface IBasicShowDialog { fun showAddPreResolveDialog() fun onHttpDnsInit() -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoFragment.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoFragment.kt index 74c07d6..8918f99 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoFragment.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoFragment.kt @@ -91,4 +91,5 @@ class InfoFragment : Fragment() { } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoViewModel.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoViewModel.kt index 85911cd..b813ebe 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoViewModel.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/InfoViewModel.kt @@ -16,14 +16,14 @@ import com.aliyun.ams.httpdns.demo.R class InfoViewModel(application: Application) : AndroidViewModel(application) { /** - * 账户ID + * 璐︽埛ID */ val accountId = SingleLiveData().apply { value = "" } /** - * 账户secret + * 璐︽埛secret */ val secretKey = SingleLiveData() @@ -59,4 +59,5 @@ class InfoViewModel(application: Application) : AndroidViewModel(application) { } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/SdnsGlobalSettingActivity.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/SdnsGlobalSettingActivity.kt index 79a283a..c52d02a 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/SdnsGlobalSettingActivity.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/SdnsGlobalSettingActivity.kt @@ -42,4 +42,5 @@ class SdnsGlobalSettingActivity: AppCompatActivity() { } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListActivity.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListActivity.kt index 4728264..367c8c0 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListActivity.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListActivity.kt @@ -52,7 +52,7 @@ class ListActivity : AppCompatActivity(), ListAdapter.OnDeleteListener { binding.infoListToolbar.title = title setSupportActionBar(binding.infoListToolbar) - supportActionBar?.setDisplayHomeAsUpEnabled(true)//添加默认的返回图标 + supportActionBar?.setDisplayHomeAsUpEnabled(true)//娣诲姞榛樿鐨勮繑鍥炲浘鏍? supportActionBar?.setHomeButtonEnabled(true) binding.infoListView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) @@ -170,7 +170,7 @@ class ListActivity : AppCompatActivity(), ListAdapter.OnDeleteListener { ipTypeGroup.addView(view) view = createIpTypeRadio(this) - view.text = "自动判断IP类型" + view.text = "鑷姩鍒ゆ柇IP绫诲瀷" view.tag = 3 ipTypeGroup.addView(view) @@ -214,7 +214,7 @@ class ListActivity : AppCompatActivity(), ListAdapter.OnDeleteListener { view.tag = 2 ipTypeGroup.addView(view) view = createIpTypeRadio(this) - view.text = "自动判断IP类型" + view.text = "鑷姩鍒ゆ柇IP绫诲瀷" view.tag = 3 ipTypeGroup.addView(view) val builder = AlertDialog.Builder(this) @@ -325,7 +325,7 @@ class ListActivity : AppCompatActivity(), ListAdapter.OnDeleteListener { } override fun onHostWithFixedIPDeleted(position: Int) { - //只能重启生效 + //鍙兘閲嶅惎鐢熸晥 viewModel.onHostWithFixedIPDeleted(position) } @@ -349,4 +349,5 @@ class ListActivity : AppCompatActivity(), ListAdapter.OnDeleteListener { override fun onBatchResolveDeleted(host: String, intValue: Int) { viewModel.onBatchResolveDeleted(host, intValue) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListAdapter.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListAdapter.kt index 2c44029..46beaf9 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListAdapter.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListAdapter.kt @@ -109,7 +109,7 @@ class ListAdapter(private val context: Context, 0 -> "IPv4" 1 -> "IPv6" 2 -> "IPv4&IPv6" - else -> "自动判断IP类型" + else -> "鑷姩鍒ゆ柇IP绫诲瀷" } binding.portOrTtlIndicate.text = context.getString(R.string.ip_type) } @@ -121,7 +121,7 @@ class ListAdapter(private val context: Context, 0 -> "IPv4" 1 -> "IPv6" 2 -> "IPv4&IPv6" - else -> "自动判断IP类型" + else -> "鑷姩鍒ゆ柇IP绫诲瀷" } binding.portOrTtlIndicate.text = context.getString(R.string.ip_type) } @@ -147,4 +147,5 @@ class ListAdapter(private val context: Context, fun onBatchResolveDeleted(host: String, intValue: Int) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItem.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItem.kt index b391013..03f3f62 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItem.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItem.kt @@ -5,4 +5,5 @@ package com.alibaba.ams.emas.demo.ui.info.list * @date 2023/6/5 */ -data class ListItem(var type: Int, var content: String, var intValue: Int) \ No newline at end of file +data class ListItem(var type: Int, var content: String, var intValue: Int) + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItemType.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItemType.kt index 71397d1..75f518a 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItemType.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListItemType.kt @@ -17,4 +17,5 @@ const val kListItemTypeBlackList = 0x05 const val kListItemBatchResolve = 0x06 -const val kListItemTag = 0x07 \ No newline at end of file +const val kListItemTag = 0x07 + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListViewModel.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListViewModel.kt index 5404137..9793530 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListViewModel.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/info/list/ListViewModel.kt @@ -354,7 +354,7 @@ class ListViewModel(application: Application) : AndroidViewModel(application) { } fun onHostWithFixedIPDeleted(position: Int) { - //只能重启生效 + //鍙兘閲嶅惎鐢熸晥 val deletedHost = hostFixedIpList.removeAt(position) saveHostWithFixedIP() } @@ -403,4 +403,5 @@ class ListViewModel(application: Application) : AndroidViewModel(application) { private fun getString(resId: Int, vararg args: String): String { return getApplication().getString(resId, *args) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeFragment.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeFragment.kt index 252573b..6d663e4 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeFragment.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeFragment.kt @@ -64,4 +64,5 @@ class BestPracticeFragment : Fragment(), IBestPracticeShowDialog { } builder?.show() } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeViewModel.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeViewModel.kt index 7891fd4..25a926f 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeViewModel.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/BestPracticeViewModel.kt @@ -10,7 +10,7 @@ import com.alibaba.ams.emas.demo.readStringFrom import com.alibaba.sdk.android.httpdns.NetType import com.alibaba.sdk.android.httpdns.RequestIpType import com.alibaba.sdk.android.httpdns.net.HttpDnsNetworkDetector -import com.alibaba.sdk.android.tool.NetworkUtils +import com.Alibaba.sdk.android.tool.NetworkUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -56,7 +56,7 @@ class BestPracticeViewModel(application: Application) : AndroidViewModel(applica val dnsService = HttpDnsServiceHolder.getHttpDnsService(getApplication()) dnsService?.let { val httpDnsResult = dnsService.getIpsByHostAsync(host, RequestIpType.both) - Log.d("httpdns", "$host 解析结果 $httpDnsResult") + Log.d("httpdns", "$host 瑙f瀽缁撴灉 $httpDnsResult") val ipStackType = HttpDnsNetworkDetector.getInstance().getNetType(getApplication()) val isV6 = ipStackType == NetType.v6 || ipStackType == NetType.both val isV4 = ipStackType == NetType.v4 || ipStackType == NetType.both @@ -75,9 +75,9 @@ class BestPracticeViewModel(application: Application) : AndroidViewModel(applica conn.readTimeout = 30000 conn.instanceFollowRedirects = false - //设置SNI + //璁剧疆SNI val sslSocketFactory = TLSSNISocketFactory(conn) - // SNI场景,创建SSLSocket + // SNI鍦烘櫙锛屽垱寤篠SLSocket conn.sslSocketFactory = sslSocketFactory conn.hostnameVerifier = HostnameVerifier { _, session -> val requestHost = conn.getRequestProperty("Host") ?: conn.url.host @@ -85,13 +85,13 @@ class BestPracticeViewModel(application: Application) : AndroidViewModel(applica } val code = conn.responseCode if (needRedirect(code)) { - //临时重定向和永久重定向location的大小写有区分 + //涓存椂閲嶅畾鍚戝拰姘镐箙閲嶅畾鍚憀ocation鐨勫ぇ灏忓啓鏈夊尯鍒? var location = conn.getHeaderField("Location") if (location == null) { location = conn.getHeaderField("location") } if (!(location!!.startsWith("http://") || location.startsWith("https://"))) { - //某些时候会省略host,只返回后面的path,所以需要补全url + //鏌愪簺鏃跺€欎細鐪佺暐host锛屽彧杩斿洖鍚庨潰鐨刾ath锛屾墍浠ラ渶瑕佽ˉ鍏╱rl val originalUrl = URL(url) location = (originalUrl.protocol + "://" + originalUrl.host + location) @@ -123,4 +123,5 @@ class BestPracticeViewModel(application: Application) : AndroidViewModel(applica return code in 300..399 } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/HttpDnsWebviewGetActivity.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/HttpDnsWebviewGetActivity.kt index 9b52213..2de146f 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/HttpDnsWebviewGetActivity.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/HttpDnsWebviewGetActivity.kt @@ -26,7 +26,7 @@ class HttpDnsWebviewGetActivity : AppCompatActivity() { binding.webviewToolbar.title = getString(R.string.httpdns_webview_best_practice) setSupportActionBar(binding.webviewToolbar) - supportActionBar?.setDisplayHomeAsUpEnabled(true)//添加默认的返回图标 + supportActionBar?.setDisplayHomeAsUpEnabled(true)//娣诲姞榛樿鐨勮繑鍥炲浘鏍? supportActionBar?.setHomeButtonEnabled(true) binding.httpdnsWebview.webViewClient = object : WebViewClient() { @@ -55,7 +55,7 @@ class HttpDnsWebviewGetActivity : AppCompatActivity() { val contentType = urlConnection.contentType val mimeType = contentType?.split(";")?.get(0) if (TextUtils.isEmpty(mimeType)) { - //无mimeType得请求不拦截 + //鏃爉imeType寰楄姹備笉鎷︽埅 return super.shouldInterceptRequest(view, request) } val charset = getCharset(contentType) @@ -79,7 +79,7 @@ class HttpDnsWebviewGetActivity : AppCompatActivity() { resourceResponse.setStatusCodeAndReasonPhrase(statusCode, response) val responseHeader: MutableMap = HashMap() for ((key) in headerFields) { - // HttpUrlConnection可能包含key为null的报头,指向该http请求状态码 + // HttpUrlConnection鍙兘鍖呭惈key涓簄ull鐨勬姤澶达紝鎸囧悜璇ttp璇锋眰鐘舵€佺爜 responseHeader[key] = httpURLConnection.getHeaderField(key) } resourceResponse.responseHeaders = responseHeader @@ -156,7 +156,7 @@ class HttpDnsWebviewGetActivity : AppCompatActivity() { return if (location != null) { if (!(location.startsWith("http://") || location.startsWith("https://"))) { - //某些时候会省略host,只返回后面的path,所以需要补全url + //鏌愪簺鏃跺€欎細鐪佺暐host锛屽彧杩斿洖鍚庨潰鐨刾ath锛屾墍浠ラ渶瑕佽ˉ鍏╱rl val originalUrl = URL(path) location = (originalUrl.protocol + "://" + originalUrl.host + location) } diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/IBestPracticeShowDialog.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/IBestPracticeShowDialog.kt index 87d8e34..9cb9bae 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/IBestPracticeShowDialog.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/IBestPracticeShowDialog.kt @@ -8,4 +8,5 @@ interface IBestPracticeShowDialog { fun showResponseDialog( message: String) fun showNoNetworkDialog() -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/SNISocketFactory.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/SNISocketFactory.kt index c0a1310..78a914e 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/SNISocketFactory.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/practice/SNISocketFactory.kt @@ -79,3 +79,4 @@ class SNISocketFactory(private val conn: HttpsURLConnection) : SSLSocketFactory( } } + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/IResolveShowDialog.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/IResolveShowDialog.kt index ae76563..e1b23b2 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/IResolveShowDialog.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/IResolveShowDialog.kt @@ -14,4 +14,5 @@ interface IResolveShowDialog { fun showResolveMethodDialog() fun showRequestNumberDialog() -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/NetRequestType.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/NetRequestType.kt index a1a7b99..d249eec 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/NetRequestType.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/NetRequestType.kt @@ -8,4 +8,5 @@ enum class NetRequestType { OKHTTP, HTTP_URL_CONNECTION -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveFragment.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveFragment.kt index 1b50303..c519506 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveFragment.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveFragment.kt @@ -68,14 +68,14 @@ class ResolveFragment : Fragment(), IResolveShowDialog { binding.startResolve.setOnClickListener { binding.resolveHostInputLayout.error = "" - //1. 校验域名是否填写 + //1. 鏍¢獙鍩熷悕鏄惁濉啓 val host = binding.resolveHostInputLayout.editText?.text.toString() if (TextUtils.isEmpty(host)) { binding.resolveHostInputLayout.error = getString(R.string.resolve_host_empty) return@setOnClickListener } var sdnsParams: MutableMap? = null - //2. 校验sdns参数 + //2. 鏍¢獙sdns鍙傛暟 if (viewModel.isSdns.value!!) { val sdnsParamsStr = binding.sdnsParamsInputLayout.editText?.text.toString() if (!TextUtils.isEmpty(sdnsParamsStr)) { @@ -177,7 +177,7 @@ class ResolveFragment : Fragment(), IResolveShowDialog { val builder = activity?.let { act -> AlertDialog.Builder(act) } builder?.apply { setTitle(R.string.select_resolve_method) - val items = arrayOf("同步方法", "异步方法", "同步非阻塞方法") + val items = arrayOf("鍚屾鏂规硶", "寮傛鏂规硶", "鍚屾闈為樆濉炴柟娉?) val preferences = activity?.let { getAccountPreference(it) } var resolvedMethod = preferences?.getString(KEY_RESOLVE_METHOD, "getHttpDnsResultForHostSync(String host, RequestIpType type)").toString() @@ -229,4 +229,5 @@ class ResolveFragment : Fragment(), IResolveShowDialog { } builder?.show() } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveViewModel.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveViewModel.kt index 862cfa4..c4b1719 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveViewModel.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/ResolveViewModel.kt @@ -149,4 +149,5 @@ class ResolveViewModel(application: Application) : AndroidViewModel(application) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/Response.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/Response.kt index 9fa457c..76d1bd0 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/Response.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/Response.kt @@ -5,3 +5,4 @@ package com.alibaba.ams.emas.demo.ui.resolve * @date 2023/6/14 */ data class Response(val code: Int, val body: String?) + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/SchemaType.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/SchemaType.kt index 9173511..2043c35 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/SchemaType.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/ui/resolve/SchemaType.kt @@ -8,4 +8,5 @@ enum class SchemaType { HTTPS, HTTP -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/widget/SwipeLayout.kt b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/widget/SwipeLayout.kt index e3872d9..cb5c2c9 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/widget/SwipeLayout.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/main/java/com/alibaba/ams/emas/demo/widget/SwipeLayout.kt @@ -37,18 +37,18 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) /** - * 初始化方法 + * 鍒濆鍖栨柟娉? * * @param context * @param attrs * @param defStyleAttr */ private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) { - //创建辅助对象 + //鍒涘缓杈呭姪瀵硅薄 val viewConfiguration = ViewConfiguration.get(context) scaledTouchSlop = viewConfiguration.scaledTouchSlop scroller = Scroller(context) - //1、获取配置的属性值 + //1銆佽幏鍙栭厤缃殑灞炴€у€? val typedArray = context.theme .obtainStyledAttributes(attrs, R.styleable.SwipeLayout, defStyleAttr, 0) try { @@ -77,7 +77,7 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) - //获取childView的个数 + //鑾峰彇childView鐨勪釜鏁? isClickable = true var count = childCount val measureMatchParentChildren = @@ -173,7 +173,7 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : contentView!!.isClickable = true } } - //布局contentView + //甯冨眬contentView val cRight: Int if (contentView != null) { contentViewLayoutParam = contentView!!.layoutParams as MarginLayoutParams? @@ -227,7 +227,7 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : return@run } scrollBy(distanceX.toInt(), 0) - //越界修正 + //瓒婄晫淇 if (scrollX < 0) { scrollTo(0, 0) } else if (scrollX > 0) { @@ -238,7 +238,7 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : ) } } - //当处于水平滑动时,禁止父类拦截 + //褰撳浜庢按骞虫粦鍔ㄦ椂锛岀姝㈢埗绫绘嫤鎴? if (abs(distanceX) > scaledTouchSlop) { parent.requestDisallowInterceptTouchEvent(true) } @@ -261,13 +261,13 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : when (event.action) { MotionEvent.ACTION_DOWN -> {} MotionEvent.ACTION_MOVE -> { - //滑动时拦截点击时间 + //婊戝姩鏃舵嫤鎴偣鍑绘椂闂? if (abs(finalDistanceX) > scaledTouchSlop) { return true } } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { - //滑动后不触发contentView的点击事件 + //婊戝姩鍚庝笉瑙﹀彂contentView鐨勭偣鍑讳簨浠? if (isSwiping) { isSwiping = false finalDistanceX = 0f @@ -279,7 +279,7 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : } /** - * 自动设置状态 + * 鑷姩璁剧疆鐘舵€? * * @param result */ @@ -302,7 +302,7 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : } override fun computeScroll() { - //判断Scroller是否执行完毕: + //鍒ゆ柇Scroller鏄惁鎵ц瀹屾瘯锛? if (scroller!!.computeScrollOffset()) { scrollTo(scroller!!.currX, scroller!!.currY) invalidate() @@ -310,7 +310,7 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : } /** - * 根据当前的scrollX的值判断松开手后应处于何种状态 + * 鏍规嵁褰撳墠鐨剆crollX鐨勫€煎垽鏂澗寮€鎵嬪悗搴斿浜庝綍绉嶇姸鎬? * * @param * @param scrollX @@ -321,12 +321,12 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : return mStateCache } if (finalDistanceX < 0) { - //关闭右边 + //鍏抽棴鍙宠竟 if (scrollX > 0 && menuView != null) { return State.CLOSE } } else if (finalDistanceX > 0) { - //开启右边 + //寮€鍚彸杈? if (scrollX > 0 && menuView != null) { if (abs(menuView!!.width * fraction) < abs(scrollX)) { return State.RIGHT_OPEN @@ -360,4 +360,5 @@ class SwipeLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : enum class State { RIGHT_OPEN, CLOSE } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/demo/src/main/res/values-zh-rCN/strings.xml b/EdgeHttpDNS/sdk/android/demo/src/main/res/values-zh-rCN/strings.xml index 1dd3608..e465a8d 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/main/res/values-zh-rCN/strings.xml +++ b/EdgeHttpDNS/sdk/android/demo/src/main/res/values-zh-rCN/strings.xml @@ -1,138 +1,138 @@ - 阿里云HttpDNS官方Demo - 基础设置 - HttpDNS解析 - 最佳实践 - 信息 + 闃块噷浜慔ttpDNS瀹樻柟Demo + 鍩虹璁剧疆 + HttpDNS瑙f瀽 + 鏈€浣冲疄璺?/string> + 淇℃伅 - 开启鉴权模式 - SecretKey通过config配置 - 开启加密模式 - 允许过期IP - 开启持久化缓存IP - 缓存过期时间 - 缓存过期时间的单位是天. - 开启HTTPS - 允许降级 - 网络切换自动刷新 - 允许SDK打印日志 - 超时时间 - 请先初始化HttpDns - 已经初始化 + 寮€鍚壌鏉冩ā寮?/string> + SecretKey閫氳繃config閰嶇疆 + 寮€鍚姞瀵嗘ā寮?/string> + 鍏佽杩囨湡IP + 寮€鍚寔涔呭寲缂撳瓨IP + 缂撳瓨杩囨湡鏃堕棿 + 缂撳瓨杩囨湡鏃堕棿鐨勫崟浣嶆槸澶? + 寮€鍚疕TTPS + 鍏佽闄嶇骇 + 缃戠粶鍒囨崲鑷姩鍒锋柊 + 鍏佽SDK鎵撳嵃鏃ュ織 + 瓒呮椂鏃堕棿 + 璇峰厛鍒濆鍖朒ttpDns + 宸茬粡鍒濆鍖?/string> - 中国 - 中国香港 - 新加坡 - 德国 - 美国 - 预发 + 涓浗 + 涓浗棣欐腐 + 鏂板姞鍧?/string> + 寰峰浗 + 缇庡浗 + 棰勫彂 - 选择Region - 确认 - 取消 - 请输入超时时间,毫秒为单位 - 设置超时 - 超时时间为空 + 閫夋嫨Region + 纭 + 鍙栨秷 + 璇疯緭鍏ヨ秴鏃舵椂闂达紝姣涓哄崟浣?/string> + 璁剧疆瓒呮椂 + 瓒呮椂鏃堕棿涓虹┖ - 探测IP列表 - 自定义TTL缓存列表 - 主站域名列表 - 域名黑名单列表 - 自定义解析全局参数 - 批量解析域名 + 鎺㈡祴IP鍒楄〃 + 鑷畾涔塗TL缂撳瓨鍒楄〃 + 涓荤珯鍩熷悕鍒楄〃 + 鍩熷悕榛戝悕鍗曞垪琛?/string> + 鑷畾涔夎В鏋愬叏灞€鍙傛暟 + 鎵归噺瑙f瀽鍩熷悕 - HttpDNS版本号 - 未知 - 当前所连接网络的网络栈类型 - 清空指定域名缓存 - 请输入要清空缓存的域名 - 网络请求类型 - 异步解析获取IP - 自定义域名解析 - 要解析的IP类型 - 使用的解析方法 - 并发请求次数 + HttpDNS鐗堟湰鍙?/string> + 鏈煡 + 褰撳墠鎵€杩炴帴缃戠粶鐨勭綉缁滄爤绫诲瀷 + 娓呯┖鎸囧畾鍩熷悕缂撳瓨 + 璇疯緭鍏ヨ娓呯┖缂撳瓨鐨勫煙鍚?/string> + 缃戠粶璇锋眰绫诲瀷 + 寮傛瑙f瀽鑾峰彇IP + 鑷畾涔夊煙鍚嶈В鏋?/string> + 瑕佽В鏋愮殑IP绫诲瀷 + 浣跨敤鐨勮В鏋愭柟娉?/string> + 骞跺彂璇锋眰娆℃暟 - 选择IP类型 - 选择解析方法 - 选择并发请求次数 - 自动判断IP类型 - 添加预解析域名 - 请输入要预解析的域名 - 预解析域名列表 - 添加Tag - %s域名已经被添加至预解析列表,请勿重复添加 - 初始化HttpDns - 批量解析域名列表 - 请输入要批量解析的域名 - 请输入要批量解析的域名 - %s域名已经被添加至批量解析列表,请勿重复添加 + 閫夋嫨IP绫诲瀷 + 閫夋嫨瑙f瀽鏂规硶 + 閫夋嫨骞跺彂璇锋眰娆℃暟 + 鑷姩鍒ゆ柇IP绫诲瀷 + 娣诲姞棰勮В鏋愬煙鍚?/string> + 璇疯緭鍏ヨ棰勮В鏋愮殑鍩熷悕 + 棰勮В鏋愬煙鍚嶅垪琛?/string> + 娣诲姞Tag + %s鍩熷悕宸茬粡琚坊鍔犺嚦棰勮В鏋愬垪琛紝璇峰嬁閲嶅娣诲姞 + 鍒濆鍖朒ttpDns + 鎵归噺瑙f瀽鍩熷悕鍒楄〃 + 璇疯緭鍏ヨ鎵归噺瑙f瀽鐨勫煙鍚?/string> + 璇疯緭鍏ヨ鎵归噺瑙f瀽鐨勫煙鍚?/string> + %s鍩熷悕宸茬粡琚坊鍔犺嚦鎵归噺瑙f瀽鍒楄〃锛岃鍕块噸澶嶆坊鍔?/string> - 域名: - 端口: - TTL时长: + 鍩熷悕锛?/string> + 绔彛锛?/string> + TTL鏃堕暱: - 请输入主站域名 - 添加主站域名 - 主站域名为空 - %s主站域名已经被添加,请勿重复添加 + 璇疯緭鍏ヤ富绔欏煙鍚?/string> + 娣诲姞涓荤珯鍩熷悕 + 涓荤珯鍩熷悕涓虹┖ + %s涓荤珯鍩熷悕宸茬粡琚坊鍔狅紝璇峰嬁閲嶅娣诲姞 - 请输入标签 + 璇疯緭鍏ユ爣绛?/string> - 请输入不使用HttpDns解析的域名 - 添加不使用HttpDns的域名 - 域名为空 - %s域名已经在黑名单中,请勿重复添加 + 璇疯緭鍏ヤ笉浣跨敤HttpDns瑙f瀽鐨勫煙鍚?/string> + 娣诲姞涓嶄娇鐢℉ttpDns鐨勫煙鍚?/string> + 鍩熷悕涓虹┖ + %s鍩熷悕宸茬粡鍦ㄩ粦鍚嶅崟涓紝璇峰嬁閲嶅娣诲姞 - 请输入探测IP的域名 - 请输入探测IP的端口 - 添加IP探测 - 端口号为空 - %s:%s已经被添加至IP探测列表,请勿重复添加 + 璇疯緭鍏ユ帰娴婭P鐨勫煙鍚?/string> + 璇疯緭鍏ユ帰娴婭P鐨勭鍙?/string> + 娣诲姞IP鎺㈡祴 + 绔彛鍙蜂负绌?/string> + %s:%s宸茬粡琚坊鍔犺嚦IP鎺㈡祴鍒楄〃锛岃鍕块噸澶嶆坊鍔?/string> - 域名为空 - 预解析的域名为空 - 批量解析的域名为空 + 鍩熷悕涓虹┖ + 棰勮В鏋愮殑鍩熷悕涓虹┖ + 鎵归噺瑙f瀽鐨勫煙鍚嶄负绌?/string> - 请输入缓存的域名 - 请输入缓存的ttl时间,单位:秒 - 添加自定义TTL - TTL时间为空 - 请输入正确格式的TTL时长 + 璇疯緭鍏ョ紦瀛樼殑鍩熷悕 + 璇疯緭鍏ョ紦瀛樼殑ttl鏃堕棿锛屽崟浣嶏細绉?/string> + 娣诲姞鑷畾涔塗TL + TTL鏃堕棿涓虹┖ + 璇疯緭鍏ユ纭牸寮忕殑TTL鏃堕暱 - 删除 - 清除所有HttpDNS配置缓存 - 所有HttpDNS配置缓存都已清除 - 清空Dns缓存(500次) + 鍒犻櫎 + 娓呴櫎鎵€鏈塇ttpDNS閰嶇疆缂撳瓨 + 鎵€鏈塇ttpDNS閰嶇疆缂撳瓨閮藉凡娓呴櫎 + 娓呯┖Dns缂撳瓨锛?00娆★級 - 自定义解析的参数 - json对象格式 - 自定义解析的参数必须是json对象 + 鑷畾涔夎В鏋愮殑鍙傛暟 + json瀵硅薄鏍煎紡 + 鑷畾涔夎В鏋愮殑鍙傛暟蹇呴』鏄痡son瀵硅薄 - 自定义解析的cache key - Cache key用于唯一标识缓存中的解析结果 + 鑷畾涔夎В鏋愮殑cache key + Cache key鐢ㄤ簬鍞竴鏍囪瘑缂撳瓨涓殑瑙f瀽缁撴灉 - 要解析的域名 - 例如:help.aliyun.com - 要请求的接口 - 例如: /document_detail/434554.html + 瑕佽В鏋愮殑鍩熷悕 + 渚嬪锛歨elp.aliyun.com + 瑕佽姹傜殑鎺ュ彛 + 渚嬪: /document_detail/434554.html - 解析并请求 - 域名不能为空 - 域名不能是IP地址 - 请输入正确格式的域名 - Schema类型 - HttpDNS WebView 拦截GET请求 - HttpDNS WebView POST请求通过Native发送 - HttpDNS IP直连方案 + 瑙f瀽骞惰姹?/string> + 鍩熷悕涓嶈兘涓虹┖ + 鍩熷悕涓嶈兘鏄疘P鍦板潃 + 璇疯緭鍏ユ纭牸寮忕殑鍩熷悕 + Schema绫诲瀷 + HttpDNS WebView 鎷︽埅GET璇锋眰 + HttpDNS WebView POST璇锋眰閫氳繃Native鍙戦€?/string> + HttpDNS IP鐩磋繛鏂规 - 好的 - 请求结果 - Body请通过日志查看,关键字为httpdns - IP直连方案 + 濂界殑 + 璇锋眰缁撴灉 + Body璇烽€氳繃鏃ュ織鏌ョ湅锛屽叧閿瓧涓篽ttpdns + IP鐩磋繛鏂规 - 提示 - 网络未连接,请检查网络 - 请求异常: %s + 鎻愮ず + 缃戠粶鏈繛鎺ワ紝璇锋鏌ョ綉缁?/string> + 璇锋眰寮傚父: %s \ No newline at end of file diff --git a/EdgeHttpDNS/sdk/android/demo/src/test/java/com/alibaba/ams/emas/demo/ExampleUnitTest.kt b/EdgeHttpDNS/sdk/android/demo/src/test/java/com/alibaba/ams/emas/demo/ExampleUnitTest.kt index 89edea5..93ec87c 100644 --- a/EdgeHttpDNS/sdk/android/demo/src/test/java/com/alibaba/ams/emas/demo/ExampleUnitTest.kt +++ b/EdgeHttpDNS/sdk/android/demo/src/test/java/com/alibaba/ams/emas/demo/ExampleUnitTest.kt @@ -14,4 +14,5 @@ class ExampleUnitTest { fun addition_isCorrect() { assertEquals(4, 2 + 2) } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/build.gradle b/EdgeHttpDNS/sdk/android/httpdns-sdk/build.gradle index e8b8b55..2a1397c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/build.gradle +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/build.gradle @@ -102,27 +102,18 @@ ext.getIntlVersion = { version -> } } -afterEvaluate { - publishing { - publications { - mavenReleaseAar(MavenPublication) { - from components.normalRelease - groupId 'com.aliyun.ams' - artifactId 'alicloud-android-httpdns' - version "$project.android.defaultConfig.versionName" - } - mavenIntlReleaseAar(MavenPublication) { - from components.intlRelease - groupId 'com.aliyun.ams' - artifactId 'alicloud-android-httpdns' - version getIntlVersion(project.android.defaultConfig.versionName) - } - } - repositories { - if (project.android.defaultConfig.versionName.endsWith("-local-SNAPSHOT")) { - // only maven local - } else if (project.android.defaultConfig.versionName.endsWith("-SNAPSHOT")) { - +task copyDependencies { + doLast { + def config = configurations.findByName("normalReleaseRuntimeClasspath") + if (config != null) { + config.resolvedConfiguration.resolvedArtifacts.each { artifact -> + def file = artifact.file + if (file.name.contains("alicloud-android")) { + copy { + from file + into 'build/outputs/dependencies' + } + } } } } diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/proguard-rules.pro b/EdgeHttpDNS/sdk/android/httpdns-sdk/proguard-rules.pro index c1def44..2eb779c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/proguard-rules.pro +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/proguard-rules.pro @@ -58,6 +58,8 @@ public ; } +-keep class com.alibaba.sdk.android.httpdns.network.**{*;} + -keep interface com.alibaba.sdk.android.httpdns.HttpDnsSettings$NetworkChecker{*;} -keep interface com.alibaba.sdk.android.httpdns.HttpDnsSettings$NetworkDetector{*;} -keep class com.alibaba.sdk.android.httpdns.utils.CommonUtil{ diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/ApiForTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/ApiForTest.java index 9a6c10f..1e9e777 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/ApiForTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/ApiForTest.java @@ -12,7 +12,7 @@ import java.util.concurrent.ScheduledExecutorService; public interface ApiForTest { /** - * 指定初始服务ip + * 鎸囧畾鍒濆鏈嶅姟ip * @param region * @param ips * @param ports @@ -22,38 +22,38 @@ public interface ApiForTest { void setInitServer(String region, String[] ips, int[] ports, String[] ipv6s, int[] v6Ports); /** - * 指定httpdns使用的线程池 + * 鎸囧畾httpdns浣跨敤鐨勭嚎绋嬫睜 * @param scheduledExecutorService */ void setThread(ScheduledExecutorService scheduledExecutorService); /** - * 指定 测试使用的socket factory + * 鎸囧畾 娴嬭瘯浣跨敤鐨剆ocket factory * @param speedTestSocketFactory */ void setSocketFactory(IPRankingTask.SpeedTestSocketFactory speedTestSocketFactory); /** - * 指定调度接口的调用间歇,避免正常的间歇过长无法测试 + * 鎸囧畾璋冨害鎺ュ彛鐨勮皟鐢ㄩ棿姝囷紝閬垮厤姝e父鐨勯棿姝囪繃闀挎棤娉曟祴璇? * @param timeInterval */ void setUpdateServerTimeInterval(int timeInterval); /** - * 指定 sniff模式的 请求间歇 + * 鎸囧畾 sniff妯″紡鐨?璇锋眰闂存瓏 * @param timeInterval */ void setSniffTimeInterval(int timeInterval); /** - * 获取httpdns的线程池用于控制异常操作 + * 鑾峰彇httpdns鐨勭嚎绋嬫睜鐢ㄤ簬鎺у埗寮傚父鎿嶄綔 * * @return */ ExecutorService getWorker(); /** - * 设置兜底的调度ip + * 璁剧疆鍏滃簳鐨勮皟搴p * * @param defaultServerIps * @param ports @@ -61,7 +61,7 @@ public interface ApiForTest { void setDefaultUpdateServer(String[] defaultServerIps, int[] ports); /** - * 设置ipv6的兜底调度IP + * 璁剧疆ipv6鐨勫厹搴曡皟搴P * * @param defaultServerIps * @param ports @@ -69,9 +69,10 @@ public interface ApiForTest { void setDefaultUpdateServerIpv6(String[] defaultServerIps, int[] ports); /** - * 设置测试用的网络detector + * 璁剧疆娴嬭瘯鐢ㄧ殑缃戠粶detector * * @param networkDetector */ void setNetworkDetector(HttpDnsSettings.NetworkDetector networkDetector); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/BeforeHttpDnsServiceInit.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/BeforeHttpDnsServiceInit.java index 89dfdca..e085b5b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/BeforeHttpDnsServiceInit.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/BeforeHttpDnsServiceInit.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns; /** - * 测试用的初始化接口 + * 娴嬭瘯鐢ㄧ殑鍒濆鍖栨帴鍙? * @author zonglin.nzl * @date 1/14/22 */ @@ -9,3 +9,4 @@ public interface BeforeHttpDnsServiceInit { void beforeInit(HttpDnsService service); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/HttpDns.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/HttpDns.java index 29a5c08..191f108 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/HttpDns.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/HttpDns.java @@ -10,17 +10,17 @@ import com.alibaba.sdk.android.httpdns.network.HttpDnsHttpAdapter; import com.alibaba.sdk.android.httpdns.utils.CommonUtil; /** - * Httpdns实例管理 + * Httpdns瀹炰緥绠$悊 */ public class HttpDns { private static HttpDnsInstanceHolder sHolder = new HttpDnsInstanceHolder(new InstanceCreator()); /** - * 获取HttpDnsService对象 + * 鑾峰彇HttpDnsService瀵硅薄 * - * @param applicationContext 当前APP的Context - * @param accountID HttpDns控制台分配的AccountID + * @param applicationContext 褰撳墠APP鐨凜ontext + * @param accountID HttpDns鎺у埗鍙板垎閰嶇殑AccountID * @return */ public synchronized static HttpDnsService getService(final Context applicationContext, final String accountID) { @@ -28,11 +28,11 @@ public class HttpDns { } /** - * 获取HttpDnsService对象,并启用鉴权功能 + * 鑾峰彇HttpDnsService瀵硅薄锛屽苟鍚敤閴存潈鍔熻兘 * - * @param applicationContext 当前APP的Context - * @param accountID HttpDns控制台分配的AccountID - * @param secretKey 用户鉴权私钥 + * @param applicationContext 褰撳墠APP鐨凜ontext + * @param accountID HttpDns鎺у埗鍙板垎閰嶇殑AccountID + * @param secretKey 鐢ㄦ埛閴存潈绉侀挜 * @return */ public synchronized static HttpDnsService getService(final Context applicationContext, final String accountID, final String secretKey) { @@ -40,9 +40,9 @@ public class HttpDns { } /** - * 获取HttpDnsService对象,初始化时不传入任何参数,靠统一接入服务获取相关参数 + * 鑾峰彇HttpDnsService瀵硅薄锛屽垵濮嬪寲鏃朵笉浼犲叆浠讳綍鍙傛暟锛岄潬缁熶竴鎺ュ叆鏈嶅姟鑾峰彇鐩稿叧鍙傛暟 * - * @param applicationContext 当前APP的Context + * @param applicationContext 褰撳墠APP鐨凜ontext * @return */ public synchronized static HttpDnsService getService(final Context applicationContext) { @@ -50,11 +50,11 @@ public class HttpDns { } /** - * 启用或者禁用httpdns,理论上这个是内部接口,不给外部使用的 - * 但是已经对外暴露,所以保留 + * 鍚敤鎴栬€呯鐢╤ttpdns锛岀悊璁轰笂杩欎釜鏄唴閮ㄦ帴鍙o紝涓嶇粰澶栭儴浣跨敤鐨? + * 浣嗘槸宸茬粡瀵瑰鏆撮湶锛屾墍浠ヤ繚鐣? * * @param enabled - * @deprecated 启用禁用应该调用实例的方法,而不是控制全部实例的方法 + * @deprecated 鍚敤绂佺敤搴旇璋冪敤瀹炰緥鐨勬柟娉曪紝鑰屼笉鏄帶鍒跺叏閮ㄥ疄渚嬬殑鏂规硶 */ @Deprecated public synchronized static void switchDnsService(boolean enabled) { @@ -62,7 +62,7 @@ public class HttpDns { } /** - * 重置httpdns,用于一些模拟应用重启的场景 + * 閲嶇疆httpdns锛岀敤浜庝竴浜涙ā鎷熷簲鐢ㄩ噸鍚殑鍦烘櫙 */ public static void resetInstance() { sHolder = new HttpDnsInstanceHolder(new InstanceCreator()); @@ -83,3 +83,4 @@ public class HttpDns { return new HttpDnsHttpAdapter(service, options); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/InitManager.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/InitManager.java index 9121e39..84f5215 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/InitManager.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/InitManager.java @@ -3,8 +3,8 @@ package com.alibaba.sdk.android.httpdns; import java.util.HashMap; /** - * 增加初始化逻辑的单例 - * 用于在测试用的httpdns实例中增加测试需要的初始化逻辑 + * 澧炲姞鍒濆鍖栭€昏緫鐨勫崟渚? + * 鐢ㄤ簬鍦ㄦ祴璇曠敤鐨刪ttpdns瀹炰緥涓鍔犳祴璇曢渶瑕佺殑鍒濆鍖栭€昏緫 * @author zonglin.nzl * @date 1/14/22 */ @@ -32,3 +32,4 @@ public class InitManager { return initThings.remove(accountId); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceTestImpl.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceTestImpl.java index a8aa73e..91ced47 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceTestImpl.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceTestImpl.java @@ -12,8 +12,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; /** - * 测试时 使用的httpdns 实例 - * 增加了一些用于测试的api和机制 + * 娴嬭瘯鏃?浣跨敤鐨刪ttpdns 瀹炰緥 + * 澧炲姞浜嗕竴浜涚敤浜庢祴璇曠殑api鍜屾満鍒? * @author zonglin.nzl * @date 2020/10/16 */ @@ -25,7 +25,7 @@ public class HttpDnsServiceTestImpl extends HttpDnsServiceImpl implements ApiFor @Override protected void beforeInit() { super.beforeInit(); - // 通过InitManager 在httpdns初始化之前 进行一些测试需要前置工作 + // 閫氳繃InitManager 鍦╤ttpdns鍒濆鍖栦箣鍓?杩涜涓€浜涙祴璇曢渶瑕佸墠缃伐浣? BeforeHttpDnsServiceInit init = InitManager.getInstance().getAndRemove(mHttpDnsConfig.getAccountId()); if (init != null) { @@ -84,3 +84,4 @@ public class HttpDnsServiceTestImpl extends HttpDnsServiceImpl implements ApiFor mHttpDnsConfig.setNetworkDetector(networkDetector); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java index 906cf2d..70e2bc1 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/end2end/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java @@ -5,7 +5,7 @@ import android.content.Context; import com.alibaba.sdk.android.httpdns.HttpDnsService; /** - * 改为使用测试实例 + * 鏀逛负浣跨敤娴嬭瘯瀹炰緥 * @author zonglin.nzl * @date 2020/12/4 */ @@ -15,3 +15,4 @@ public class InstanceCreator implements HttpDnsCreator { return new HttpDnsServiceTestImpl(context.getApplicationContext(), accountId, secretKey); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/HttpDns.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/HttpDns.java index 578f286..5b0154f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/HttpDns.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/HttpDns.java @@ -9,7 +9,7 @@ import com.alibaba.sdk.android.httpdns.utils.CommonUtil; import android.content.Context; /** - * Httpdns实例管理 + * Httpdns瀹炰緥绠$悊 */ public class HttpDns { @@ -17,8 +17,8 @@ public class HttpDns { new InstanceCreator()); /** - * 获取HttpDnsService对象 - * @param accountId HttpDns控制台分配的AccountID + * 鑾峰彇HttpDnsService瀵硅薄 + * @param accountId HttpDns鎺у埗鍙板垎閰嶇殑AccountID * @return */ public synchronized static HttpDnsService getService(final String accountId) { @@ -26,10 +26,10 @@ public class HttpDns { } /** - * 获取HttpDnsService对象 - * 该方法已弃用,建议使用{@link HttpDns#getService(String)}方法 - * @param applicationContext 当前APP的Context - * @param accountID HttpDns控制台分配的AccountID + * 鑾峰彇HttpDnsService瀵硅薄 + * 璇ユ柟娉曞凡寮冪敤锛屽缓璁娇鐢▄@link HttpDns#getService(String)}鏂规硶 + * @param applicationContext 褰撳墠APP鐨凜ontext + * @param accountID HttpDns鎺у埗鍙板垎閰嶇殑AccountID * @return */ @Deprecated @@ -39,11 +39,11 @@ public class HttpDns { } /** - * 获取HttpDnsService对象,并启用鉴权功能 - * 该方法已弃用,建议使用{@link HttpDns#getService(String)}方法 - * @param applicationContext 当前APP的Context - * @param accountID HttpDns控制台分配的AccountID - * @param secretKey 用户鉴权私钥 + * 鑾峰彇HttpDnsService瀵硅薄锛屽苟鍚敤閴存潈鍔熻兘 + * 璇ユ柟娉曞凡寮冪敤锛屽缓璁娇鐢▄@link HttpDns#getService(String)}鏂规硶 + * @param applicationContext 褰撳墠APP鐨凜ontext + * @param accountID HttpDns鎺у埗鍙板垎閰嶇殑AccountID + * @param secretKey 鐢ㄦ埛閴存潈绉侀挜 * @return */ @Deprecated @@ -54,9 +54,9 @@ public class HttpDns { } /** - * 获取HttpDnsService对象,初始化时不传入任何参数,靠统一接入服务获取相关参数 - * 该方法已弃用,建议使用{@link HttpDns#getService(String)}方法 - * @param applicationContext 当前APP的Context + * 鑾峰彇HttpDnsService瀵硅薄锛屽垵濮嬪寲鏃朵笉浼犲叆浠讳綍鍙傛暟锛岄潬缁熶竴鎺ュ叆鏈嶅姟鑾峰彇鐩稿叧鍙傛暟 + * 璇ユ柟娉曞凡寮冪敤锛屽缓璁娇鐢▄@link HttpDns#getService(String)}鏂规硶 + * @param applicationContext 褰撳墠APP鐨凜ontext * @return */ @Deprecated @@ -66,9 +66,9 @@ public class HttpDns { } /** - * 初始化方法,该方法主要是保存{@link InitConfig},不会真正进行初始化。真正初始化是在{@link HttpDns#getService(Context, String, String)}中 - * 这么实现主要是为了兼容{@link InitConfig.Builder#buildFor(String)}方法,新客户使用该方法和旧的方法功能一致 - * @param accountId HttpDns控制台分配的AccountID + * 鍒濆鍖栨柟娉曪紝璇ユ柟娉曚富瑕佹槸淇濆瓨{@link InitConfig}锛屼笉浼氱湡姝h繘琛屽垵濮嬪寲銆傜湡姝e垵濮嬪寲鏄湪{@link HttpDns#getService(Context, String, String)}涓? + * 杩欎箞瀹炵幇涓昏鏄负浜嗗吋瀹箋@link InitConfig.Builder#buildFor(String)}鏂规硶锛屾柊瀹㈡埛浣跨敤璇ユ柟娉曞拰鏃х殑鏂规硶鍔熻兘涓€鑷? + * @param accountId HttpDns鎺у埗鍙板垎閰嶇殑AccountID * @param config {@link InitConfig} */ public static void init(String accountId, InitConfig config) { @@ -90,14 +90,15 @@ public class HttpDns { } /** - * 启用或者禁用httpdns,理论上这个是内部接口,不给外部使用的 - * 但是已经对外暴露,所以保留 + * 鍚敤鎴栬€呯鐢╤ttpdns锛岀悊璁轰笂杩欎釜鏄唴閮ㄦ帴鍙o紝涓嶇粰澶栭儴浣跨敤鐨? + * 浣嗘槸宸茬粡瀵瑰鏆撮湶锛屾墍浠ヤ繚鐣? * * @param enabled - * @deprecated 启用禁用应该调用实例的方法,而不是控制全部实例的方法 + * @deprecated 鍚敤绂佺敤搴旇璋冪敤瀹炰緥鐨勬柟娉曪紝鑰屼笉鏄帶鍒跺叏閮ㄥ疄渚嬬殑鏂规硶 */ @Deprecated public synchronized static void switchDnsService(boolean enabled) { // do nothing as deprecated } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java index e039759..5ff235e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java @@ -10,3 +10,4 @@ public class InstanceCreator implements HttpDnsCreator { return new IntlImpl(context, accountId, secretKey); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/IntlImpl.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/IntlImpl.java index 25c4530..682773e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/IntlImpl.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/intl/java/com/alibaba/sdk/android/httpdns/impl/IntlImpl.java @@ -7,3 +7,4 @@ public class IntlImpl extends HttpDnsServiceImpl { super(context, accountId, secret); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/CacheTtlChanger.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/CacheTtlChanger.java index 12fe9b6..80c037e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/CacheTtlChanger.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/CacheTtlChanger.java @@ -1,18 +1,19 @@ package com.alibaba.sdk.android.httpdns; /** - * 修改ttl时长的接口 - * 用于用户定制ttl,以控制缓存的时长 + * 淇敼ttl鏃堕暱鐨勬帴鍙? + * 鐢ㄤ簬鐢ㄦ埛瀹氬埗ttl锛屼互鎺у埗缂撳瓨鐨勬椂闀? */ public interface CacheTtlChanger { /** - * 根据 域名 ip类型 和 服务的ttl 返回 定制的ttl + * 鏍规嵁 鍩熷悕 ip绫诲瀷 鍜?鏈嶅姟鐨則tl 杩斿洖 瀹氬埗鐨則tl * - * @param host 域名 - * @param type ip类型 - * @param ttl 服务下发的ttl 单位秒 - * @return 定制的ttl 单位秒 + * @param host 鍩熷悕 + * @param type ip绫诲瀷 + * @param ttl 鏈嶅姟涓嬪彂鐨則tl 鍗曚綅绉? + * @return 瀹氬埗鐨則tl 鍗曚綅绉? */ int changeCacheTtl(String host, RequestIpType type, int ttl); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/DegradationFilter.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/DegradationFilter.java index b1382ca..627787d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/DegradationFilter.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/DegradationFilter.java @@ -1,13 +1,14 @@ package com.alibaba.sdk.android.httpdns; /** - * 降级判断开关接口 + * 闄嶇骇鍒ゆ柇寮€鍏虫帴鍙? */ @Deprecated public interface DegradationFilter { /** - * 是否应该不使用httpdns + * 鏄惁搴旇涓嶄娇鐢╤ttpdns * */ boolean shouldDegradeHttpDNS(String hostName); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResult.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResult.java index 3545f4c..60d6620 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResult.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResult.java @@ -9,7 +9,7 @@ import java.util.Arrays; import java.util.List; /** - * sdns的解析结果 + * sdns鐨勮В鏋愮粨鏋? */ public class HTTPDNSResult { String host; @@ -148,3 +148,4 @@ public class HTTPDNSResult { return fromLocalDns; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResultWrapper.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResultWrapper.java index ae2a99f..853e66f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResultWrapper.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HTTPDNSResultWrapper.java @@ -7,7 +7,7 @@ import com.alibaba.sdk.android.httpdns.cache.HostRecord; import java.util.List; /** - * 对解析结果进行封装,用于可观测数据的一些解析数据携带,不对外透出 + * 瀵硅В鏋愮粨鏋滆繘琛屽皝瑁咃紝鐢ㄤ簬鍙娴嬫暟鎹殑涓€浜涜В鏋愭暟鎹惡甯︼紝涓嶅澶栭€忓嚭 */ public class HTTPDNSResultWrapper { private final HTTPDNSResult mHTTPDNSResult; @@ -59,3 +59,4 @@ public class HTTPDNSResultWrapper { return mHTTPDNSResult.toString(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsCallback.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsCallback.java index fc37b05..33fdefb 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsCallback.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsCallback.java @@ -3,3 +3,4 @@ package com.alibaba.sdk.android.httpdns; public interface HttpDnsCallback { void onHttpDnsCompleted(HTTPDNSResult result); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsService.java index cf17a32..684ac6d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsService.java @@ -5,173 +5,173 @@ import java.util.List; import java.util.Map; /** - * HttpDns服务接口 + * HttpDns鏈嶅姟鎺ュ彛 */ public interface HttpDnsService { /** - * 设置预解析域名列表,默认解析ipv4 + * 璁剧疆棰勮В鏋愬煙鍚嶅垪琛紝榛樿瑙f瀽ipv4 * - * @param hostList 预解析的host域名列表 + * @param hostList 棰勮В鏋愮殑host鍩熷悕鍒楄〃 */ void setPreResolveHosts(List hostList); /** - * 设置预解析域名列表和解析的ip类型 + * 璁剧疆棰勮В鏋愬煙鍚嶅垪琛ㄥ拰瑙f瀽鐨刬p绫诲瀷 * - * @param hostList 预解析的host列表 - * @param requestIpType {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) + * @param hostList 棰勮В鏋愮殑host鍒楄〃 + * @param requestIpType {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? */ void setPreResolveHosts(List hostList, RequestIpType requestIpType); /** - * 异步解析接口, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 + * 寮傛瑙f瀽鎺ュ彛, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 * - * @param host 如www.aliyun.com - * @return 返回ip, 如果没得到解析结果, 则返回null - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getIPv4ForHostAsync(String)} + * @param host 濡倃ww.aliyun.com + * @return 杩斿洖ip, 濡傛灉娌″緱鍒拌В鏋愮粨鏋? 鍒欒繑鍥瀗ull + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getIPv4ForHostAsync(String)} */ @Deprecated String getIpByHostAsync(String host); /** - * 异步解析接口,只查询v4地址,首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 + * 寮傛瑙f瀽鎺ュ彛锛屽彧鏌ヨv4鍦板潃锛岄鍏堟煡璇㈢紦瀛? 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 * - * @param host 要解析的host域名 - * @return 返回v4地址 + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @return 杩斿洖v4鍦板潃 */ @Deprecated String getIPv4ForHostAsync(String host); /** - * 异步解析接口, 获取ipv4列表 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4鍒楄〃 * - * @param host 要解析的host域名 - * @return 返回v4地址的String 数组, 如果没得到解析结果, 则String 数组的长度为0 - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getIPv4ListForHostAsync(String)} + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @return 杩斿洖v4鍦板潃鐨凷tring 鏁扮粍, 濡傛灉娌″緱鍒拌В鏋愮粨鏋? 鍒橲tring 鏁扮粍鐨勯暱搴︿负0 + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getIPv4ListForHostAsync(String)} */ @Deprecated String[] getIpsByHostAsync(String host); /** - * 异步解析接口, 获取ipv4列表 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4鍒楄〃 * - * @param host 要解析的host域名 - * @return 返回v4地址列表 + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @return 杩斿洖v4鍦板潃鍒楄〃 */ @Deprecated String[] getIPv4ListForHostAsync(String host); /** - * 异步解析接口,获取单个ipv6, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙栧崟涓猧pv6, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 * - * @param host 要解析的host域名 - * @return 返回v6地址 - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getIPv6ForHostAsync(String)} + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @return 杩斿洖v6鍦板潃 + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getIPv6ForHostAsync(String)} */ @Deprecated String getIPv6ByHostAsync(String host); /** - * 异步解析接口,获取单个ipv6, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙栧崟涓猧pv6, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 * - * @param host 要解析的host域名 - * @return 返回v6地址 + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @return 杩斿洖v6鍦板潃 */ @Deprecated String getIPv6ForHostAsync(String host); /** - * 异步解析接口,获取ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙杋pv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 * - * @param host 要解析的host域名 - * @return 返回v6地址的String 数组, 如果没得到解析结果, 则String 数组的长度为0 - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getIPv6ListForHostASync(String)} + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @return 杩斿洖v6鍦板潃鐨凷tring 鏁扮粍, 濡傛灉娌″緱鍒拌В鏋愮粨鏋? 鍒橲tring 鏁扮粍鐨勯暱搴︿负0 + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getIPv6ListForHostASync(String)} */ @Deprecated String[] getIPv6sByHostAsync(String host); /** - * 异步解析接口,获取ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙杋pv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 * - * @param host 要解析的host域名 - * @return 返回v6地址的String 数组, 如果没得到解析结果, 则String 数组的长度为0 + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @return 杩斿洖v6鍦板潃鐨凷tring 鏁扮粍, 濡傛灉娌″緱鍒拌В鏋愮粨鏋? 鍒橲tring 鏁扮粍鐨勯暱搴︿负0 */ @Deprecated String[] getIPv6ListForHostASync(String host); /** - * 异步解析接口,获取ipv4ipv6列表 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙杋pv4ipv6鍒楄〃 * - * @param host 要解析的host域名 + * @param host 瑕佽В鏋愮殑host鍩熷悕 * @return {@link HTTPDNSResult} - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getHttpDnsResultForHostAsync(String)} + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getHttpDnsResultForHostAsync(String)} */ @Deprecated HTTPDNSResult getAllByHostAsync(String host); /** - * 异步解析接口,获取ipv4 + ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙杋pv4 + ipv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 * - * @param host 要解析的host域名 + * @param host 瑕佽В鏋愮殑host鍩熷悕 * @return {@link HTTPDNSResult} */ @Deprecated HTTPDNSResult getHttpDnsResultForHostAsync(String host); /** - * 异步解析接口,获取ipv4 + ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持 指定解析IP类型 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙杋pv4 + ipv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔 鎸囧畾瑙f瀽IP绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? * @return {@link HTTPDNSResult} - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getHttpDnsResultForHostAsync(String, RequestIpType)} + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getHttpDnsResultForHostAsync(String, RequestIpType)} */ @Deprecated HTTPDNSResult getIpsByHostAsync(String host, RequestIpType type); /** - * 异步解析接口,获取ipv4 + ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持 指定解析IP类型 + * 寮傛瑙f瀽鎺ュ彛锛岃幏鍙杋pv4 + ipv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔 鎸囧畾瑙f瀽IP绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? * @return {@link HTTPDNSResult} */ @Deprecated HTTPDNSResult getHttpDnsResultForHostAsync(String host, RequestIpType type); /*** - * 校正App签名时间 - * @param time time为epoch时间戳,1970年1月1日以来的秒数 + * 鏍℃App绛惧悕鏃堕棿 + * @param time time涓篹poch鏃堕棿鎴筹紝1970骞?鏈?鏃ヤ互鏉ョ殑绉掓暟 */ void setAuthCurrentTime(long time); /** - * 获取会话id + * 鑾峰彇浼氳瘽id * * @return sid */ String getSessionId(); - //以下针对SDNS + //浠ヤ笅閽堝SDNS /** - * 异步解析接口, 获取ipv4 + ipv6 列表,首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持配置sdns参数 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4 + ipv6 鍒楄〃,棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔閰嶇疆sdns鍙傛暟 * - * @param host 要解析的host域名 + * @param host 瑕佽В鏋愮殑host鍩熷悕 * @return {@link HTTPDNSResult} - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getHttpDnsResultForHostAsync(String, Map, String)} + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getHttpDnsResultForHostAsync(String, Map, String)} */ @Deprecated HTTPDNSResult getIpsByHostAsync(String host, Map params, String cacheKey); /** - * 异步解析接口, 获取ipv4 + ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持配置sdns参数 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4 + ipv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔閰嶇疆sdns鍙傛暟 * - * @param host 要解析的host域名 + * @param host 瑕佽В鏋愮殑host鍩熷悕 * @param params * @param cacheKey * @return {@link HTTPDNSResult} @@ -181,16 +181,16 @@ public interface HttpDnsService { String cacheKey); /** - * 异步解析接口, 获取ipv4 + ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持配置sdns参数 - * 支持指定解析类型 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4 + ipv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔閰嶇疆sdns鍙傛暟 + * 鏀寔鎸囧畾瑙f瀽绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? * @param params * @param cacheKey * @return {@link HTTPDNSResult} - * @deprecated 该接口已废弃,后续版本可能会被删除,请使用{@link #getHttpDnsResultForHostAsync(String, RequestIpType, + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細琚垹闄わ紝璇蜂娇鐢▄@link #getHttpDnsResultForHostAsync(String, RequestIpType, * Map, String)} */ @Deprecated @@ -198,14 +198,14 @@ public interface HttpDnsService { String cacheKey); /** - * 异步解析接口, 获取ipv4 + ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持配置sdns参数 - * 支持指定解析类型 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4 + ipv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔閰嶇疆sdns鍙傛暟 + * 鏀寔鎸囧畾瑙f瀽绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) - * @param params 自定义解析参数 - * @param cacheKey 缓存的key + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? + * @param params 鑷畾涔夎В鏋愬弬鏁? + * @param cacheKey 缂撳瓨鐨刱ey * @return {@link HTTPDNSResult} */ @Deprecated @@ -213,103 +213,103 @@ public interface HttpDnsService { String> params, String cacheKey); /** - * 同步解析接口,支持指定解析类型 - * 支持配置sdns参数 - * 需要注意的地方: - * 1. 该方法必须在子线程中执行,如果在主线程中调用该方法,方法内部会自动切换成异步执行 - * 2. 同步接口会阻塞当前子线程,阻塞时长可以通过{@link InitConfig.Builder#setTimeout(int)}设置, - * 不过阻塞时长的上限是5s,如果设置的超时时长超过5s则无效 + * 鍚屾瑙f瀽鎺ュ彛锛屾敮鎸佹寚瀹氳В鏋愮被鍨? + * 鏀寔閰嶇疆sdns鍙傛暟 + * 闇€瑕佹敞鎰忕殑鍦版柟: + * 1. 璇ユ柟娉曞繀椤诲湪瀛愮嚎绋嬩腑鎵ц锛屽鏋滃湪涓荤嚎绋嬩腑璋冪敤璇ユ柟娉曪紝鏂规硶鍐呴儴浼氳嚜鍔ㄥ垏鎹㈡垚寮傛鎵ц + * 2. 鍚屾鎺ュ彛浼氶樆濉炲綋鍓嶅瓙绾跨▼锛岄樆濉炴椂闀垮彲浠ラ€氳繃{@link InitConfig.Builder#setTimeout(int)}璁剧疆锛? + * 涓嶈繃闃诲鏃堕暱鐨勪笂闄愭槸5s锛屽鏋滆缃殑瓒呮椂鏃堕暱瓒呰繃5s鍒欐棤鏁? * - * @param host 要解析的host域名列表 + * @param host 瑕佽В鏋愮殑host鍩熷悕鍒楄〃 * @param type {@link RequestIpType} - * @param params 自定义解析参数 - * @param cacheKey 缓存的key + * @param params 鑷畾涔夎В鏋愬弬鏁? + * @param cacheKey 缂撳瓨鐨刱ey * @return {@link HTTPDNSResult} */ HTTPDNSResult getHttpDnsResultForHostSync(String host, RequestIpType type, Map params, String cacheKey); /** - * 异步解析接口, 获取ipv4 + ipv6列表, 通过回调返回解析结果,首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持配置sdns参数 - * 支持指定解析类型 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4 + ipv6鍒楄〃, 閫氳繃鍥炶皟杩斿洖瑙f瀽缁撴灉锛岄鍏堟煡璇㈢紦瀛? 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔閰嶇疆sdns鍙傛暟 + * 鏀寔鎸囧畾瑙f瀽绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) - * @param params 自定义解析参数 - * @param cacheKey 缓存的key + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? + * @param params 鑷畾涔夎В鏋愬弬鏁? + * @param cacheKey 缂撳瓨鐨刱ey */ void getHttpDnsResultForHostAsync(String host, RequestIpType type, Map params, String cacheKey, HttpDnsCallback callback); /** - * 异步解析接口, 获取ipv4 + ipv6列表, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持配置sdns参数 - * 支持指定解析类型 + * 寮傛瑙f瀽鎺ュ彛, 鑾峰彇ipv4 + ipv6鍒楄〃, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔閰嶇疆sdns鍙傛暟 + * 鏀寔鎸囧畾瑙f瀽绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) - * @param params 自定义解析参数 - * @param cacheKey 缓存的key + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? + * @param params 鑷畾涔夎В鏋愬弬鏁? + * @param cacheKey 缂撳瓨鐨刱ey */ HTTPDNSResult getHttpDnsResultForHostSyncNonBlocking(String host, RequestIpType type, Map params, String cacheKey); - //以上针对SDNS + //浠ヤ笂閽堝SDNS /** - * 设置region,海外节点 - * 国内版默认是中国大陆节点,国际版默认是新加坡节点 + * 璁剧疆region锛屾捣澶栬妭鐐? + * 鍥藉唴鐗堥粯璁ゆ槸涓浗澶ч檰鑺傜偣锛屽浗闄呯増榛樿鏄柊鍔犲潯鑺傜偣 * - * @param region sg(新家坡), hk(中国香港), ""(中国大陆), de(德国), us(美国) + * @param region sg(鏂板鍧?, hk(涓浗棣欐腐), ""(涓浗澶ч檰), de(寰峰浗), us(缇庡浗) */ @Deprecated void setRegion(String region); /** - * 设置region - * 国内版默认是中国大陆节点 + * 璁剧疆region + * 鍥藉唴鐗堥粯璁ゆ槸涓浗澶ч檰鑺傜偣 * * @param region {@link Region} */ void setRegion(Region region); /** - * 立即清除域名端侧内存和本地缓存。 - * 后续调用异步接口,会先返回空,触发域名解析 + * 绔嬪嵆娓呴櫎鍩熷悕绔晶鍐呭瓨鍜屾湰鍦扮紦瀛樸€? + * 鍚庣画璋冪敤寮傛鎺ュ彛锛屼細鍏堣繑鍥炵┖锛岃Е鍙戝煙鍚嶈В鏋? * - * @param hosts host域名列表 + * @param hosts host鍩熷悕鍒楄〃 */ void cleanHostCache(ArrayList hosts); /** - * 同步解析接口,支持指定解析类型 - * 需要注意的地方: - * 1. 该方法必须在子线程中执行,如果在主线程中调用该方法,方法内部会自动切换成异步执行 - * 2. 同步接口会阻塞当前子线程,阻塞时长可以通过{@link InitConfig.Builder#setTimeout(int)}设置, - * 不过阻塞时长的上限是5s,如果设置的超时时长超过5s则无效 + * 鍚屾瑙f瀽鎺ュ彛锛屾敮鎸佹寚瀹氳В鏋愮被鍨? + * 闇€瑕佹敞鎰忕殑鍦版柟: + * 1. 璇ユ柟娉曞繀椤诲湪瀛愮嚎绋嬩腑鎵ц锛屽鏋滃湪涓荤嚎绋嬩腑璋冪敤璇ユ柟娉曪紝鏂规硶鍐呴儴浼氳嚜鍔ㄥ垏鎹㈡垚寮傛鎵ц + * 2. 鍚屾鎺ュ彛浼氶樆濉炲綋鍓嶅瓙绾跨▼锛岄樆濉炴椂闀垮彲浠ラ€氳繃{@link InitConfig.Builder#setTimeout(int)}璁剧疆锛? + * 涓嶈繃闃诲鏃堕暱鐨勪笂闄愭槸5s锛屽鏋滆缃殑瓒呮椂鏃堕暱瓒呰繃5s鍒欐棤鏁? * - * @param host 要解析的host域名列表 + * @param host 瑕佽В鏋愮殑host鍩熷悕鍒楄〃 * @param type {@link RequestIpType} * @return {@link HTTPDNSResult} */ HTTPDNSResult getHttpDnsResultForHostSync(String host, RequestIpType type); /** - * 异步解析接口,根据type获取ip, 通过回调返回解析结果,首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求 - * 支持 指定解析IP类型 + * 寮傛瑙f瀽鎺ュ彛锛屾牴鎹畉ype鑾峰彇ip, 閫氳繃鍥炶皟杩斿洖瑙f瀽缁撴灉锛岄鍏堟煡璇㈢紦瀛? 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰 + * 鏀寔 鎸囧畾瑙f瀽IP绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? */ void getHttpDnsResultForHostAsync(String host, RequestIpType type, HttpDnsCallback callback); /** - * 异步解析接口,根据type获取ip, 首先查询缓存, 若存在则返回结果, 若不存在返回null 并且进行异步域名解析请求(不会通过回调给调用方) - * 支持 指定解析IP类型 + * 寮傛瑙f瀽鎺ュ彛锛屾牴鎹畉ype鑾峰彇ip, 棣栧厛鏌ヨ缂撳瓨, 鑻ュ瓨鍦ㄥ垯杩斿洖缁撴灉, 鑻ヤ笉瀛樺湪杩斿洖null 骞朵笖杩涜寮傛鍩熷悕瑙f瀽璇锋眰锛堜笉浼氶€氳繃鍥炶皟缁欒皟鐢ㄦ柟锛? + * 鏀寔 鎸囧畾瑙f瀽IP绫诲瀷 * - * @param host 要解析的host域名 - * @param type {@link RequestIpType} 网络栈类型,v4,v6,both,auto(根据当前设备所连的网络自动判断网络栈) + * @param host 瑕佽В鏋愮殑host鍩熷悕 + * @param type {@link RequestIpType} 缃戠粶鏍堢被鍨嬶紝v4,v6,both,auto(鏍规嵁褰撳墠璁惧鎵€杩炵殑缃戠粶鑷姩鍒ゆ柇缃戠粶鏍? * @return {@link HTTPDNSResult} */ HTTPDNSResult getHttpDnsResultForHostSyncNonBlocking(String host, RequestIpType type); diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsSettings.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsSettings.java index b523261..a8b05fc 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsSettings.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsSettings.java @@ -32,16 +32,17 @@ public class HttpDnsSettings { } /** - * 需要外部注入的一些网络环境判断 + * 闇€瑕佸閮ㄦ敞鍏ョ殑涓€浜涚綉缁滅幆澧冨垽鏂? */ public interface NetworkChecker { boolean isIpv6Only(); } /** - * 获取网络类型的接口 + * 鑾峰彇缃戠粶绫诲瀷鐨勬帴鍙? */ public interface NetworkDetector { NetType getNetType(Context context); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsV1Client.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsV1Client.java index 5b47c07..f63c674 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsV1Client.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/HttpDnsV1Client.java @@ -1,4 +1,4 @@ -package com.alibaba.sdk.android.httpdns; +package com.alibaba.sdk.android.httpdns; import android.content.Context; import android.text.TextUtils; @@ -69,3 +69,4 @@ public final class HttpDnsV1Client { return HttpDns.buildHttpClientAdapter(service, options); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ILogger.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ILogger.java index db74e04..d236129 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ILogger.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ILogger.java @@ -1,12 +1,13 @@ package com.alibaba.sdk.android.httpdns; /** - * 日志接口 + * 鏃ュ織鎺ュ彛 */ public interface ILogger { /** - * 日志输出 + * 鏃ュ織杈撳嚭 */ void log(String msg); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/InitConfig.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/InitConfig.java index 3dea324..6fa5505 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/InitConfig.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/InitConfig.java @@ -16,9 +16,9 @@ import com.alibaba.sdk.android.httpdns.ranking.IPRankingBean; import com.alibaba.sdk.android.httpdns.utils.Constants; /** - * 初始化配置 - * 之前的初始化方式,每个配置都是单独设置的,有可能造成一些时序上的问题 - * 所以增加统一初始化配置的方法,由内部固定初始化逻辑,避免时序问题 + * 鍒濆鍖栭厤缃? + * 涔嬪墠鐨勫垵濮嬪寲鏂瑰紡锛屾瘡涓厤缃兘鏄崟鐙缃殑锛屾湁鍙兘閫犳垚涓€浜涙椂搴忎笂鐨勯棶棰? + * 鎵€浠ュ鍔犵粺涓€鍒濆鍖栭厤缃殑鏂规硶锛岀敱鍐呴儴鍥哄畾鍒濆鍖栭€昏緫锛岄伩鍏嶆椂搴忛棶棰? */ public class InitConfig { @@ -209,8 +209,8 @@ public class InitConfig { private String secretKey = null; /** - * 设置是否允许返回超过ttl 的ip - * @param enableExpiredIp 是否允许返回超过ttl 的ip + * 璁剧疆鏄惁鍏佽杩斿洖瓒呰繃ttl 鐨刬p + * @param enableExpiredIp 鏄惁鍏佽杩斿洖瓒呰繃ttl 鐨刬p * @return {@link Builder} */ public Builder setEnableExpiredIp(boolean enableExpiredIp) { @@ -219,8 +219,8 @@ public class InitConfig { } /** - * 设置是否允许使用DB缓存,默认不允许 - * @param enableCacheIp 是否允许使用DB缓存 + * 璁剧疆鏄惁鍏佽浣跨敤DB缂撳瓨锛岄粯璁や笉鍏佽 + * @param enableCacheIp 鏄惁鍏佽浣跨敤DB缂撳瓨 * @return {@link Builder} */ public Builder setEnableCacheIp(boolean enableCacheIp) { @@ -238,8 +238,8 @@ public class InitConfig { } /** - * 设置请求超时时间,单位ms,默认为2s - * @param timeoutMillis 超时时间,单位ms + * 璁剧疆璇锋眰瓒呮椂鏃堕棿,鍗曚綅ms,榛樿涓?s + * @param timeoutMillis 瓒呮椂鏃堕棿锛屽崟浣峬s * @return {@link Builder} */ public Builder setTimeoutMillis(int timeoutMillis) { @@ -248,8 +248,8 @@ public class InitConfig { } /** - * 设置请求超时时间,单位ms,默认为2s - * @param timeout 超时时间,单位ms + * 璁剧疆璇锋眰瓒呮椂鏃堕棿,鍗曚綅ms,榛樿涓?s + * @param timeout 瓒呮椂鏃堕棿锛屽崟浣峬s * @return {@link Builder} */ @Deprecated @@ -259,8 +259,8 @@ public class InitConfig { } /** - * 设置开启/关闭降级到Local Dns,在httpdns解析失败或者域名被过滤不走httpdns的时候,开启降级会走local dns解析 - * @param enableDegradation true, 开启 | false, 关闭 + * 璁剧疆寮€鍚?鍏抽棴闄嶇骇鍒癓ocal Dns锛屽湪httpdns瑙f瀽澶辫触鎴栬€呭煙鍚嶈杩囨护涓嶈蛋httpdns鐨勬椂鍊欙紝寮€鍚檷绾т細璧發ocal dns瑙f瀽 + * @param enableDegradation true, 寮€鍚?锝?false, 鍏抽棴 * @return {@link Builder} */ public Builder setEnableDegradationLocalDns(boolean enableDegradation) { @@ -269,8 +269,8 @@ public class InitConfig { } /** - * 设置HTTPDNS域名解析请求类型(HTTP/HTTPS),若不调用该接口,默认为HTTP请求 - * @param enableHttps 是否使用https + * 璁剧疆HTTPDNS鍩熷悕瑙f瀽璇锋眰绫诲瀷(HTTP/HTTPS)锛岃嫢涓嶈皟鐢ㄨ鎺ュ彛锛岄粯璁や负HTTP璇锋眰 + * @param enableHttps 鏄惁浣跨敤https * @return {@link Builder} */ public Builder setEnableHttps(boolean enableHttps) { @@ -279,7 +279,7 @@ public class InitConfig { } /** - * 设置要探测的域名列表,默认只会对ipv4的地址进行ip优选 + * 璁剧疆瑕佹帰娴嬬殑鍩熷悕鍒楄〃,榛樿鍙細瀵筰pv4鐨勫湴鍧€杩涜ip浼橀€? * @param ipRankingList {@link IPRankingBean} * @return {@link Builder} */ @@ -303,9 +303,9 @@ public class InitConfig { } /** - * 配置自定义ttl的逻辑 + * 閰嶇疆鑷畾涔塼tl鐨勯€昏緫 * - * @param cacheTtlChanger 修改ttl的接口 + * @param cacheTtlChanger 淇敼ttl鐨勬帴鍙? */ public Builder configCacheTtlChanger(CacheTtlChanger cacheTtlChanger) { this.cacheTtlChanger = cacheTtlChanger; @@ -313,9 +313,9 @@ public class InitConfig { } /** - * 配置主站域名列表 + * 閰嶇疆涓荤珯鍩熷悕鍒楄〃 * - * @param hostListWithFixedIp 主站域名列表 + * @param hostListWithFixedIp 涓荤珯鍩熷悕鍒楄〃 */ public Builder configHostWithFixedIp(List hostListWithFixedIp) { this.hostListWithFixedIp = hostListWithFixedIp; @@ -323,8 +323,8 @@ public class InitConfig { } /** - * 设置网络切换时是否自动刷新所有域名解析结果,默认自动刷新 - * @param enable 是否允许自动刷新域名解析结果 + * 璁剧疆缃戠粶鍒囨崲鏃舵槸鍚﹁嚜鍔ㄥ埛鏂版墍鏈夊煙鍚嶈В鏋愮粨鏋滐紝榛樿鑷姩鍒锋柊 + * @param enable 鏄惁鍏佽鑷姩鍒锋柊鍩熷悕瑙f瀽缁撴灉 * @return {@link Builder} */ public Builder setPreResolveAfterNetworkChanged(boolean enable) { @@ -333,7 +333,7 @@ public class InitConfig { } /** - * 设置降级策略, 用户可定制规则降级为原生DNS解析方式 + * 璁剧疆闄嶇骇绛栫暐, 鐢ㄦ埛鍙畾鍒惰鍒欓檷绾т负鍘熺敓DNS瑙f瀽鏂瑰紡 * @param filter {@link DegradationFilter} * @return {@link Builder} */ @@ -344,7 +344,7 @@ public class InitConfig { } /** - * 设置不使用HttpDns的策略, 用户可定制规则指定不走httpdns的域名 + * 璁剧疆涓嶄娇鐢℉ttpDns鐨勭瓥鐣? 鐢ㄦ埛鍙畾鍒惰鍒欐寚瀹氫笉璧癶ttpdns鐨勫煙鍚? * @param filter {@link NotUseHttpDnsFilter} * @return {@link Builder} */ @@ -354,8 +354,8 @@ public class InitConfig { } /** - * 是否开启sdk内部的崩溃保护机制,默认是关闭的 - * @param enabled 开启/关闭 + * 鏄惁寮€鍚痵dk鍐呴儴鐨勫穿婧冧繚鎶ゆ満鍒讹紝榛樿鏄叧闂殑 + * @param enabled 寮€鍚?鍏抽棴 * @return {@link Builder} */ public Builder enableCrashDefend(boolean enabled) { @@ -364,8 +364,8 @@ public class InitConfig { } /** - * 设置sdns全局参数(该全局参数不影响异步解析任务,只用于解析接口调用时进行参数合并) - * @param params sdn的全局参数 + * 璁剧疆sdns鍏ㄥ眬鍙傛暟锛堣鍏ㄥ眬鍙傛暟涓嶅奖鍝嶅紓姝ヨВ鏋愪换鍔★紝鍙敤浜庤В鏋愭帴鍙h皟鐢ㄦ椂杩涜鍙傛暟鍚堝苟锛? + * @param params sdn鐨勫叏灞€鍙傛暟 * @return {@link Builder} */ public Builder setSdnsGlobalParams(Map params) { @@ -402,7 +402,7 @@ public class InitConfig { } if (tmpTag.indexOf(tag) != -1) { - //去重 + //鍘婚噸 continue; } @@ -413,7 +413,7 @@ public class InitConfig { } int lastCommaIndex = tmpTag.lastIndexOf(","); - //最后一位逗号要去掉 + //鏈€鍚庝竴浣嶉€楀彿瑕佸幓鎺? if (lastCommaIndex == tmpTag.length() - 1) { tmpTag.deleteCharAt(lastCommaIndex); } @@ -427,8 +427,8 @@ public class InitConfig { } /** - * 设置aes加密密钥 - * @param aesSecretKey 加密密钥 + * 璁剧疆aes鍔犲瘑瀵嗛挜 + * @param aesSecretKey 鍔犲瘑瀵嗛挜 * @return {@link Builder} */ public Builder setAesSecretKey(String aesSecretKey) { @@ -437,24 +437,21 @@ public class InitConfig { } /** - * 设置主服务域名。 - */ + * 璁剧疆涓绘湇鍔″煙鍚嶃€? */ public Builder setPrimaryServiceHost(String host) { this.primaryServiceHost = host; return this; } /** - * 设置备服务域名。 - */ + * 璁剧疆澶囨湇鍔″煙鍚嶃€? */ public Builder setBackupServiceHost(String host) { this.backupServiceHost = host; return this; } /** - * 批量设置服务域名,支持主备两个。 - */ + * 鎵归噺璁剧疆鏈嶅姟鍩熷悕锛屾敮鎸佷富澶囦袱涓€? */ public Builder setServiceHosts(List hosts) { if (hosts != null && hosts.size() > 0) { this.primaryServiceHost = hosts.get(0); @@ -466,16 +463,15 @@ public class InitConfig { } /** - * 设置服务端口,默认 -1 表示使用协议默认端口。 - */ + * 璁剧疆鏈嶅姟绔彛锛岄粯璁?-1 琛ㄧず浣跨敤鍗忚榛樿绔彛銆? */ public Builder setServicePort(int port) { this.servicePort = port; return this; } /** - * 设置context - * @param context 上下文 + * 璁剧疆context + * @param context 涓婁笅鏂? * @return {@link Builder} */ public Builder setContext(Context context) { @@ -490,8 +486,8 @@ public class InitConfig { } /** - * 设置加签密钥 - * @param secretKey 加签密钥 + * 璁剧疆鍔犵瀵嗛挜 + * @param secretKey 鍔犵瀵嗛挜 * @return {@link Builder} */ public Builder setSecretKey(String secretKey) { @@ -510,3 +506,4 @@ public class InitConfig { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NetType.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NetType.java index ab2f6c9..1c47a31 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NetType.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NetType.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns; /** - * 网络类型 + * 缃戠粶绫诲瀷 */ public enum NetType { none, @@ -9,3 +9,4 @@ public enum NetType { v6, both } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NotUseHttpDnsFilter.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NotUseHttpDnsFilter.java index f5e3ddd..79ad80f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NotUseHttpDnsFilter.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/NotUseHttpDnsFilter.java @@ -1,14 +1,15 @@ package com.alibaba.sdk.android.httpdns; /** - * 不使用HttpDns的配置接口 + * 涓嶄娇鐢℉ttpDns鐨勯厤缃帴鍙? */ public interface NotUseHttpDnsFilter { /** - * 是否应该不使用httpdns - * @param hostName 域名 - * @return true 不走httpdns解析 | false 走httpdns解析 + * 鏄惁搴旇涓嶄娇鐢╤ttpdns + * @param hostName 鍩熷悕 + * @return true 涓嶈蛋httpdns瑙f瀽 锝?false 璧癶ttpdns瑙f瀽 * */ boolean notUseHttpDns(String hostName); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/Region.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/Region.java index 4fcaff0..e42092b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/Region.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/Region.java @@ -18,3 +18,4 @@ public enum Region { return region; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/RequestIpType.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/RequestIpType.java index 505dc07..575b40d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/RequestIpType.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/RequestIpType.java @@ -1,17 +1,18 @@ package com.alibaba.sdk.android.httpdns; /** - * 请求的ip类型 + * 璇锋眰鐨刬p绫诲瀷 */ public enum RequestIpType { v4, v6, /** - * 表示 两个都要 + * 琛ㄧず 涓や釜閮借 */ both, /** - * 表示根据网络情况自动判断 + * 琛ㄧず鏍规嵁缃戠粶鎯呭喌鑷姩鍒ゆ柇 */ auto } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/SyncService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/SyncService.java index 08b212c..2b6eaff 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/SyncService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/SyncService.java @@ -2,12 +2,13 @@ package com.alibaba.sdk.android.httpdns; public interface SyncService { /** - * 同步解析接口,必须在子线程中执行,否则没有效果 + * 鍚屾瑙f瀽鎺ュ彛锛屽繀椤诲湪瀛愮嚎绋嬩腑鎵ц锛屽惁鍒欐病鏈夋晥鏋? * - * @deprecated 该接口已废弃,后续版本可能会删除,请使用 + * @deprecated 璇ユ帴鍙e凡搴熷純锛屽悗缁増鏈彲鑳戒細鍒犻櫎锛岃浣跨敤 * {@link HttpDnsService#getHttpDnsResultForHostSync(String, RequestIpType)} */ @Deprecated HTTPDNSResult getByHost(String host, RequestIpType type); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/HostRecord.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/HostRecord.java index 8303a21..21261ed 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/HostRecord.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/HostRecord.java @@ -6,8 +6,8 @@ import com.alibaba.sdk.android.httpdns.RequestIpType; import com.alibaba.sdk.android.httpdns.utils.CommonUtil; /** - * ip解析结果记录 - * 注意计算hash 和 equal实现,没有使用fromDB字段 + * ip瑙f瀽缁撴灉璁板綍 + * 娉ㄦ剰璁$畻hash 鍜?equal瀹炵幇锛屾病鏈変娇鐢╢romDB瀛楁 */ public class HostRecord { private long id = -1; @@ -181,3 +181,4 @@ public class HostRecord { '}'; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelper.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelper.java index bd0a693..8186498 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelper.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelper.java @@ -13,7 +13,7 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** - * 数据库存取操作 + * 鏁版嵁搴撳瓨鍙栨搷浣? */ public class RecordDBHelper extends SQLiteOpenHelper { @@ -42,7 +42,7 @@ public class RecordDBHelper extends SQLiteOpenHelper { static final String COL_CACHE_KEY = "cache_key"; - // 旧版本 用于存储网络标识的字段,由于合规的影响,删除了相关代码,此字段变为固定字段,目前已经没有意义 + // 鏃х増鏈?鐢ㄤ簬瀛樺偍缃戠粶鏍囪瘑鐨勫瓧娈碉紝鐢变簬鍚堣鐨勫奖鍝嶏紝鍒犻櫎浜嗙浉鍏充唬鐮侊紝姝ゅ瓧娈靛彉涓哄浐瀹氬瓧娈碉紝鐩墠宸茬粡娌℃湁鎰忎箟 static final String COL_SP = "sp"; static final String COL_NO_IP_CODE = "no_ip_code"; @@ -93,7 +93,7 @@ public class RecordDBHelper extends SQLiteOpenHelper { } /** - * 从数据库获取全部数据 + * 浠庢暟鎹簱鑾峰彇鍏ㄩ儴鏁版嵁 * * @param region * @return @@ -146,7 +146,7 @@ public class RecordDBHelper extends SQLiteOpenHelper { } /** - * 从数据库删除数据 + * 浠庢暟鎹簱鍒犻櫎鏁版嵁 */ public void delete(List records) { if (records == null || records.isEmpty()) { @@ -177,7 +177,7 @@ public class RecordDBHelper extends SQLiteOpenHelper { } /** - * 更新数据 + * 鏇存柊鏁版嵁 */ public void insertOrUpdate(List records) { synchronized (mLock) { @@ -258,3 +258,4 @@ public class RecordDBHelper extends SQLiteOpenHelper { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ConfigCacheHelper.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ConfigCacheHelper.java index 28e92ae..26c70a2 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ConfigCacheHelper.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ConfigCacheHelper.java @@ -9,7 +9,7 @@ import android.content.Context; import android.content.SharedPreferences; /** - * 辅助配置的缓存写入和读取 + * 杈呭姪閰嶇疆鐨勭紦瀛樺啓鍏ュ拰璇诲彇 */ public class ConfigCacheHelper { @@ -58,8 +58,9 @@ public class ConfigCacheHelper { for (SpCacheItem item : items) { item.saveToCache(editor); } - // 虽然提示建议使用apply,但是实践证明,apply是把写文件操作推迟到了一些界面切换等时机,反而影响了UI线程。不如直接在子线程写文件 + // 铏界劧鎻愮ず寤鸿浣跨敤apply锛屼絾鏄疄璺佃瘉鏄庯紝apply鏄妸鍐欐枃浠舵搷浣滄帹杩熷埌浜嗕竴浜涚晫闈㈠垏鎹㈢瓑鏃舵満锛屽弽鑰屽奖鍝嶄簡UI绾跨▼銆備笉濡傜洿鎺ュ湪瀛愮嚎绋嬪啓鏂囦欢 editor.commit(); } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/RegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/RegionServer.java index 4f953d5..b0d12bd 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/RegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/RegionServer.java @@ -6,14 +6,14 @@ import java.util.Arrays; public class RegionServer { /** - * HttpDns的服务IP + * HttpDns鐨勬湇鍔P */ private String[] mServerIps; /** - * HttpDns的服务端口,线上都是默认端口 80 或者 443 - * 此处是为了测试场景指定端口 - * 下标和{@link #mServerIps} 对应 - * 如果为null 表示没有指定端口 + * HttpDns鐨勬湇鍔$鍙o紝绾夸笂閮芥槸榛樿绔彛 80 鎴栬€?443 + * 姝ゅ鏄负浜嗘祴璇曞満鏅寚瀹氱鍙? + * 涓嬫爣鍜寋@link #mServerIps} 瀵瑰簲 + * 濡傛灉涓簄ull 琛ㄧず娌℃湁鎸囧畾绔彛 */ private int[] mPorts; private String mRegion; @@ -115,3 +115,4 @@ public class RegionServer { return true; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ServerConfig.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ServerConfig.java index 9c58b6e..e4e6e2b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ServerConfig.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/ServerConfig.java @@ -11,8 +11,8 @@ import android.content.SharedPreferences; import android.text.TextUtils; /** - * 服务节点配置 - * 维护 服务节点的一些状态 + * 鏈嶅姟鑺傜偣閰嶇疆 + * 缁存姢 鏈嶅姟鑺傜偣鐨勪竴浜涚姸鎬? */ public class ServerConfig extends RegionServer implements SpCacheItem { @@ -30,7 +30,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 获取当前使用的服务IP + * 鑾峰彇褰撳墠浣跨敤鐨勬湇鍔P */ public String getServerIp() { final String[] serverIps = getServerIps(); @@ -42,7 +42,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 获取当前使用的服务IP ipv6 + * 鑾峰彇褰撳墠浣跨敤鐨勬湇鍔P ipv6 */ public String getServerIpForV6() { final String[] serverIps = getIpv6ServerIps(); @@ -54,7 +54,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 获取当前使用的服务端口 + * 鑾峰彇褰撳墠浣跨敤鐨勬湇鍔$鍙? */ public int getPort() { final int[] ports = getPorts(); @@ -65,7 +65,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 获取当前使用的服务端口 + * 鑾峰彇褰撳墠浣跨敤鐨勬湇鍔$鍙? */ public int getPortForV6() { final int[] ports = getIpv6Ports(); @@ -77,16 +77,16 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 是否应该更新服务IP + * 鏄惁搴旇鏇存柊鏈嶅姟IP */ public boolean shouldUpdateServerIp() { return System.currentTimeMillis() - mServerIpsLastUpdatedTime >= 24 * 60 * 60 * 1000; } /** - * 设置服务IP + * 璁剧疆鏈嶅姟IP * - * @return false 表示 前后服务一直,没有更新 + * @return false 琛ㄧず 鍓嶅悗鏈嶅姟涓€鐩达紝娌℃湁鏇存柊 */ public synchronized boolean setServerIps(String region, String[] serverIps, int[] ports, String[] serverV6Ips, int[] v6Ports) { @@ -115,9 +115,9 @@ public class ServerConfig extends RegionServer implements SpCacheItem { || !CommonUtil.isSameServer(serverV6Ips, v6Ports, mHttpDnsConfig.getInitServer().getIpv6ServerIps(), mHttpDnsConfig.getInitServer().getIpv6Ports())) { - // 非初始化IP,才认为是真正的更新了服务IP + // 闈炲垵濮嬪寲IP锛屾墠璁や负鏄湡姝g殑鏇存柊浜嗘湇鍔P this.mServerIpsLastUpdatedTime = System.currentTimeMillis(); - // 非初始IP才有缓存的必要 + // 闈炲垵濮婭P鎵嶆湁缂撳瓨鐨勫繀瑕? mHttpDnsConfig.saveToCache(); } return changed || v6changed; @@ -128,9 +128,9 @@ public class ServerConfig extends RegionServer implements SpCacheItem { int[] serverPorts = getPorts(); String region = getRegion(); - //对比和当前的region server是否是同一批,避免测速完已经被更新 + //瀵规瘮鍜屽綋鍓嶇殑region server鏄惁鏄悓涓€鎵癸紝閬垮厤娴嬮€熷畬宸茬粡琚洿鏂? if (serverIps.length != sortedIps.length) { - //ip数量不一致,数据已经被更新 + //ip鏁伴噺涓嶄竴鑷达紝鏁版嵁宸茬粡琚洿鏂? if (HttpDnsLog.isPrint()) { HttpDnsLog.d("abort rank server ip count changed, current ips: " + Arrays.toString(serverIps) + ", sorted ips: " + Arrays.toString(sortedIps)); @@ -139,7 +139,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } boolean contain; - //如果排序的ip都在当前Server ip列表中,认为是一批服务ip,ip和端口需要一起判断 + //濡傛灉鎺掑簭鐨刬p閮藉湪褰撳墠Server ip鍒楄〃涓紝璁や负鏄竴鎵规湇鍔p锛宨p鍜岀鍙i渶瑕佷竴璧峰垽鏂? for (int i = 0; i != sortedIps.length; ++i) { contain = isContainServiceIp(serverIps, serverPorts, sortedIps[i], ports == null ? -1 : ports[i]); if (!contain) { @@ -159,7 +159,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { HttpDnsLog.d("update ranked server ips: " + Arrays.toString(sortedIps) + ", ports: " + Arrays.toString(ports)); } - //仅更新内存 + //浠呮洿鏂板唴瀛? boolean changed = updateRegionAndIpv4(region, sortedIps, ports); if (changed) { this.mLastOkServerIndex = 0; @@ -168,13 +168,13 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } public synchronized void updateServerIpv6sRank(String[] sortedIps, int[] ports) { - //和当前ip进行对比,看看是不是已经被更新了,如果被更新了那此次排序结果不使用 + //鍜屽綋鍓峣p杩涜瀵规瘮锛岀湅鐪嬫槸涓嶆槸宸茬粡琚洿鏂颁簡锛屽鏋滆鏇存柊浜嗛偅姝ゆ鎺掑簭缁撴灉涓嶄娇鐢? String[] serverIps = getIpv6ServerIps(); int[] serverPorts = getIpv6Ports(); - //对比和当前的region server是否是同一批,避免测速完已经被更新 + //瀵规瘮鍜屽綋鍓嶇殑region server鏄惁鏄悓涓€鎵癸紝閬垮厤娴嬮€熷畬宸茬粡琚洿鏂? if (serverIps.length != sortedIps.length) { - //ip数量不一致,数据已经被更新 + //ip鏁伴噺涓嶄竴鑷达紝鏁版嵁宸茬粡琚洿鏂? if (HttpDnsLog.isPrint()) { HttpDnsLog.d("abort rank server ip count changed, current ipv6s: " + Arrays.toString(serverIps) + ", sorted ipv6s: " + Arrays.toString(sortedIps)); @@ -183,7 +183,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } boolean contain; - //如果排序的ip都在当前Server ip列表中,认为是一批服务ip + //濡傛灉鎺掑簭鐨刬p閮藉湪褰撳墠Server ip鍒楄〃涓紝璁や负鏄竴鎵规湇鍔p for (int i = 0; i != sortedIps.length; ++i) { contain = isContainServiceIp(serverIps, serverPorts, sortedIps[i], ports == null ? -1 : ports[i]); if (!contain) { @@ -204,7 +204,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { + ", ports: " + Arrays.toString(ports)); } - //仅更新内存 + //浠呮洿鏂板唴瀛? boolean v6changed = updateIpv6(sortedIps, ports); if (v6changed) { mLastOkServerIndexForV6 = 0; @@ -239,11 +239,11 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 切换域名解析服务 + * 鍒囨崲鍩熷悕瑙f瀽鏈嶅姟 * - * @param ip 请求失败的服务IP - * @param port 请求失败的服务端口 - * @return 是否切换回了最开始的服务。当请求切换的ip和port不是当前ip和port时,说明这个切换请求是无效的,不切换,返回false 认为没有切换回最开始的ip + * @param ip 璇锋眰澶辫触鐨勬湇鍔P + * @param port 璇锋眰澶辫触鐨勬湇鍔$鍙? + * @return 鏄惁鍒囨崲鍥炰簡鏈€寮€濮嬬殑鏈嶅姟銆傚綋璇锋眰鍒囨崲鐨刬p鍜宲ort涓嶆槸褰撳墠ip鍜宲ort鏃讹紝璇存槑杩欎釜鍒囨崲璇锋眰鏄棤鏁堢殑锛屼笉鍒囨崲锛岃繑鍥瀎alse 璁や负娌℃湁鍒囨崲鍥炴渶寮€濮嬬殑ip */ public boolean shiftServer(String ip, int port) { return shiftServerV4(ip, port); @@ -284,9 +284,9 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 标记当前好用的域名解析服务 + * 鏍囪褰撳墠濂界敤鐨勫煙鍚嶈В鏋愭湇鍔? * - * @return 标记成功与否 + * @return 鏍囪鎴愬姛涓庡惁 */ public boolean markOkServer(String serverIp, int port) { final String[] serverIps = getServerIps(); @@ -306,9 +306,9 @@ public class ServerConfig extends RegionServer implements SpCacheItem { } /** - * 标记当前好用的域名解析服务 + * 鏍囪褰撳墠濂界敤鐨勫煙鍚嶈В鏋愭湇鍔? * - * @return 标记成功与否 + * @return 鏍囪鎴愬姛涓庡惁 */ public boolean markOkServerV6(String serverIp, int port) { final String[] serverIps = getIpv6ServerIps(); @@ -353,7 +353,7 @@ public class ServerConfig extends RegionServer implements SpCacheItem { public void restoreFromCache(SharedPreferences sp) { String cachedServerRegion = sp.getString(Constants.CONFIG_CURRENT_SERVER_REGION, getRegion()); - //初始化region和缓存server region一致的情况,使用缓存的服务IP。否则初始化的region优先级更高 + //鍒濆鍖杛egion鍜岀紦瀛榮erver region涓€鑷寸殑鎯呭喌锛屼娇鐢ㄧ紦瀛樼殑鏈嶅姟IP銆傚惁鍒欏垵濮嬪寲鐨剅egion浼樺厛绾ф洿楂? if (CommonUtil.regionEquals(cachedServerRegion, getRegion())) { if (HttpDnsLog.isPrint()) { HttpDnsLog.d("restore service ip of " + (TextUtils.isEmpty(cachedServerRegion) ? "default" : cachedServerRegion)); @@ -390,3 +390,4 @@ public class ServerConfig extends RegionServer implements SpCacheItem { editor.putString(Constants.CONFIG_CURRENT_SERVER_REGION, getRegion()); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/SpCacheItem.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/SpCacheItem.java index 9c50b0f..e6af818 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/SpCacheItem.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/SpCacheItem.java @@ -7,3 +7,4 @@ public interface SpCacheItem { void saveToCache(SharedPreferences.Editor editor); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/AmericaRegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/AmericaRegionServer.java index 3ae220f..92c9739 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/AmericaRegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/AmericaRegionServer.java @@ -16,10 +16,10 @@ public class AmericaRegionServer { private static final int[] IPV6_PORTS = null; private static final String[] UPDATE_SERVER = new String[] { - "resolvers-us.httpdns.aliyuncs.com" + "resolvers-us.httpdns.Aliyuncs.com" }; private static final String[] IPV6_UPDATE_SERVER = new String[] { - "resolvers-us.httpdns.aliyuncs.com" + "resolvers-us.httpdns.Aliyuncs.com" }; public static RegionServer getInitServer() { @@ -30,3 +30,4 @@ public class AmericaRegionServer { return new RegionServer(UPDATE_SERVER, Constants.NO_PORTS, IPV6_UPDATE_SERVER, Constants.NO_PORTS, Constants.REGION_US); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/DefaultRegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/DefaultRegionServer.java index fa0ef34..6d8f9da 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/DefaultRegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/DefaultRegionServer.java @@ -22,10 +22,10 @@ public final class DefaultRegionServer { private static final int[] IPV6_PORTS = null; private static final String[] UPDATE_SERVER = new String[] { - "resolvers-cn.httpdns.aliyuncs.com" + "resolvers-cn.httpdns.Aliyuncs.com" }; private static final String[] IPV6_UPDATE_SERVER = new String[] { - "resolvers-cn.httpdns.aliyuncs.com" + "resolvers-cn.httpdns.Aliyuncs.com" }; public static RegionServer getInitServer() { @@ -36,3 +36,4 @@ public final class DefaultRegionServer { return new RegionServer(UPDATE_SERVER, Constants.NO_PORTS, IPV6_UPDATE_SERVER, Constants.NO_PORTS, Constants.REGION_DEFAULT); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/GermanyRegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/GermanyRegionServer.java index 581ac92..0eb87c7 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/GermanyRegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/GermanyRegionServer.java @@ -17,10 +17,10 @@ public class GermanyRegionServer { private static final int[] IPV6_PORTS = null; private static final String[] UPDATE_SERVER = new String[] { - "resolvers-de.httpdns.aliyuncs.com" + "resolvers-de.httpdns.Aliyuncs.com" }; private static final String[] IPV6_UPDATE_SERVER = new String[] { - "resolvers-de.httpdns.aliyuncs.com" + "resolvers-de.httpdns.Aliyuncs.com" }; public static RegionServer getInitServer() { @@ -31,3 +31,4 @@ public class GermanyRegionServer { return new RegionServer(UPDATE_SERVER, Constants.NO_PORTS, IPV6_UPDATE_SERVER, Constants.NO_PORTS, Constants.REGION_DE); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/HongKongRegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/HongKongRegionServer.java index d8900c5..821df39 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/HongKongRegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/HongKongRegionServer.java @@ -16,10 +16,10 @@ public class HongKongRegionServer { private static final int[] IPV6_PORTS = null; private static final String[] UPDATE_SERVER = new String[] { - "resolvers-hk.httpdns.aliyuncs.com" + "resolvers-hk.httpdns.Aliyuncs.com" }; private static final String[] IPV6_UPDATE_SERVER = new String[] { - "resolvers-hk.httpdns.aliyuncs.com" + "resolvers-hk.httpdns.Aliyuncs.com" }; public static RegionServer getInitServer() { @@ -30,3 +30,4 @@ public class HongKongRegionServer { return new RegionServer(UPDATE_SERVER, Constants.NO_PORTS, IPV6_UPDATE_SERVER, Constants.NO_PORTS, Constants.REGION_HK); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/PreReleaseRegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/PreReleaseRegionServer.java index 4e972e6..427cfd0 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/PreReleaseRegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/PreReleaseRegionServer.java @@ -9,15 +9,15 @@ public class PreReleaseRegionServer { }; private static final int[] PORTS = null; private static final String[] IPV6_SERVER_IPS = new String [] { - "resolvers-cn-pre.httpdns.aliyuncs.com" + "resolvers-cn-pre.httpdns.Aliyuncs.com" }; private static final int[] IPV6_PORTS = null; private static final String[] UPDATE_SERVER = new String[] { - "resolvers-cn-pre.httpdns.aliyuncs.com" + "resolvers-cn-pre.httpdns.Aliyuncs.com" }; private static final String[] IPV6_UPDATE_SERVER = new String[] { - "resolvers-cn-pre.httpdns.aliyuncs.com" + "resolvers-cn-pre.httpdns.Aliyuncs.com" }; public static RegionServer getInitServer() { @@ -28,3 +28,4 @@ public class PreReleaseRegionServer { return new RegionServer(UPDATE_SERVER, Constants.NO_PORTS, IPV6_UPDATE_SERVER, Constants.NO_PORTS, Constants.REGION_DEBUG_PRE); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/RegionServerManager.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/RegionServerManager.java index f61706b..22b8c60 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/RegionServerManager.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/RegionServerManager.java @@ -74,3 +74,4 @@ public class RegionServerManager { return regionServer; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/SingaporeRegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/SingaporeRegionServer.java index a4e3742..b6b4fd2 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/SingaporeRegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/config/region/SingaporeRegionServer.java @@ -16,10 +16,10 @@ public class SingaporeRegionServer { private static final int[] IPV6_PORTS = null; private static final String[] UPDATE_SERVER = new String[] { - "resolvers-sg.httpdns.aliyuncs.com" + "resolvers-sg.httpdns.Aliyuncs.com" }; private static final String[] IPV6_UPDATE_SERVER = new String[] { - "resolvers-sg.httpdns.aliyuncs.com" + "resolvers-sg.httpdns.Aliyuncs.com" }; public static RegionServer getInitServer() { @@ -30,3 +30,4 @@ public class SingaporeRegionServer { return new RegionServer(UPDATE_SERVER, Constants.NO_PORTS, IPV6_UPDATE_SERVER, Constants.NO_PORTS, Constants.REGION_SG); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/HttpDnsUncaughtExceptionHandler.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/HttpDnsUncaughtExceptionHandler.java index 8beff9c..b5f98c8 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/HttpDnsUncaughtExceptionHandler.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/HttpDnsUncaughtExceptionHandler.java @@ -3,7 +3,7 @@ package com.alibaba.sdk.android.httpdns.exception; import com.alibaba.sdk.android.httpdns.log.HttpDnsLog; public class HttpDnsUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { - // 处理所有未捕获异常 + // 澶勭悊鎵€鏈夋湭鎹曡幏寮傚父 public void uncaughtException(Thread thread, Throwable ex) { try { HttpDnsLog.e("Catch an uncaught exception, " + thread.getName() + ", error message: " @@ -19,3 +19,4 @@ public class HttpDnsUncaughtExceptionHandler implements Thread.UncaughtException } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/InitException.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/InitException.java index 20b3622..6e61e1a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/InitException.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/exception/InitException.java @@ -6,3 +6,4 @@ public class InitException extends RuntimeException { super(msg); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptService.java index 8fb1ae8..23ae185 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptService.java @@ -161,3 +161,4 @@ public class AESEncryptService { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/ErrorImpl.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/ErrorImpl.java index e9272e8..e57357a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/ErrorImpl.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/ErrorImpl.java @@ -176,3 +176,4 @@ public class ErrorImpl implements HttpDnsService, SyncService { return Constants.EMPTY; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveLocker.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveLocker.java index ffd67ae..25c1e50 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveLocker.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveLocker.java @@ -22,12 +22,12 @@ public class HostResolveLocker { if (type == RequestIpType.both) { if (mBothResolvingHost.contains(host)) { - // 正在解析 + // 姝e湪瑙f瀽 return false; } else { synchronized (mLock) { if (mBothResolvingHost.contains(host)) { - // 正在解析 + // 姝e湪瑙f瀽 return false; } else { mBothResolvingHost.add(host); @@ -159,3 +159,4 @@ public class HostResolveLocker { return recorder.await(host, type, timeout, unit); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorder.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorder.java index 3d830fe..5818a17 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorder.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorder.java @@ -17,13 +17,13 @@ public class HostResolveRecorder { if (type == RequestIpType.both) { if (mBothResolvingHost.contains(host) || (mV4ResolvingHost.contains(host) && mV6ResolvingHost.contains(host))) { - // 正在解析 + // 姝e湪瑙f瀽 return false; } else { synchronized (mLock) { if (mBothResolvingHost.contains(host) || (mV4ResolvingHost.contains(host) && mV6ResolvingHost.contains(host))) { - // 正在解析 + // 姝e湪瑙f瀽 return false; } else { mBothResolvingHost.add(host); @@ -117,3 +117,4 @@ public class HostResolveRecorder { recorder.endResolve(host, type); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfig.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfig.java index b980b5d..737938c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfig.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfig.java @@ -25,62 +25,62 @@ import android.content.pm.PackageManager; import android.os.Build; /** - * httpdns的配置 + * httpdns鐨勯厤缃? */ public class HttpDnsConfig implements SpCacheItem { private final Context mContext; private boolean mEnabled = Constants.DEFAULT_SDK_ENABLE; /** - * 初始服务节点 + * 鍒濆鏈嶅姟鑺傜偣 */ private RegionServer mInitServer; /** - * 兜底的调度服务IP,用于应对国际版服务IP有可能不稳定的情况 + * 鍏滃簳鐨勮皟搴︽湇鍔P锛岀敤浜庡簲瀵瑰浗闄呯増鏈嶅姟IP鏈夊彲鑳戒笉绋冲畾鐨勬儏鍐? */ private RegionServer mDefaultUpdateServer; /** - * 当前服务节点 + * 褰撳墠鏈嶅姟鑺傜偣 */ private final ServerConfig mCurrentServer; /** - * 用户的accountId + * 鐢ㄦ埛鐨刟ccountId */ private final String mAccountId; /** - * 当前请求使用的schema + * 褰撳墠璇锋眰浣跨敤鐨剆chema */ private String mSchema = Constants.DEFAULT_SCHEMA; /** - * 当前region + * 褰撳墠region */ private String mRegion; /** - * 超时时长 + * 瓒呮椂鏃堕暱 */ private int mTimeout = Constants.DEFAULT_TIMEOUT; /** - * 是否禁用服务,以避免崩溃 + * 鏄惁绂佺敤鏈嶅姟锛屼互閬垮厤宕╂簝 */ private boolean mHitCrashDefend; /** - * 是否远程禁用服务 + * 鏄惁杩滅▼绂佺敤鏈嶅姟 */ private boolean mRemoteDisabled = false; /** - * 是否禁用probe能力 + * 鏄惁绂佺敤probe鑳藉姏 */ private boolean mIPRankingDisabled = false; /** - * 是否开启降级到Local Dns + * 鏄惁寮€鍚檷绾у埌Local Dns */ private boolean mEnableDegradationLocalDns = Constants.DEFAULT_ENABLE_DEGRADATION_LOCAL_DNS; /** - * 网络探测接口 + * 缃戠粶鎺㈡祴鎺ュ彛 */ private HttpDnsSettings.NetworkDetector mNetworkDetector = null; @@ -102,14 +102,14 @@ public class HttpDnsConfig implements SpCacheItem { mUA = buildUA(); } - //region提前设置 + //region鎻愬墠璁剧疆 mRegion = getInitRegion(accountId); mInitServer = RegionServerManager.getInitServer(mRegion); mDefaultUpdateServer = RegionServerManager.getUpdateServer(mRegion); mCurrentServer = new ServerConfig(this, mInitServer.getServerIps(), mInitServer.getPorts(), mInitServer.getIpv6ServerIps(), mInitServer.getIpv6Ports()); mObservableConfig = new ObservableConfig(); - // 先从缓存读取数据,再赋值cacheHelper, 避免在读取缓存过程中,触发写缓存操作 + // 鍏堜粠缂撳瓨璇诲彇鏁版嵁锛屽啀璧嬪€糲acheHelper锛?閬垮厤鍦ㄨ鍙栫紦瀛樿繃绋嬩腑锛岃Е鍙戝啓缂撳瓨鎿嶄綔 ConfigCacheHelper helper = new ConfigCacheHelper(); if (context != null) { helper.restoreFromCache(context, this); @@ -167,9 +167,9 @@ public class HttpDnsConfig implements SpCacheItem { } /** - * 是否启用httpdns + * 鏄惁鍚敤httpdns *

- * 注意是 永久禁用,因为缓存的原因,一旦禁用,就没有机会启用了 + * 娉ㄦ剰鏄?姘镐箙绂佺敤锛屽洜涓虹紦瀛樼殑鍘熷洜锛屼竴鏃︾鐢紝灏辨病鏈夋満浼氬惎鐢ㄤ簡 */ public void setEnabled(boolean enabled) { if (this.mEnabled != enabled) { @@ -214,16 +214,16 @@ public class HttpDnsConfig implements SpCacheItem { } public void setWorker(ExecutorService worker) { - // 给测试使用 + // 缁欐祴璇曚娇鐢? this.mWorker = worker; this.mDbWorker = worker; mResolveWorker = worker; } /** - * 切换https + * 鍒囨崲https * - * @return 配置是否变化 + * @return 閰嶇疆鏄惁鍙樺寲 */ public boolean setHTTPSRequestEnabled(boolean enabled) { String oldSchema = mSchema; @@ -247,7 +247,7 @@ public class HttpDnsConfig implements SpCacheItem { } /** - * 设置用户切换的region + * 璁剧疆鐢ㄦ埛鍒囨崲鐨剅egion */ public boolean setRegion(String region) { if (!mRegion.equals(region)) { @@ -261,7 +261,7 @@ public class HttpDnsConfig implements SpCacheItem { } /** - * 获取ipv6的服务节点 + * 鑾峰彇ipv6鐨勬湇鍔¤妭鐐? */ public String[] getIpv6ServerIps() { return this.mCurrentServer.getIpv6ServerIps(); @@ -316,10 +316,10 @@ public class HttpDnsConfig implements SpCacheItem { } /** - * 设置初始服务IP + * 璁剧疆鍒濆鏈嶅姟IP *

- * 线上SDK 初始化服务IP是内置写死的。 - * 本API主要用于一些测试代码使用 + * 绾夸笂SDK 鍒濆鍖栨湇鍔P鏄唴缃啓姝荤殑銆? + * 鏈珹PI涓昏鐢ㄤ簬涓€浜涙祴璇曚唬鐮佷娇鐢? * */ public void setInitServers(String initRegion, String[] initIps, int[] initPorts, @@ -344,8 +344,8 @@ public class HttpDnsConfig implements SpCacheItem { } /** - * 设置兜底的调度IP, - * 测试代码使用 + * 璁剧疆鍏滃簳鐨勮皟搴P锛? + * 娴嬭瘯浠g爜浣跨敤 */ public void setDefaultUpdateServer(String[] ips, int[] ports) { this.mDefaultUpdateServer.updateRegionAndIpv4(this.mInitServer.getRegion(), ips, ports); @@ -379,7 +379,7 @@ public class HttpDnsConfig implements SpCacheItem { this.mNetworkDetector = networkDetector; } - // 缓存相关的 处理,暂时放这里 + // 缂撳瓨鐩稿叧鐨?澶勭悊锛屾殏鏃舵斁杩欓噷 public void saveToCache() { if (mCacheHelper != null && mContext != null) { @@ -429,3 +429,4 @@ public class HttpDnsConfig implements SpCacheItem { + ";" + "HTTPDNS" + "/" + BuildConfig.VERSION_NAME; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsCreator.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsCreator.java index 1bb357a..cfff42c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsCreator.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsCreator.java @@ -5,8 +5,9 @@ import android.content.Context; import com.alibaba.sdk.android.httpdns.HttpDnsService; /** - * httpdns服务创建接口 + * httpdns鏈嶅姟鍒涘缓鎺ュ彛 */ public interface HttpDnsCreator { HttpDnsService create(Context context, String accountId, String secretKey); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolder.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolder.java index 24c65d2..6cff181 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolder.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolder.java @@ -8,7 +8,7 @@ import com.alibaba.sdk.android.httpdns.log.HttpDnsLog; import java.util.HashMap; /** - * HttpDnsService 实例持有者 + * HttpDnsService 瀹炰緥鎸佹湁鑰? */ public class HttpDnsInstanceHolder { @@ -40,3 +40,4 @@ public class HttpDnsInstanceHolder { return service; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceImpl.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceImpl.java index efc05ec..fc37467 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceImpl.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsServiceImpl.java @@ -45,7 +45,7 @@ import android.os.Looper; import android.text.TextUtils; /** - * 域名解析服务 httpdns接口的实现 + * 鍩熷悕瑙f瀽鏈嶅姟 httpdns鎺ュ彛鐨勫疄鐜? */ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdate, NetworkStateManager.OnNetworkChange, SyncService { @@ -64,7 +64,7 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat private boolean resolveAfterNetworkChange = true; private boolean mUseCustomServiceHosts = false; /** - * crash defend 默认关闭 + * crash defend 榛樿鍏抽棴 */ private boolean mCrashDefendEnabled = false; public static Context sContext; @@ -135,21 +135,21 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat InitConfig config = InitConfig.getInitConfig(accountId); if (config != null) { - // 先设置和网络相关的内容 + // 鍏堣缃拰缃戠粶鐩稿叧鐨勫唴瀹? this.mHttpDnsConfig.setTimeout(config.getTimeout()); this.mHttpDnsConfig.setHTTPSRequestEnabled(config.isEnableHttps()); mHttpDnsConfig.setBizTags(config.getBizTags()); mHttpDnsConfig.setEnableDegradationLocalDns(config.isEnableDegradationLocalDns()); - // 再设置一些可以提前,没有副作用的内容 + // 鍐嶈缃竴浜涘彲浠ユ彁鍓嶏紝娌℃湁鍓綔鐢ㄧ殑鍐呭 mResolveHostService.setEnableExpiredIp(config.isEnableExpiredIp()); if (config.getIPRankingList() != null) { mIpIPRankingService.setIPRankingList(config.getIPRankingList()); } - // 设置region 必须在 读取缓存之前。2.4.1版本开始region初始化提前到HttpDnsConfig初始化 + // 璁剧疆region 蹇呴』鍦?璇诲彇缂撳瓨涔嬪墠銆?.4.1鐗堟湰寮€濮媟egion鍒濆鍖栨彁鍓嶅埌HttpDnsConfig鍒濆鍖? - // 设置 主站域名 需要在 读取缓存之前 + // 璁剧疆 涓荤珯鍩熷悕 闇€瑕佸湪 璇诲彇缂撳瓨涔嬪墠 this.mResultRepo.setHostListWhichIpFixed(config.getHostListWithFixedIp()); - // 设置缓存控制,并读取缓存 + // 璁剧疆缂撳瓨鎺у埗锛屽苟璇诲彇缂撳瓨 mResultRepo.setCachedIPEnabled(config.isEnableCacheIp(), config.getExpiredThresholdMillis()); this.mResultRepo.setCacheTtlChanger(config.getCacheTtlChanger()); resolveAfterNetworkChange = config.isResolveAfterNetworkChange(); @@ -249,7 +249,7 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat } mRequestHandler.resetStatus(); - //服务IP更新,触发服务IP测速 + //鏈嶅姟IP鏇存柊锛岃Е鍙戞湇鍔P娴嬮€? if (!mUseCustomServiceHosts) { mRegionServerRankingService.rankServiceIp(mHttpDnsConfig.getCurrentServer()); } @@ -644,7 +644,7 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat boolean changed = mHttpDnsConfig.setRegion(region); if (changed) { mResultRepo.clearMemoryCache(); - //region变化,服务IP变成对应的预置IP,触发测速 + //region鍙樺寲锛屾湇鍔P鍙樻垚瀵瑰簲鐨勯缃甀P锛岃Е鍙戞祴閫? if (!mUseCustomServiceHosts) { mRegionServerRankingService.rankServiceIp(mHttpDnsConfig.getCurrentServer()); } @@ -710,24 +710,24 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat mHttpDnsConfig.getWorker().execute(new Runnable() { @Override public void run() { - // 获取当前网络标识 + // 鑾峰彇褰撳墠缃戠粶鏍囪瘑 String requestNetworkKey = getCurrentNetworkKey(); - // 获取历史域名 + // 鑾峰彇鍘嗗彶鍩熷悕 HashMap allHost = mResultRepo.getAllHostWithoutFixedIP(); if (HttpDnsLog.isPrint()) { HttpDnsLog.d("network change to " + requestNetworkKey + ", smart resolve hosts"); } - // 智能增量解析 + // 鏅鸿兘澧為噺瑙f瀽 if (resolveAfterNetworkChange && mHttpDnsConfig.isEnabled()) { smartBatchResolve(allHost, requestNetworkKey); } } }); - //网络变化,触发服务IP测速 + //缃戠粶鍙樺寲锛岃Е鍙戞湇鍔P娴嬮€? if (!mUseCustomServiceHosts) { mRegionServerRankingService.rankServiceIp(mHttpDnsConfig.getCurrentServer()); } @@ -778,11 +778,11 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat public void cleanHostCache(ArrayList hosts) { CleanHostCacheEvent cleanHostCacheEvent = new CleanHostCacheEvent(); if (hosts == null || hosts.size() == 0) { - // 清理所有host + // 娓呯悊鎵€鏈塰ost mResultRepo.clear(); cleanHostCacheEvent.setTag(ObservableConstants.CLEAN_ALL_HOST_CACHE); } else { - // 清理选中的host + // 娓呯悊閫変腑鐨刪ost cleanHostCacheEvent.setTag(ObservableConstants.CLEAN_SPECIFY_HOST_CACHE); mResultRepo.clear(hosts); } @@ -887,22 +887,22 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat } /** - * 智能增量解析:只解析当前网络环境下缺失的域名 + * 鏅鸿兘澧為噺瑙f瀽锛氬彧瑙f瀽褰撳墠缃戠粶鐜涓嬬己澶辩殑鍩熷悕 * - * @param allHosts 所有历史域名 - * @param requestNetworkKey 请求时的网络标识 + * @param allHosts 鎵€鏈夊巻鍙插煙鍚? + * @param requestNetworkKey 璇锋眰鏃剁殑缃戠粶鏍囪瘑 */ private void smartBatchResolve(HashMap allHosts, String requestNetworkKey) { ArrayList v4List = new ArrayList<>(); ArrayList v6List = new ArrayList<>(); ArrayList bothList = new ArrayList<>(); - // 检查当前网络环境下是否需要解析 + // 妫€鏌ュ綋鍓嶇綉缁滅幆澧冧笅鏄惁闇€瑕佽В鏋? for (Map.Entry entry : allHosts.entrySet()) { String host = entry.getKey(); RequestIpType type = entry.getValue(); - // 使用请求时的网络标识检查缓存 + // 浣跨敤璇锋眰鏃剁殑缃戠粶鏍囪瘑妫€鏌ョ紦瀛? if (needsResolveInNetwork(host, type, requestNetworkKey)) { if (type == RequestIpType.v4) { v4List.add(host); @@ -914,7 +914,7 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat } } - // 使用带网络标识的批量解析方法 + // 浣跨敤甯︾綉缁滄爣璇嗙殑鎵归噺瑙f瀽鏂规硶 if (v4List.size() > 0) { mBatchResolveHostService.batchResolveHostAsync(v4List, RequestIpType.v4); } @@ -933,26 +933,27 @@ public class HttpDnsServiceImpl implements HttpDnsService, OnRegionServerIpUpdat } /** - * 检查指定网络环境下是否需要解析域名 + * 妫€鏌ユ寚瀹氱綉缁滅幆澧冧笅鏄惁闇€瑕佽В鏋愬煙鍚? * - * @param host 域名 - * @param type 解析类型 - * @param networkKey 网络标识 - * @return 是否需要解析 + * @param host 鍩熷悕 + * @param type 瑙f瀽绫诲瀷 + * @param networkKey 缃戠粶鏍囪瘑 + * @return 鏄惁闇€瑕佽В鏋? */ private boolean needsResolveInNetwork(String host, RequestIpType type, String networkKey) { - // 检查指定网络环境下是否有有效缓存 + // 妫€鏌ユ寚瀹氱綉缁滅幆澧冧笅鏄惁鏈夋湁鏁堢紦瀛? ResolveHostCache cache = mResultRepo.getCacheGroup().getCache(networkKey); HTTPDNSResultWrapper result = cache.getResult(host, type); return result == null || result.isExpired(); } /** - * 获取当前网络标识,用于网络隔离缓存 + * 鑾峰彇褰撳墠缃戠粶鏍囪瘑锛岀敤浜庣綉缁滈殧绂荤紦瀛? * - * @return 当前网络标识 + * @return 褰撳墠缃戠粶鏍囪瘑 */ private String getCurrentNetworkKey() { return NetworkStateManager.getInstance().getCurrentNetworkKey(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/SignService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/SignService.java index de61652..ccce1d0 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/SignService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/impl/SignService.java @@ -45,7 +45,7 @@ public class SignService { public String sign(Map param) { if (TextUtils.isEmpty(mSecretKey)) { if (HttpDnsLog.isPrint()) { - HttpDnsLog.d("secretKey为空."); + HttpDnsLog.d("secretKey为空"); } return ""; } @@ -67,8 +67,7 @@ public class SignService { } /** - * 新版 /resolve 请求签名: - * appId|lower(domain)|upper(qtype)|exp|nonce + * 鏂扮増 /resolve 璇锋眰绛惧悕锛? * appId|lower(domain)|upper(qtype)|exp|nonce */ public String signResolve(String appId, String domain, String qtype, String exp, String nonce) { if (TextUtils.isEmpty(mSecretKey) @@ -139,3 +138,4 @@ public class SignService { return !TextUtils.isEmpty(mSecretKey); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/log/HttpDnsLog.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/log/HttpDnsLog.java index 1f1b959..07df5ee 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/log/HttpDnsLog.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/log/HttpDnsLog.java @@ -7,7 +7,7 @@ import com.alibaba.sdk.android.httpdns.ILogger; import android.util.Log; /** - * 日志工具类 + * 鏃ュ織宸ュ叿绫? */ public class HttpDnsLog { @@ -16,8 +16,8 @@ public class HttpDnsLog { private static final HashSet LOGGERS = new HashSet<>(); /** - * 设置日志接口 - * 不受{@link #printToLogcat} 控制 + * 璁剧疆鏃ュ織鎺ュ彛 + * 涓嶅彈{@link #printToLogcat} 鎺у埗 */ public static void setLogger(ILogger logger) { if (logger != null) { @@ -26,7 +26,7 @@ public class HttpDnsLog { } /** - * 移除日志接口 + * 绉婚櫎鏃ュ織鎺ュ彛 */ public static void removeLogger(ILogger logger) { if (logger != null) { @@ -35,7 +35,7 @@ public class HttpDnsLog { } /** - * logcat开关 + * logcat寮€鍏? * * @param enable */ @@ -124,7 +124,7 @@ public class HttpDnsLog { } /** - * ip数组转成字符串方便输出 + * ip鏁扮粍杞垚瀛楃涓叉柟渚胯緭鍑? * * @param ips * @return @@ -142,3 +142,4 @@ public class HttpDnsLog { return stringBuilder.toString(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/HttpDnsNetworkDetector.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/HttpDnsNetworkDetector.java index c57829c..7fe2249 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/HttpDnsNetworkDetector.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/HttpDnsNetworkDetector.java @@ -31,7 +31,7 @@ public class HttpDnsNetworkDetector implements HttpDnsSettings.NetworkDetector { private Context mContext; /** - * 网络变化时,清除缓存 + * 缃戠粶鍙樺寲鏃讹紝娓呴櫎缂撳瓨 */ public void cleanCache(final boolean connected) { if (mDisableCache) { @@ -42,7 +42,7 @@ public class HttpDnsNetworkDetector implements HttpDnsSettings.NetworkDetector { mWorker.execute(new Runnable() { @Override public void run() { - // 异步探测一下 + // 寮傛鎺㈡祴涓€涓? if (mContext != null) { mCache = detectNetType(mContext); } @@ -52,22 +52,22 @@ public class HttpDnsNetworkDetector implements HttpDnsSettings.NetworkDetector { } /** - * 是否禁用缓存,默认不禁用 - * 不确定是否存在网络链接不变的情况下,网络情况会发生变化的情况,所以提供了此开关 + * 鏄惁绂佺敤缂撳瓨锛岄粯璁や笉绂佺敤 + * 涓嶇‘瀹氭槸鍚﹀瓨鍦ㄧ綉缁滈摼鎺ヤ笉鍙樼殑鎯呭喌涓嬶紝缃戠粶鎯呭喌浼氬彂鐢熷彉鍖栫殑鎯呭喌锛屾墍浠ユ彁渚涗簡姝ゅ紑鍏? */ public void disableCache(boolean disable) { this.mDisableCache = disable; } /** - * 如果不能检查本地网关ip,可以调用此接口关闭 + * 濡傛灉涓嶈兘妫€鏌ユ湰鍦扮綉鍏砳p,鍙互璋冪敤姝ゆ帴鍙e叧闂? */ public void setCheckInterface(boolean checkInterface) { this.mCheckInterface = checkInterface; } /** - * 有些场景需要通过本地解析来确认网络类型,默认使用 www.taobao.com + * 鏈変簺鍦烘櫙闇€瑕侀€氳繃鏈湴瑙f瀽鏉ョ‘璁ょ綉缁滅被鍨嬶紝榛樿浣跨敤 www.taobao.com */ public void setHostToCheckNetType(String hostToCheckNetType) { this.mHostToCheckNetType = hostToCheckNetType; @@ -95,8 +95,8 @@ public class HttpDnsNetworkDetector implements HttpDnsSettings.NetworkDetector { private NetType detectNetType(Context context) { this.mContext = context.getApplicationContext(); try { - int type;// 不检查本地IP的情况下,无法过滤ipv6只有本地ip的情况,需要通过其它方式检测下。 - // 没有网络? + int type;// 涓嶆鏌ユ湰鍦癐P鐨勬儏鍐典笅锛屾棤娉曡繃婊pv6鍙湁鏈湴ip鐨勬儏鍐碉紝闇€瑕侀€氳繃鍏跺畠鏂瑰紡妫€娴嬩笅銆? + // 娌℃湁缃戠粶锛? if (mCheckInterface) { type = Inet64Util.getIpStack(context); } else { @@ -112,7 +112,7 @@ public class HttpDnsNetworkDetector implements HttpDnsSettings.NetworkDetector { } else if (type == IPV6_ONLY) { return NetType.v6; } else { - // 没有网络? + // 娌℃湁缃戠粶锛? return NetType.none; } @@ -128,4 +128,5 @@ public class HttpDnsNetworkDetector implements HttpDnsSettings.NetworkDetector { private final static int IPV6_ONLY = 2; private final static int IP_DUAL_STACK = 3; -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/NetworkStateManager.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/NetworkStateManager.java index 59afe17..8a76bb1 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/NetworkStateManager.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/net/NetworkStateManager.java @@ -54,7 +54,7 @@ public class NetworkStateManager { } this.mContext = ctx.getApplicationContext(); - // 立即检测当前网络状态 + // 绔嬪嵆妫€娴嬪綋鍓嶇綉缁滅姸鎬? mWorker.execute(() -> { try { String currentNetwork = detectCurrentNetwork(); @@ -132,7 +132,7 @@ public class NetworkStateManager { if (ipPrefix != null) { name = name + "_" + ipPrefix; } - // 增加前缀,防止与用户cacheKey冲突 + // 澧炲姞鍓嶇紑锛岄槻姝笌鐢ㄦ埛cacheKey鍐茬獊 mCurrentNetworkKey = (name == null) ? NONE_NETWORK : (NETWORK_KEY_PREFIX + name); if (HttpDnsLog.isPrint()) { @@ -235,3 +235,4 @@ public class NetworkStateManager { return context.checkPermission(permission, Process.myPid(), Process.myUid()); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterException.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterException.java index 21312c7..9f9e1db 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterException.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterException.java @@ -1,4 +1,4 @@ -package com.alibaba.sdk.android.httpdns.network; +package com.alibaba.sdk.android.httpdns.network; import java.io.IOException; @@ -19,3 +19,4 @@ public class HttpDnsAdapterException extends IOException { return errorCode; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterOptions.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterOptions.java index 61d321b..7c9845a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterOptions.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterOptions.java @@ -1,4 +1,4 @@ -package com.alibaba.sdk.android.httpdns.network; +package com.alibaba.sdk.android.httpdns.network; import com.alibaba.sdk.android.httpdns.RequestIpType; @@ -68,3 +68,4 @@ public class HttpDnsAdapterOptions { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterRequest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterRequest.java index 4bc7439..a758ac9 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterRequest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterRequest.java @@ -1,4 +1,4 @@ -package com.alibaba.sdk.android.httpdns.network; +package com.alibaba.sdk.android.httpdns.network; import java.util.Collections; import java.util.LinkedHashMap; @@ -41,3 +41,4 @@ public class HttpDnsAdapterRequest { return body; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterResponse.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterResponse.java index 580c9a8..7a79cd4 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterResponse.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsAdapterResponse.java @@ -1,4 +1,4 @@ -package com.alibaba.sdk.android.httpdns.network; +package com.alibaba.sdk.android.httpdns.network; import java.util.List; import java.util.Map; @@ -32,3 +32,4 @@ public class HttpDnsAdapterResponse { return usedIp; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsErrorCode.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsErrorCode.java index bb3aaaf..e80ab3f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsErrorCode.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsErrorCode.java @@ -1,4 +1,4 @@ -package com.alibaba.sdk.android.httpdns.network; +package com.alibaba.sdk.android.httpdns.network; public final class HttpDnsErrorCode { private HttpDnsErrorCode() { @@ -9,3 +9,4 @@ public final class HttpDnsErrorCode { public static final String HOST_ROUTE_REJECTED = "HOST_ROUTE_REJECTED"; public static final String RESOLVE_SIGN_INVALID = "RESOLVE_SIGN_INVALID"; } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsHttpAdapter.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsHttpAdapter.java index 9ff994f..c8d2d45 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsHttpAdapter.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/network/HttpDnsHttpAdapter.java @@ -1,4 +1,4 @@ -package com.alibaba.sdk.android.httpdns.network; +package com.alibaba.sdk.android.httpdns.network; import com.alibaba.sdk.android.httpdns.HTTPDNSResult; import com.alibaba.sdk.android.httpdns.HttpDnsService; @@ -211,7 +211,7 @@ public class HttpDnsHttpAdapter { try { SSLSocketFactory baseFactory; if (options.isAllowInsecureCertificatesForDebugOnly()) { - baseFactory = trustAllSocketFactory(); + baseFactory = AlibabaAllSocketFactory(); } else { baseFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } @@ -221,7 +221,7 @@ public class HttpDnsHttpAdapter { } } - private SSLSocketFactory trustAllSocketFactory() throws GeneralSecurityException { + private SSLSocketFactory AlibabaAllSocketFactory() throws GeneralSecurityException { TrustManager[] managers = new TrustManager[]{new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { @@ -306,3 +306,4 @@ public class HttpDnsHttpAdapter { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConfig.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConfig.java index c1b8eeb..57864ef 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConfig.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConfig.java @@ -10,7 +10,7 @@ import org.json.JSONException; import org.json.JSONObject; public class ObservableConfig implements SpCacheItem { - //默认关闭 + //榛樿鍏抽棴 public boolean enable = false; public double sampleRatio = 1.0; public String endpoint = ""; @@ -21,7 +21,7 @@ public class ObservableConfig implements SpCacheItem { public boolean updateConfig(ObservableConfig config) { if (config == null) { - //调度接口没有下发配置,关闭可观测 + //璋冨害鎺ュ彛娌℃湁涓嬪彂閰嶇疆锛屽叧闂彲瑙傛祴 if (enable) { enable = false; raw = null; @@ -115,3 +115,4 @@ public class ObservableConfig implements SpCacheItem { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConstants.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConstants.java index fdf894c..5d7ea73 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConstants.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableConstants.java @@ -36,3 +36,4 @@ public final class ObservableConstants { public static final int EMPTY_RESULT = 0x00; public static final int NOT_EMPTY_RESULT = 0x40; } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableHttpRequest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableHttpRequest.java index 0d1666d..b3ed1f6 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableHttpRequest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableHttpRequest.java @@ -96,3 +96,4 @@ public class ObservableHttpRequest extends HttpRequestWrapper { return null; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableManager.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableManager.java index bea8359..000d3ca 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableManager.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/ObservableManager.java @@ -92,7 +92,7 @@ public class ObservableManager { } /** - * 是否开启可观测,如果关闭,则打点和上报都关闭 + * 鏄惁寮€鍚彲瑙傛祴锛屽鏋滃叧闂紝鍒欐墦鐐瑰拰涓婃姤閮藉叧闂? * @return */ private boolean isEnableObservable() { @@ -111,7 +111,7 @@ public class ObservableManager { } if (event instanceof LocalDnsEvent) { - //需要local dns的event,在这里统一执行local dns解析 + //闇€瑕乴ocal dns鐨別vent锛屽湪杩欓噷缁熶竴鎵цlocal dns瑙f瀽 try { sWorker.execute(new Runnable() { @Override @@ -121,7 +121,7 @@ public class ObservableManager { } }); } catch (Exception e) { - //线程池异常,也要添加事件 + //绾跨▼姹犲紓甯革紝涔熻娣诲姞浜嬩欢 addObservableEventInner(event); } } else { @@ -205,14 +205,14 @@ public class ObservableManager { if (HttpDnsLog.isPrint()) { HttpDnsLog.w("observable report rate exception."); } - //关闭日志采集 + //鍏抽棴鏃ュ織閲囬泦 mReportingRateException = true; } } private void tryReport() { if (mCacheEvents.size() >= mHttpDnsConfig.getObservableConfig().batchReportMaxSize) { - //达到上报数量 + //杈惧埌涓婃姤鏁伴噺 mHandler.removeMessages(MESSAGE_REPORT); mHandler.sendEmptyMessage(MESSAGE_REPORT); } @@ -233,7 +233,7 @@ public class ObservableManager { return; } - //上报流量控制判断 + //涓婃姤娴侀噺鎺у埗鍒ゆ柇 long current = System.currentTimeMillis(); if (reachingReportingLimit(current)) { return; @@ -258,7 +258,7 @@ public class ObservableManager { return; } - //添加上报时间点,用于上报流量控制 + //娣诲姞涓婃姤鏃堕棿鐐癸紝鐢ㄤ簬涓婃姤娴侀噺鎺у埗 mReportsTime.addLast(current); HttpRequest request = new ObservableHttpRequest<>(url, new ResponseParser() { @@ -267,7 +267,7 @@ public class ObservableManager { return response; } }, headers, body); - // 重试2次 + // 閲嶈瘯2娆? request = new RetryHttpRequest<>(request, 2); mReportWorker.execute(new HttpRequestTask<>(request, new RequestCallback() { @@ -360,7 +360,7 @@ public class ObservableManager { return false; } - //先移除超过每分钟上报次数的上报时间点 + //鍏堢Щ闄よ秴杩囨瘡鍒嗛挓涓婃姤娆℃暟鐨勪笂鎶ユ椂闂寸偣 while (mReportsTime.size() > limit) { mReportsTime.pollFirst(); } @@ -373,3 +373,4 @@ public class ObservableManager { return current - first < DateUtils.MINUTE_IN_MILLIS; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/BatchQueryHttpDnsApiEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/BatchQueryHttpDnsApiEvent.java index cee3e37..e20e2df 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/BatchQueryHttpDnsApiEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/BatchQueryHttpDnsApiEvent.java @@ -22,3 +22,4 @@ public class BatchQueryHttpDnsApiEvent extends QueryHttpDnsApiEvent { //do nothing } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CallSdkApiEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CallSdkApiEvent.java index cfec431..19add64 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CallSdkApiEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CallSdkApiEvent.java @@ -80,3 +80,4 @@ public class CallSdkApiEvent extends ObservableEvent implements GroupEvent, Loca return mTag; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CleanHostCacheEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CleanHostCacheEvent.java index 3f8807d..d7d9484 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CleanHostCacheEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/CleanHostCacheEvent.java @@ -42,3 +42,4 @@ public class CleanHostCacheEvent extends ObservableEvent { //do nothing } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/GroupEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/GroupEvent.java index 3294c46..3bd84d6 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/GroupEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/GroupEvent.java @@ -1,10 +1,11 @@ package com.alibaba.sdk.android.httpdns.observable.event; /** - * 需要聚合的事件 + * 闇€瑕佽仛鍚堢殑浜嬩欢 */ public interface GroupEvent { boolean isSameGroup(ObservableEvent event); void groupWith(ObservableEvent event); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/LocalDnsEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/LocalDnsEvent.java index acb3265..eb7ad83 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/LocalDnsEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/LocalDnsEvent.java @@ -60,8 +60,9 @@ public interface LocalDnsEvent { } /** - * 返回值和tag中的请求类型保持一致 + * 杩斿洖鍊煎拰tag涓殑璇锋眰绫诲瀷淇濇寔涓€鑷? * @return */ abstract int getRequestIpType(); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ObservableEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ObservableEvent.java index 3f07dd1..161e3a8 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ObservableEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ObservableEvent.java @@ -164,7 +164,7 @@ public abstract class ObservableEvent { DIVIDER + mTimestamp + DIVIDER + (TextUtils.isEmpty(mServerIp) ? "" : mServerIp) + DIVIDER + mCostTime + - DIVIDER + (TextUtils.isEmpty(mNetworkType) ? "" : mNetworkType) + //预留的网络类型 + DIVIDER + (TextUtils.isEmpty(mNetworkType) ? "" : mNetworkType) + //棰勭暀鐨勭綉缁滅被鍨? DIVIDER + ((TextUtils.isEmpty(mIpType)) ? "" : mIpType) + DIVIDER + mStatusCode + DIVIDER + (TextUtils.isEmpty(mErrorCode) ? "" : mErrorCode) + @@ -174,3 +174,4 @@ public abstract class ObservableEvent { DIVIDER + mLocalDnsCost; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/QueryHttpDnsApiEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/QueryHttpDnsApiEvent.java index c65fd60..28c5af8 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/QueryHttpDnsApiEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/QueryHttpDnsApiEvent.java @@ -34,3 +34,4 @@ public class QueryHttpDnsApiEvent extends ObservableEvent implements LocalDnsEve return mTag; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ReportingRateExceptionEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ReportingRateExceptionEvent.java index 9ca2c2f..cdade1f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ReportingRateExceptionEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/ReportingRateExceptionEvent.java @@ -42,3 +42,4 @@ public class ReportingRateExceptionEvent extends ObservableEvent { //do nothing } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/UpdateRegionServerIpsEvent.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/UpdateRegionServerIpsEvent.java index 411531e..67ecf8e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/UpdateRegionServerIpsEvent.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/observable/event/UpdateRegionServerIpsEvent.java @@ -50,3 +50,4 @@ public class UpdateRegionServerIpsEvent extends ObservableEvent { //do nothing } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingBean.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingBean.java index b5eb90c..7bf1c1f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingBean.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingBean.java @@ -1,15 +1,15 @@ package com.alibaba.sdk.android.httpdns.ranking; /** - * IP优选配置项 + * IP浼橀€夐厤缃」 */ public class IPRankingBean { /** - * 进行ip优选的域名 + * 杩涜ip浼橀€夌殑鍩熷悕 */ String hostName; /** - * 用于测试速度的端口 + * 鐢ㄤ簬娴嬭瘯閫熷害鐨勭鍙? */ int port; @@ -46,3 +46,4 @@ public class IPRankingBean { return hash; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingCallback.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingCallback.java index 8bb65df..cc88b06 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingCallback.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingCallback.java @@ -1,8 +1,9 @@ package com.alibaba.sdk.android.httpdns.ranking; /** - * IP优选的结果回调 + * IP浼橀€夌殑缁撴灉鍥炶皟 */ public interface IPRankingCallback { void onResult(String host, String[] sortedIps); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingService.java index 8551cc7..22b0d0a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingService.java @@ -8,7 +8,7 @@ import java.util.concurrent.ConcurrentSkipListSet; import com.alibaba.sdk.android.httpdns.impl.HttpDnsConfig; /** - * IP优选服务 + * IP浼橀€夋湇鍔? */ public class IPRankingService { @@ -28,7 +28,7 @@ public class IPRankingService { } /** - * 进行ipv4优选 + * 杩涜ipv4浼橀€? */ public void probeIpv4(String host, String[] ips, final IPRankingCallback IPRankingCallback) { if (mHttpDnsConfig.isIPRankingDisabled()) { @@ -77,3 +77,4 @@ public class IPRankingService { return null; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingTask.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingTask.java index b1489d8..481791f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingTask.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/ranking/IPRankingTask.java @@ -8,7 +8,7 @@ import java.net.SocketAddress; import com.alibaba.sdk.android.httpdns.utils.CommonUtil; /** - * ip优选实现 + * ip浼橀€夊疄鐜? */ public class IPRankingTask implements Runnable { @@ -61,3 +61,4 @@ public class IPRankingTask implements Runnable { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/AsyncRequestTask.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/AsyncRequestTask.java index f857da0..8e5992c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/AsyncRequestTask.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/AsyncRequestTask.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns.request; /** - * 数据请求转异步 + * 鏁版嵁璇锋眰杞紓姝? */ public abstract class AsyncRequestTask implements Runnable { @@ -12,7 +12,7 @@ public abstract class AsyncRequestTask implements Runnable { } /** - * 请求数据,不需要直接调用,除非想要同步获取请求数据 + * 璇锋眰鏁版嵁锛屼笉闇€瑕佺洿鎺ヨ皟鐢紝闄ら潪鎯宠鍚屾鑾峰彇璇锋眰鏁版嵁 */ public abstract T request() throws Throwable; @@ -31,3 +31,4 @@ public abstract class AsyncRequestTask implements Runnable { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/BatchResolveHttpRequestStatusWatcher.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/BatchResolveHttpRequestStatusWatcher.java index 559226a..83a2842 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/BatchResolveHttpRequestStatusWatcher.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/BatchResolveHttpRequestStatusWatcher.java @@ -71,3 +71,4 @@ public class BatchResolveHttpRequestStatusWatcher implements HttpRequestWatcher. } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpException.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpException.java index a3b4dbc..0f3b09c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpException.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpException.java @@ -6,7 +6,7 @@ import org.json.JSONException; import org.json.JSONObject; /** - * 网络请求失败的异常 + * 缃戠粶璇锋眰澶辫触鐨勫紓甯? */ public class HttpException extends Exception { public static final int ERROR_CODE_403 = 403; @@ -14,55 +14,55 @@ public class HttpException extends Exception { public static final int ERROR_CODE_500 = 500; /** - * 用户服务level不匹配 - * (用户有不同的level,高level有一些专用的服务节点,如果一个低level的用户,向一个高level专用的服务节点请求,就会返回此错误) + * 鐢ㄦ埛鏈嶅姟level涓嶅尮閰? + * 锛堢敤鎴锋湁涓嶅悓鐨刲evel锛岄珮level鏈変竴浜涗笓鐢ㄧ殑鏈嶅姟鑺傜偣锛屽鏋滀竴涓綆level鐨勭敤鎴凤紝鍚戜竴涓珮level涓撶敤鐨勬湇鍔¤妭鐐硅姹傦紝灏变細杩斿洖姝ら敊璇級 *

- * 需要重试 切换服务IP + * 闇€瑕侀噸璇?鍒囨崲鏈嶅姟IP */ public static final String ERROR_MSG_SERVICE_LEVEL_DENY = "ServiceLevelDeny"; /** - * 未用签名访问 - * 不重试 不切换 - * 生成空解析 缓存1小时 + * 鏈敤绛惧悕璁块棶 + * 涓嶉噸璇?涓嶅垏鎹? + * 鐢熸垚绌鸿В鏋?缂撳瓨1灏忔椂 */ public static final String ERROR_MSG_UNSIGNED = "UnsignedInterfaceDisabled"; /** - * 签名过期 - * 不重试 不切换 (sdk逻辑保证不应该过期) + * 绛惧悕杩囨湡 + * 涓嶉噸璇?涓嶅垏鎹?锛坰dk閫昏緫淇濊瘉涓嶅簲璇ヨ繃鏈燂級 */ public static final String ERROR_MSG_SIGNATURE_EXPIRED = "SignatureExpired"; /** - * 签名验证失败 - * 不重试 不切换 + * 绛惧悕楠岃瘉澶辫触 + * 涓嶉噸璇?涓嶅垏鎹? */ public static final String ERROR_MSG_INVALID_SIGNATURE = "InvalidSignature"; /** - * 账户服务level缺失 - * 不重试 不切换 - * 生成空解析 缓存1小时 + * 璐︽埛鏈嶅姟level缂哄け + * 涓嶉噸璇?涓嶅垏鎹? + * 鐢熸垚绌鸿В鏋?缂撳瓨1灏忔椂 */ public static final String ERROR_MSG_INVALID_ACCOUNT = "InvalidAccount"; /** - * 账户不存在或者禁用 - * 不重试 不切换 - * 生成空解析 缓存1小时 + * 璐︽埛涓嶅瓨鍦ㄦ垨鑰呯鐢? + * 涓嶉噸璇?涓嶅垏鎹? + * 鐢熸垚绌鸿В鏋?缂撳瓨1灏忔椂 */ public static final String ERROR_MSG_ACCOUNT_NOT_EXISTS = "AccountNotExists"; /** - * 签名有效时间过长 - * 不重试 不切换 + * 绛惧悕鏈夋晥鏃堕棿杩囬暱 + * 涓嶉噸璇?涓嶅垏鎹? */ public static final String ERROR_MSG_INVALID_DURATION = "InvalidDuration"; /** - * 无效域名 - * 不重试 不切换 + * 鏃犳晥鍩熷悕 + * 涓嶉噸璇?涓嶅垏鎹? */ public static final String ERROR_MSG_INVALID_HOST = "InvalidHost"; @@ -82,10 +82,10 @@ public class HttpException extends Exception { } /** - * 创建异常 + * 鍒涘缓寮傚父 * * @param code - * @param message 服务器返回的特定格式的数据 + * @param message 鏈嶅姟鍣ㄨ繑鍥炵殑鐗瑰畾鏍煎紡鐨勬暟鎹? * @return */ public static HttpException create(int code, String message) { @@ -116,7 +116,7 @@ public class HttpException extends Exception { } /** - * 是不是要切换服务IP + * 鏄笉鏄鍒囨崲鏈嶅姟IP */ public boolean shouldShiftServer() { String msg = getMessage(); @@ -130,7 +130,7 @@ public class HttpException extends Exception { } /** - * 这个错误是否建议重试 + * 杩欎釜閿欒鏄惁寤鸿閲嶈瘯 */ public boolean shouldRetry() { String msg = getMessage(); @@ -144,7 +144,7 @@ public class HttpException extends Exception { } /** - * 这个错误是否要创建空缓存 + * 杩欎釜閿欒鏄惁瑕佸垱寤虹┖缂撳瓨 */ public boolean shouldCreateEmptyCache() { String msg = getMessage(); @@ -153,3 +153,4 @@ public class HttpException extends Exception { || ERROR_MSG_ACCOUNT_NOT_EXISTS.equals(msg); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequest.java index d59d2b8..3105043 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequest.java @@ -12,102 +12,88 @@ import javax.net.ssl.HttpsURLConnection; import com.alibaba.sdk.android.httpdns.log.HttpDnsLog; /** - * 网络请求 + * HTTP request wrapper for resolve APIs. */ public class HttpRequest { - private HttpRequestConfig requestConfig; - private ResponseParser translator; + private HttpRequestConfig requestConfig; + private ResponseParser translator; - protected HttpRequest() { - } + protected HttpRequest() { + } - public HttpRequest(HttpRequestConfig requestConfig, ResponseParser translator) { - this.requestConfig = requestConfig; - this.translator = translator; - } + public HttpRequest(HttpRequestConfig requestConfig, ResponseParser translator) { + this.requestConfig = requestConfig; + this.translator = translator; + } - /** - * 获取本次请求的配置 - * - * @return - */ - public HttpRequestConfig getRequestConfig() { - return requestConfig; - } + public HttpRequestConfig getRequestConfig() { + return requestConfig; + } - /** - * 发起请求 - * - * @return 返回的数据 - * @throws Throwable 发生的错误 - */ - public T request() throws Throwable { - HttpURLConnection conn = null; - InputStream in = null; - BufferedReader streamReader = null; + public T request() throws Throwable { + HttpURLConnection conn = null; + InputStream in = null; + BufferedReader streamReader = null; - long start = System.currentTimeMillis(); - String serverIp = requestConfig.getIp(); - String url = requestConfig.url(); - if (HttpDnsLog.isPrint()) { - HttpDnsLog.d("request url " + url); - } - try { - conn = (HttpURLConnection)new URL(url).openConnection(); - conn.setReadTimeout(requestConfig.getTimeout()); - conn.setConnectTimeout(requestConfig.getTimeout()); - //设置通用UA - conn.setRequestProperty("User-Agent", requestConfig.getUA()); - if (conn instanceof HttpsURLConnection) { - ((HttpsURLConnection) conn).setHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier()); - } - if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { - in = conn.getErrorStream(); - if (in != null) { - streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); - String errStr = readStringFrom(streamReader).toString(); - throw HttpException.create(conn.getResponseCode(), errStr); - } else { - throw HttpException.create(conn.getResponseCode(), ""); - } - } else { - in = conn.getInputStream(); - streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); - String responseStr = readStringFrom(streamReader).toString(); - if (HttpDnsLog.isPrint()) { - HttpDnsLog.d("request success " + responseStr); - } - return translator.parse(serverIp, responseStr); - } - } catch (Throwable e) { - long cost = System.currentTimeMillis() - start; - HttpDnsLog.w("request " + url + " fail, cost " + cost, e); - throw e; - } finally { - if (conn != null) { - conn.disconnect(); - } - try { - if (in != null) { - in.close(); - } - if (streamReader != null) { - streamReader.close(); - } - } catch (IOException ignored) { - } - } - } + long start = System.currentTimeMillis(); + String serverIp = requestConfig.getIp(); + String url = requestConfig.url(); + if (HttpDnsLog.isPrint()) { + HttpDnsLog.d("request url " + url); + } + try { + conn = (HttpURLConnection) new URL(url).openConnection(); + conn.setReadTimeout(requestConfig.getTimeout()); + conn.setConnectTimeout(requestConfig.getTimeout()); + conn.setRequestProperty("User-Agent", requestConfig.getUA()); + if (conn instanceof HttpsURLConnection) { + HttpsURLConnection httpsURLConnection = (HttpsURLConnection) conn; + httpsURLConnection.setHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier()); + } + if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { + in = conn.getErrorStream(); + if (in != null) { + streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); + String errStr = readStringFrom(streamReader).toString(); + throw HttpException.create(conn.getResponseCode(), errStr); + } else { + throw HttpException.create(conn.getResponseCode(), ""); + } + } else { + in = conn.getInputStream(); + streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); + String responseStr = readStringFrom(streamReader).toString(); + if (HttpDnsLog.isPrint()) { + HttpDnsLog.d("request success " + responseStr); + } + return translator.parse(serverIp, responseStr); + } + } catch (Throwable e) { + long cost = System.currentTimeMillis() - start; + HttpDnsLog.w("request " + url + " fail, cost " + cost, e); + throw e; + } finally { + if (conn != null) { + conn.disconnect(); + } + try { + if (in != null) { + in.close(); + } + if (streamReader != null) { + streamReader.close(); + } + } catch (IOException ignored) { + } + } + } - /** - * stream to string - */ - public static StringBuilder readStringFrom(BufferedReader streamReader) throws IOException { - StringBuilder sb = new StringBuilder(); - String line; - while ((line = streamReader.readLine()) != null) { - sb.append(line); - } - return sb; - } + public static StringBuilder readStringFrom(BufferedReader streamReader) throws IOException { + StringBuilder sb = new StringBuilder(); + String line; + while ((line = streamReader.readLine()) != null) { + sb.append(line); + } + return sb; + } } diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestConfig.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestConfig.java index 6a02f9d..eeda70f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestConfig.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestConfig.java @@ -7,45 +7,45 @@ import com.alibaba.sdk.android.httpdns.impl.AESEncryptService; import com.alibaba.sdk.android.httpdns.utils.Constants; /** - * 网络请求的配置 + * 缃戠粶璇锋眰鐨勯厤缃? */ public class HttpRequestConfig { public static final String HTTP_SCHEMA = "http://"; public static final String HTTPS_SCHEMA = "https://"; public static final String HTTPS_CERTIFICATE_HOSTNAME = "203.107.1.1"; /** - * 请求协议 + * 璇锋眰鍗忚 */ private String mSchema = HTTP_SCHEMA; /** - * 服务器ip + * 鏈嶅姟鍣╥p */ private String mIp; /** - * 服务器端口 + * 鏈嶅姟鍣ㄧ鍙? */ private int mPort; /** - * 请求路径,包含query参数 + * 璇锋眰璺緞锛屽寘鍚玵uery鍙傛暟 */ private String mPath; /** - * 请求超时时间 + * 璇锋眰瓒呮椂鏃堕棿 */ private int mTimeout = Constants.DEFAULT_TIMEOUT; /** - * 服务器IP类型 只会是 v4 或者 v6 + * 鏈嶅姟鍣↖P绫诲瀷 鍙細鏄?v4 鎴栬€?v6 */ private RequestIpType mIpType = RequestIpType.v4; private String mUA = ""; - //待解析的域名 + //寰呰В鏋愮殑鍩熷悕 private String mResolvingHost; - //待解析的域名的ip类型 + //寰呰В鏋愮殑鍩熷悕鐨刬p绫诲瀷 private RequestIpType mResolvingIpType; - //是不是重试 + //鏄笉鏄噸璇? private boolean isRetry = false; private boolean isSignMode = false; @@ -114,7 +114,7 @@ public class HttpRequestConfig { public String url() { if (mIpType == RequestIpType.v6) { - //域名兜底,这里需要对域名做特殊处理 + //鍩熷悕鍏滃簳锛岃繖閲岄渶瑕佸鍩熷悕鍋氱壒娈婂鐞? if (!TextUtils.isEmpty(mIp) && mIp.contains(".")) { return mSchema + mIp + ":" + mPort + mPath; } @@ -167,3 +167,4 @@ public class HttpRequestConfig { this.mAESEncryptService = mAESEncryptService; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestFailWatcher.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestFailWatcher.java index 52f0412..098e5e2 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestFailWatcher.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestFailWatcher.java @@ -23,3 +23,4 @@ public class HttpRequestFailWatcher implements HttpRequestWatcher.Watcher { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTask.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTask.java index 5a01696..3a1fe24 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTask.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTask.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns.request; /** - * 网络请求的异步任务 + * 缃戠粶璇锋眰鐨勫紓姝ヤ换鍔? */ public class HttpRequestTask extends AsyncRequestTask { @@ -17,3 +17,4 @@ public class HttpRequestTask extends AsyncRequestTask { return mHttpRequest.request(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcher.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcher.java index 138df85..9c31499 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcher.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcher.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns.request; /** - * 监听网络请求,用于附加业务逻辑 + * 鐩戝惉缃戠粶璇锋眰锛岀敤浜庨檮鍔犱笟鍔¢€昏緫 */ public class HttpRequestWatcher extends HttpRequestWrapper { @@ -51,3 +51,4 @@ public class HttpRequestWatcher extends HttpRequestWrapper { void onFail(HttpRequestConfig config, Throwable throwable); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapper.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapper.java index 54bcc94..dd2a3d7 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapper.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapper.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns.request; /** - * 网络请求的包装类 + * 缃戠粶璇锋眰鐨勫寘瑁呯被 */ public class HttpRequestWrapper extends HttpRequest { @@ -21,3 +21,4 @@ public class HttpRequestWrapper extends HttpRequest { return mHttpRequest.request(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RequestCallback.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RequestCallback.java index d02b14b..a1c9ce9 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RequestCallback.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RequestCallback.java @@ -1,10 +1,11 @@ package com.alibaba.sdk.android.httpdns.request; /** - * http请求结果回调 + * http璇锋眰缁撴灉鍥炶皟 */ public interface RequestCallback { void onSuccess(T response); void onFail(Throwable throwable); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/ResponseParser.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/ResponseParser.java index a56cb74..e7eb6b0 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/ResponseParser.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/ResponseParser.java @@ -1,8 +1,9 @@ package com.alibaba.sdk.android.httpdns.request; /** - * http响应解析 + * http鍝嶅簲瑙f瀽 */ public interface ResponseParser { T parse(String serverIp, String response) throws Throwable; } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequest.java index f8eedd2..4c2a2e5 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequest.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns.request; /** - * 失败时 重试请求 + * 澶辫触鏃?閲嶈瘯璇锋眰 */ public class RetryHttpRequest extends HttpRequestWrapper { @@ -20,7 +20,7 @@ public class RetryHttpRequest extends HttpRequestWrapper { } catch (Throwable throwable) { if (shouldRetry(throwable)) { if (retryCount > 0) { - //可观测需要 + //鍙娴嬮渶瑕? getRequestConfig().setRetry(); retryCount--; } else { @@ -37,8 +37,9 @@ public class RetryHttpRequest extends HttpRequestWrapper { if (throwable instanceof HttpException) { return ((HttpException)throwable).shouldRetry(); } else { - // 其它异常都可以重试 + // 鍏跺畠寮傚父閮藉彲浠ラ噸璇? return true; } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/SingleResolveHttpRequestStatusWatcher.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/SingleResolveHttpRequestStatusWatcher.java index e6db2c4..82e9961 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/SingleResolveHttpRequestStatusWatcher.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/SingleResolveHttpRequestStatusWatcher.java @@ -79,3 +79,4 @@ public class SingleResolveHttpRequestStatusWatcher implements HttpRequestWatcher } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/UpdateRegionServerHttpRequestStatusWatcher.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/UpdateRegionServerHttpRequestStatusWatcher.java index ecba870..f96916b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/UpdateRegionServerHttpRequestStatusWatcher.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/request/UpdateRegionServerHttpRequestStatusWatcher.java @@ -50,3 +50,4 @@ public class UpdateRegionServerHttpRequestStatusWatcher implements HttpRequestWa } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/BatchResolveHostService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/BatchResolveHostService.java index d16da07..6c91cac 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/BatchResolveHostService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/BatchResolveHostService.java @@ -16,7 +16,7 @@ import java.util.ArrayList; import java.util.List; /** - * 批量解析域名 + * 鎵归噺瑙f瀽鍩熷悕 * * @author zonglin.nzl * @date 2020/12/11 @@ -42,10 +42,10 @@ public class BatchResolveHostService { } /** - * 批量解析域名 + * 鎵归噺瑙f瀽鍩熷悕 * - * @param hostList 待解析域名列表 - * @param type 解析类型 + * @param hostList 寰呰В鏋愬煙鍚嶅垪琛? + * @param type 瑙f瀽绫诲瀷 */ public void batchResolveHostAsync(final List hostList, final RequestIpType type) { if (HttpDnsLog.isPrint()) { @@ -60,32 +60,32 @@ public class BatchResolveHostService { if (!CommonUtil.isAHost(host) || CommonUtil.isAnIP(host) || this.mHostFilter.isFiltered(host)) { - // 过滤掉不需要的域名 + // 杩囨护鎺変笉闇€瑕佺殑鍩熷悕 if (HttpDnsLog.isPrint()) { HttpDnsLog.d("resolve ignore host as not invalid " + host); } continue; } - // 过滤掉有缓存的域名 + // 杩囨护鎺夋湁缂撳瓨鐨勫煙鍚? String networkKey = NetworkStateManager.getInstance().getCurrentNetworkKey(); if (type == RequestIpType.v4) { HTTPDNSResultWrapper result = mResultRepo.getIps(host, type, networkKey); if (result == null || result.isExpired()) { - // 需要解析 + // 闇€瑕佽В鏋? hostsRequestV4.add(host); } } else if (type == RequestIpType.v6) { HTTPDNSResultWrapper result = mResultRepo.getIps(host, type, networkKey); if (result == null || result.isExpired()) { - // 需要解析 + // 闇€瑕佽В鏋? hostsRequestV6.add(host); } } else { HTTPDNSResultWrapper resultV4 = mResultRepo.getIps(host, RequestIpType.v4, networkKey); HTTPDNSResultWrapper resultV6 = mResultRepo.getIps(host, RequestIpType.v6, networkKey); if ((resultV4 == null || resultV4.isExpired()) && (resultV6 == null || resultV6.isExpired())) { - // 都需要解析 + // 閮介渶瑕佽В鏋? hostsRequestBoth.add(host); } else if (resultV4 == null || resultV4.isExpired()) { hostsRequestV4.add(host); @@ -104,7 +104,7 @@ public class BatchResolveHostService { return; } ArrayList allHosts = new ArrayList<>(hostList); - // 预解析每次最多5个域名 + // 棰勮В鏋愭瘡娆℃渶澶?涓煙鍚? final int maxCountPerRequest = 5; int requestCount = (hostList.size() + maxCountPerRequest - 1) / maxCountPerRequest; for (int i = 0; i < requestCount; i++) { @@ -189,3 +189,4 @@ public class BatchResolveHostService { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/CategoryController.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/CategoryController.java index 4c6a9bf..f292d08 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/CategoryController.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/CategoryController.java @@ -4,7 +4,7 @@ import com.alibaba.sdk.android.httpdns.impl.HttpDnsConfig; import com.alibaba.sdk.android.httpdns.serverip.RegionServerScheduleService; /** - * 域名解析策略控制 + * 鍩熷悕瑙f瀽绛栫暐鎺у埗 */ public class CategoryController implements StatusControl { @@ -44,7 +44,7 @@ public class CategoryController implements StatusControl { } /** - * 重置策略 + * 閲嶇疆绛栫暐 */ public void reset() { mStatus = Status.NORMAL; @@ -52,7 +52,7 @@ public class CategoryController implements StatusControl { } /** - * 设置嗅探模式请求间隔 + * 璁剧疆鍡呮帰妯″紡璇锋眰闂撮殧 * */ public void setSniffTimeInterval(int timeInterval) { @@ -60,7 +60,7 @@ public class CategoryController implements StatusControl { } /** - * 策略状态,只有disable状态会使用嗅探模式 + * 绛栫暐鐘舵€侊紝鍙湁disable鐘舵€佷細浣跨敤鍡呮帰妯″紡 */ enum Status { NORMAL, @@ -68,3 +68,4 @@ public class CategoryController implements StatusControl { DISABLE } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/HostFilter.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/HostFilter.java index a81c482..4dd32d4 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/HostFilter.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/HostFilter.java @@ -20,3 +20,4 @@ public class HostFilter { mNotUseHttpDnsFilter = filter; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/NormalResolveCategory.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/NormalResolveCategory.java index db4097f..6ff28ab 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/NormalResolveCategory.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/NormalResolveCategory.java @@ -11,7 +11,7 @@ import com.alibaba.sdk.android.httpdns.request.SingleResolveHttpRequestStatusWat import com.alibaba.sdk.android.httpdns.serverip.RegionServerScheduleService; /** - * 域名解析的一般策略 + * 鍩熷悕瑙f瀽鐨勪竴鑸瓥鐣? */ public class NormalResolveCategory implements ResolveHostCategory { private final HttpDnsConfig mHttpDnsConfig; @@ -31,11 +31,11 @@ public class NormalResolveCategory implements ResolveHostCategory { new ResolveHostResponseParser(requestConfig.getAESEncryptService())); request = new HttpRequestWatcher<>(request, new SingleResolveHttpRequestStatusWatcher( mHttpDnsConfig.getObservableManager())); - // 切换服务IP,更新服务IP + // 鍒囨崲鏈嶅姟IP锛屾洿鏂版湇鍔P request = new HttpRequestWatcher<>(request, new ShiftServerWatcher(config, mScheduleService, mStatusControl)); - // 重试一次 + // 閲嶈瘯涓€娆? request = new RetryHttpRequest<>(request, 1); try { config.getResolveWorker().execute(new HttpRequestTask<>(request, callback)); @@ -45,3 +45,4 @@ public class NormalResolveCategory implements ResolveHostCategory { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCache.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCache.java index 3f3a274..a198da4 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCache.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCache.java @@ -12,25 +12,25 @@ import com.alibaba.sdk.android.httpdns.cache.HostRecord; public class ResolveHostCache { /** - * v4的解析记录 + * v4鐨勮В鏋愯褰? */ private final ConcurrentHashMap mV4Records = new ConcurrentHashMap<>(); /** - * v6的解析记录 + * v6鐨勮В鏋愯褰? */ private final ConcurrentHashMap mV6Records = new ConcurrentHashMap<>(); /** - * v4的返回结果 + * v4鐨勮繑鍥炵粨鏋? */ private final ConcurrentHashMap mV4HttpDnsResults = new ConcurrentHashMap<>(); /** - * v6的返回结果 + * v6鐨勮繑鍥炵粨鏋? */ private final ConcurrentHashMap mV6HttpDnsResults = new ConcurrentHashMap<>(); /** - * 同时解析4 6的结果 + * 鍚屾椂瑙f瀽4 6鐨勭粨鏋? */ private final ConcurrentHashMap mBothHttpDnsResults = new ConcurrentHashMap<>(); @@ -240,3 +240,4 @@ public class ResolveHostCache { return all; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCacheGroup.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCacheGroup.java index 1c6974d..a64eb51 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCacheGroup.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCacheGroup.java @@ -10,12 +10,12 @@ import com.alibaba.sdk.android.httpdns.cache.HostRecord; import com.alibaba.sdk.android.httpdns.net.NetworkStateManager; /** - * 缓存组管理器,支持网络隔离缓存 + * 缂撳瓨缁勭鐞嗗櫒锛屾敮鎸佺綉缁滈殧绂荤紦瀛? */ public class ResolveHostCacheGroup { /** - * 所有缓存统一管理,包括网络隔离缓存和SDNS缓存 + * 鎵€鏈夌紦瀛樼粺涓€绠$悊锛屽寘鎷綉缁滈殧绂荤紦瀛樺拰SDNS缂撳瓨 */ private final HashMap mCaches = new HashMap<>(); private final Object lock = new Object(); @@ -23,11 +23,11 @@ public class ResolveHostCacheGroup { public ResolveHostCache getCache(String cacheKey) { if (cacheKey == null || cacheKey.isEmpty()) { - // 普通解析使用当前网络标识 + // 鏅€氳В鏋愪娇鐢ㄥ綋鍓嶇綉缁滄爣璇? cacheKey = NetworkStateManager.getInstance().getCurrentNetworkKey(); } - // 统一的缓存获取逻辑 + // 缁熶竴鐨勭紦瀛樿幏鍙栭€昏緫 ResolveHostCache cache = mCaches.get(cacheKey); if (cache == null) { synchronized (lock) { @@ -42,7 +42,7 @@ public class ResolveHostCacheGroup { } /** - * 获取所有网络缓存中的域名(排除SDNS缓存) + * 鑾峰彇鎵€鏈夌綉缁滅紦瀛樹腑鐨勫煙鍚嶏紙鎺掗櫎SDNS缂撳瓨锛? */ public HashMap getAllHostFromNetworkCaches() { HashMap allHosts = new HashMap<>(); @@ -112,3 +112,4 @@ public class ResolveHostCacheGroup { return records; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCategory.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCategory.java index 2df992c..642a423 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCategory.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostCategory.java @@ -5,11 +5,11 @@ import com.alibaba.sdk.android.httpdns.request.HttpRequestConfig; import com.alibaba.sdk.android.httpdns.request.RequestCallback; /** - * 域名解析策略接口 + * 鍩熷悕瑙f瀽绛栫暐鎺ュ彛 */ public interface ResolveHostCategory { /** - * 解析域名 + * 瑙f瀽鍩熷悕 * @param config {@link HttpDnsConfig} * @param requestConfig {@link HttpRequestConfig} * @param callback {@link RequestCallback} @@ -17,3 +17,4 @@ public interface ResolveHostCategory { void resolve(HttpDnsConfig config, HttpRequestConfig requestConfig, RequestCallback callback); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostHelper.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostHelper.java index a66a06a..b59685f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostHelper.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostHelper.java @@ -135,8 +135,7 @@ public class ResolveHostHelper { } /** - * 兼容可观测模块透传 tags。 - */ + * 鍏煎鍙娴嬫ā鍧楅€忎紶 tags銆? */ public static String getTags(HttpDnsConfig config) { if (config == null || TextUtils.isEmpty(config.getBizTags())) { return ""; @@ -144,3 +143,4 @@ public class ResolveHostHelper { return "&tags=" + config.getBizTags(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostRequestHandler.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostRequestHandler.java index 7154b62..ea91f6e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostRequestHandler.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostRequestHandler.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.Map; /** - * 发起域名解析请求 + * 鍙戣捣鍩熷悕瑙f瀽璇锋眰 */ public class ResolveHostRequestHandler { @@ -195,22 +195,20 @@ public class ResolveHostRequestHandler { } /** - * 重置状态 - */ + * 閲嶇疆鐘舵€? */ public void resetStatus() { mCategoryController.reset(); } /** - * 设置嗅探模式请求时间间隔 + * 璁剧疆鍡呮帰妯″紡璇锋眰鏃堕棿闂撮殧 */ public void setSniffTimeInterval(int timeInterval) { mCategoryController.setSniffTimeInterval(timeInterval); } /** - * 设置 SDNS 全局参数(当前服务端不使用,保留兼容) - */ + * 璁剧疆 SDNS 鍏ㄥ眬鍙傛暟锛堝綋鍓嶆湇鍔$涓嶄娇鐢紝淇濈暀鍏煎锛? */ public void setSdnsGlobalParams(Map params) { this.mGlobalParams.clear(); if (params != null) { @@ -219,9 +217,10 @@ public class ResolveHostRequestHandler { } /** - * 清除 SDNS 全局参数 + * 娓呴櫎 SDNS 鍏ㄥ眬鍙傛暟 */ public void clearSdnsGlobalParams() { this.mGlobalParams.clear(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponse.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponse.java index 6e107eb..732e66f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponse.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponse.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; /** - * 解析的结果 + * 瑙f瀽鐨勭粨鏋? */ public class ResolveHostResponse { @@ -182,3 +182,4 @@ public class ResolveHostResponse { return new ResolveHostResponse(list, ""); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseParser.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseParser.java index 68f1538..5900b18 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseParser.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseParser.java @@ -8,7 +8,7 @@ import org.json.JSONObject; public class ResolveHostResponseParser implements ResponseParser { public ResolveHostResponseParser(AESEncryptService aesEncryptService) { - // 新版协议固定 HTTPS,不使用 AES 响应体解密,保留构造参数仅为兼容调用方。 + // 新版协议固定 HTTPS,不使用 AES 响应体解密,保留构造参数仅为兼容调用方 } @Override @@ -25,3 +25,4 @@ public class ResolveHostResponseParser implements ResponseParser records = mDBHelper.readFromDb(region); for (HostRecord record : records) { - // 过期缓存不加载到内存中 + // 杩囨湡缂撳瓨涓嶅姞杞藉埌鍐呭瓨涓? if (System.currentTimeMillis() >= record.getQueryTime() + record.getTtl() * 1000L + expiredThresholdMillis) { continue; } if (record.getIps() == null || record.getIps().length == 0) { - // 空解析,按照ttl来,不区分是否来自数据库 + // 绌鸿В鏋愶紝鎸夌収ttl鏉ワ紝涓嶅尯鍒嗘槸鍚︽潵鑷暟鎹簱 record.setFromDB(false); } if (mHostListWhichIpFixed.contains(record.getHost())) { - // 固定IP,按照ttl来,不区分是否来自数据库 + // 鍥哄畾IP锛屾寜鐓tl鏉ワ紝涓嶅尯鍒嗘槸鍚︽潵鑷暟鎹簱 record.setFromDB(false); } ResolveHostCache cache = mCacheGroup.getCache(record.getCacheKey()); @@ -83,10 +83,10 @@ public class ResolveHostResultRepo { HttpDnsLog.d("cache ready"); } - //清理db + //娓呯悊db ArrayList expired = new ArrayList<>(); for (HostRecord record : records) { - //达到过期阈值 + //杈惧埌杩囨湡闃堝€? if (System.currentTimeMillis() >= record.getQueryTime() + record.getTtl() * 1000L + expiredThresholdMillis) { expired.add(record); } @@ -94,7 +94,7 @@ public class ResolveHostResultRepo { mDBHelper.delete(expired); if (!mHttpDnsConfig.getRegion().equals(region)) { - // 防止刚读取完,region变化了 + // 闃叉鍒氳鍙栧畬锛宺egion鍙樺寲浜? mCacheGroup.clearAll(); } else { for (final HostRecord record : records) { @@ -147,7 +147,7 @@ public class ResolveHostResultRepo { } /** - * 保存预解析结果 + * 淇濆瓨棰勮В鏋愮粨鏋? */ public void save(String region, ResolveHostResponse resolveHostResponse, String cacheKey) { final ArrayList records = new ArrayList<>(); @@ -175,7 +175,7 @@ public class ResolveHostResultRepo { } /** - * 更新ip, 一般用于更新ip的顺序 + * 鏇存柊ip, 涓€鑸敤浜庢洿鏂癷p鐨勯『搴? */ public void update(String host, RequestIpType type, String cacheKey, String[] ips) { switch (type) { @@ -192,7 +192,7 @@ public class ResolveHostResultRepo { } /** - * 获取之前保存的解析结果 + * 鑾峰彇涔嬪墠淇濆瓨鐨勮В鏋愮粨鏋? */ public HTTPDNSResultWrapper getIps(String host, RequestIpType type, String cacheKey) { ensureReadFromDB(); @@ -202,21 +202,21 @@ public class ResolveHostResultRepo { } /** - * 仅清除内容缓存 + * 浠呮竻闄ゅ唴瀹圭紦瀛? */ public void clearMemoryCache() { mCacheGroup.clearAll(); } /** - * 仅清除非主站域名的内存缓存 + * 浠呮竻闄ら潪涓荤珯鍩熷悕鐨勫唴瀛樼紦瀛? */ public void clearMemoryCacheForHostWithoutFixedIP() { mCacheGroup.clearAll(new ArrayList(getAllHostWithoutFixedIP().keySet())); } /** - * 清除所有已解析结果 + * 娓呴櫎鎵€鏈夊凡瑙f瀽缁撴灉 */ public void clear() { final List recordsToBeDeleted = mCacheGroup.clearAll(); @@ -234,7 +234,7 @@ public class ResolveHostResultRepo { } /** - * 清除指定域名的已解析结果 + * 娓呴櫎鎸囧畾鍩熷悕鐨勫凡瑙f瀽缁撴灉 */ public void clear(ArrayList hosts) { if (hosts == null || hosts.size() == 0) { @@ -256,7 +256,7 @@ public class ResolveHostResultRepo { } /** - * 获取当前所有已缓存结果的域名 + * 鑾峰彇褰撳墠鎵€鏈夊凡缂撳瓨缁撴灉鐨勫煙鍚? */ public HashMap getAllHostWithoutFixedIP() { HashMap result = mCacheGroup.getAllHostFromNetworkCaches(); @@ -267,7 +267,7 @@ public class ResolveHostResultRepo { } /** - * 配置 本地缓存开关,触发缓存读取逻辑 + * 閰嶇疆 鏈湴缂撳瓨寮€鍏筹紝瑙﹀彂缂撳瓨璇诲彇閫昏緫 */ public void setCachedIPEnabled(boolean enable, long expiredThresholdMillis) { mEnableCache = enable; @@ -284,16 +284,16 @@ public class ResolveHostResultRepo { } /** - * 设置自定义ttl的接口,用于控制缓存的时长 + * 璁剧疆鑷畾涔塼tl鐨勬帴鍙o紝鐢ㄤ簬鎺у埗缂撳瓨鐨勬椂闀? */ public void setCacheTtlChanger(CacheTtlChanger changer) { mCacheTtlChanger = changer; } /** - * 设置主站域名,主站域名的缓存策略和其它域名不同 - * 1. 内存缓存不轻易清除 - * 2. 默认本地缓存,本地缓存的ttl有效 + * 璁剧疆涓荤珯鍩熷悕锛屼富绔欏煙鍚嶇殑缂撳瓨绛栫暐鍜屽叾瀹冨煙鍚嶄笉鍚? + * 1. 鍐呭瓨缂撳瓨涓嶈交鏄撴竻闄? + * 2. 榛樿鏈湴缂撳瓨锛屾湰鍦扮紦瀛樼殑ttl鏈夋晥 */ public void setHostListWhichIpFixed(List hostListWhichIpFixed) { this.mHostListWhichIpFixed.clear(); @@ -303,11 +303,12 @@ public class ResolveHostResultRepo { } /** - * 获取缓存组,供外部访问网络缓存 + * 鑾峰彇缂撳瓨缁勶紝渚涘閮ㄨ闂綉缁滅紦瀛? * - * @return 缓存组 + * @return 缂撳瓨缁? */ public ResolveHostCacheGroup getCacheGroup() { return mCacheGroup; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostService.java index 4097e3b..ea29736 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostService.java @@ -28,7 +28,7 @@ import com.alibaba.sdk.android.httpdns.utils.CommonUtil; import com.alibaba.sdk.android.httpdns.utils.Constants; /** - * 域名解析服务 + * 鍩熷悕瑙f瀽鏈嶅姟 */ public class ResolveHostService { @@ -55,7 +55,7 @@ public class ResolveHostService { } /** - * 解析域名 + * 瑙f瀽鍩熷悕 */ public HTTPDNSResult resolveHostSyncNonBlocking(final String host, final RequestIpType type, final Map extras, @@ -80,7 +80,7 @@ public class ResolveHostService { } if (result == null || result.isExpired()) { if (type == RequestIpType.both) { - // 过滤掉 未过期的请求 + // 杩囨护鎺?鏈繃鏈熺殑璇锋眰 HTTPDNSResultWrapper resultV4 = mResultRepo.getIps(host, RequestIpType.v4, cacheKey); HTTPDNSResultWrapper resultV6 = mResultRepo.getIps(host, RequestIpType.v6, cacheKey); boolean v4Invalid = @@ -88,13 +88,13 @@ public class ResolveHostService { boolean v6Invalid = resultV6 == null || resultV6.isExpired(); if (v4Invalid && v6Invalid) { - // 都过期,不过滤 + // 閮借繃鏈燂紝涓嶈繃婊? asyncResolveHostInner(host, type, extras, cacheKey); } else if (v4Invalid) { - // 仅v4过期 + // 浠卾4杩囨湡 asyncResolveHostInner(host, RequestIpType.v4, extras, cacheKey); } else if (v6Invalid) { - // 仅v6过期 + // 浠卾6杩囨湡 asyncResolveHostInner(host, RequestIpType.v6, extras, cacheKey); } } else { @@ -194,7 +194,7 @@ public class ResolveHostService { } /** - * 解析域名 + * 瑙f瀽鍩熷悕 */ public HTTPDNSResult resolveHostSync(final String host, final RequestIpType type, final Map extras, final String cacheKey) { @@ -217,7 +217,7 @@ public class ResolveHostService { } if (result != null && (!result.isExpired() || mEnableExpiredIp)) { - //有缓存,如果没过期或者允许使用过期解析结果,直接返回 + //鏈夌紦瀛橈紝濡傛灉娌¤繃鏈熸垨鑰呭厑璁镐娇鐢ㄨ繃鏈熻В鏋愮粨鏋滐紝鐩存帴杩斿洖 if (HttpDnsLog.isPrint()) { HttpDnsLog.i( "request host " + host + " for " + type + " and return " + result.toString() @@ -225,11 +225,11 @@ public class ResolveHostService { } if (result.isExpired()) { - //如果缓存已经过期了,发起异步解析更新缓存 + //濡傛灉缂撳瓨宸茬粡杩囨湡浜嗭紝鍙戣捣寮傛瑙f瀽鏇存柊缂撳瓨 asyncResolveHostInner(host, type, extras, cacheKey); } - //可能是空结果,如果开启降级local dns,走local dns解析 + //鍙兘鏄┖缁撴灉锛屽鏋滃紑鍚檷绾ocal dns锛岃蛋local dns瑙f瀽 if ((result.getIps() == null || result.getIps().length == 0) && (result.getIpv6s() == null || result.getIpv6s().length == 0)) { if (mHttpDnsConfig.isEnableDegradationLocalDns()) { @@ -242,11 +242,11 @@ public class ResolveHostService { return result.getHTTPDNSResult(); } - //如果没有缓存,或者有过期缓存但是不允许使用过期缓存 + //濡傛灉娌℃湁缂撳瓨锛屾垨鑰呮湁杩囨湡缂撳瓨浣嗘槸涓嶅厑璁镐娇鐢ㄨ繃鏈熺紦瀛? if (result == null || result.isExpired()) { - // 没有缓存,或者缓存过期,或者是从数据库读取的 需要解析 + // 娌℃湁缂撳瓨锛屾垨鑰呯紦瀛樿繃鏈燂紝鎴栬€呮槸浠庢暟鎹簱璇诲彇鐨?闇€瑕佽В鏋? if (type == RequestIpType.both) { - // 过滤掉 未过期的请求 + // 杩囨护鎺?鏈繃鏈熺殑璇锋眰 HTTPDNSResultWrapper resultV4 = mResultRepo.getIps(host, RequestIpType.v4, cacheKey); HTTPDNSResultWrapper resultV6 = mResultRepo.getIps(host, RequestIpType.v6, cacheKey); boolean v4Invalid = @@ -254,13 +254,13 @@ public class ResolveHostService { boolean v6Invalid = resultV6 == null || resultV6.isExpired(); if (v4Invalid && v6Invalid) { - // 都过期,不过滤 + // 閮借繃鏈燂紝涓嶈繃婊? syncResolveHostInner(host, type, extras, cacheKey, result); } else if (v4Invalid) { - // 仅v4过期 + // 浠卾4杩囨湡 syncResolveHostInner(host, RequestIpType.v4, extras, cacheKey, result); } else if (v6Invalid) { - // 仅v6过期 + // 浠卾6杩囨湡 syncResolveHostInner(host, RequestIpType.v6, extras, cacheKey, result); } } else { @@ -278,7 +278,7 @@ public class ResolveHostService { + " after request"); } - //可能是空结果,如果开启降级local dns,走local dns解析 + //鍙兘鏄┖缁撴灉锛屽鏋滃紑鍚檷绾ocal dns锛岃蛋local dns瑙f瀽 if ((result.getIps() == null || result.getIps().length == 0) && (result.getIpv6s() == null || result.getIpv6s().length == 0)) { if (mHttpDnsConfig.isEnableDegradationLocalDns()) { @@ -342,7 +342,7 @@ public class ResolveHostService { } if (mLocker.beginResolve(host, type, cacheKey)) { final String region = mHttpDnsConfig.getRegion(); - // 没有正在进行的解析,发起新的解析 + // 娌℃湁姝e湪杩涜鐨勮В鏋愶紝鍙戣捣鏂扮殑瑙f瀽 mRequestHandler.requestResolveHost(host, type, extras, cacheKey, new RequestCallback() { @Override @@ -406,13 +406,13 @@ public class ResolveHostService { } if (result == null || !mEnableExpiredIp) { - // 有结果,但是过期了,不允许返回过期结果,等请求结束 - /* 同步锁超时时间不能大于5s,不论请求是否已结束,保证同步锁都会在至多5s内结束 */ + // 鏈夌粨鏋滐紝浣嗘槸杩囨湡浜嗭紝涓嶅厑璁歌繑鍥炶繃鏈熺粨鏋滐紝绛夎姹傜粨鏉? + /* 鍚屾閿佽秴鏃舵椂闂翠笉鑳藉ぇ浜?s锛屼笉璁鸿姹傛槸鍚﹀凡缁撴潫锛屼繚璇佸悓姝ラ攣閮戒細鍦ㄨ嚦澶?s鍐呯粨鏉?*/ int timeout = mHttpDnsConfig.getTimeout(); if (HttpDnsLog.isPrint()) { HttpDnsLog.d("the httpDnsConfig timeout is: " + timeout); } - //锁的超时上限不能大于5s + //閿佺殑瓒呮椂涓婇檺涓嶈兘澶т簬5s timeout = Math.min(timeout, Constants.SYNC_TIMEOUT_MAX_LIMIT); if (HttpDnsLog.isPrint()) { HttpDnsLog.d("final timeout is: " + timeout); @@ -431,7 +431,7 @@ public class ResolveHostService { } catch (InterruptedException e) { e.printStackTrace(); } - // 不管什么情况释放锁 + // 涓嶇浠€涔堟儏鍐甸噴鏀鹃攣 mLocker.endResolve(host, type, cacheKey); if (HttpDnsLog.isPrint()) { HttpDnsLog.d("sync resolve time is: " + (System.currentTimeMillis() - start)); @@ -480,11 +480,11 @@ public class ResolveHostService { } if (result.isExpired()) { - //如果缓存已经过期了,发起异步解析更新缓存 + //濡傛灉缂撳瓨宸茬粡杩囨湡浜嗭紝鍙戣捣寮傛瑙f瀽鏇存柊缂撳瓨 asyncResolveHostInner(host, type, extras, cacheKey); } - //可能是空结果,如果开启降级local dns,走local dns解析 + //鍙兘鏄┖缁撴灉锛屽鏋滃紑鍚檷绾ocal dns锛岃蛋local dns瑙f瀽 if ((result.getIps() == null || result.getIps().length == 0) && (result.getIpv6s() == null || result.getIpv6s().length == 0)) { if (mHttpDnsConfig.isEnableDegradationLocalDns()) { @@ -507,9 +507,9 @@ public class ResolveHostService { } CallSdkApiEvent callSdkApiEvent = getCallSdkApiEvent(ObservableConstants.RESOLVE_API_ASYNC, host, type, false, result, start); - //没有可用的解析结果,需要发起请求 + //娌℃湁鍙敤鐨勮В鏋愮粨鏋滐紝闇€瑕佸彂璧疯姹? if (type == RequestIpType.both) { - // 过滤掉 未过期的请求 + // 杩囨护鎺?鏈繃鏈熺殑璇锋眰 HTTPDNSResultWrapper resultV4 = mResultRepo.getIps(host, RequestIpType.v4, cacheKey); HTTPDNSResultWrapper resultV6 = mResultRepo.getIps(host, RequestIpType.v6, cacheKey); boolean v4Invalid = @@ -517,13 +517,13 @@ public class ResolveHostService { boolean v6Invalid = resultV6 == null || resultV6.isExpired(); if (v4Invalid && v6Invalid) { - // 都过期,不过滤 + // 閮借繃鏈燂紝涓嶈繃婊? asyncResolveHost(host, type, extras, cacheKey, callback, callSdkApiEvent); } else if (v4Invalid) { - // 仅v4过期 + // 浠卾4杩囨湡 asyncResolveHost(host, RequestIpType.v4, extras, cacheKey, callback, callSdkApiEvent); } else if (v6Invalid) { - // 仅v6过期 + // 浠卾6杩囨湡 asyncResolveHost(host, RequestIpType.v6, extras, cacheKey, callback, callSdkApiEvent); } } else { @@ -538,17 +538,17 @@ public class ResolveHostService { public void run() { asyncResolveHostInner(host, type, extras, cacheKey); - /* 同步锁超时时间不能大于5s,不论请求是否已结束,保证同步锁都会在至多5s内结束 */ + /* 鍚屾閿佽秴鏃舵椂闂翠笉鑳藉ぇ浜?s锛屼笉璁鸿姹傛槸鍚﹀凡缁撴潫锛屼繚璇佸悓姝ラ攣閮戒細鍦ㄨ嚦澶?s鍐呯粨鏉?*/ int timeout = mHttpDnsConfig.getTimeout(); if (HttpDnsLog.isPrint()) { HttpDnsLog.d("the httpDnsConfig timeout is: " + timeout); } - //锁的超时上限不能大于5s + //閿佺殑瓒呮椂涓婇檺涓嶈兘澶т簬5s timeout = Math.min(timeout, Constants.SYNC_TIMEOUT_MAX_LIMIT); if (HttpDnsLog.isPrint()) { HttpDnsLog.d("final timeout is: " + timeout); } - //发起异步请求,有无并发,统一在这里通过锁同步机制,从缓存中处理解析结果 + //鍙戣捣寮傛璇锋眰锛屾湁鏃犲苟鍙戯紝缁熶竴鍦ㄨ繖閲岄€氳繃閿佸悓姝ユ満鍒讹紝浠庣紦瀛樹腑澶勭悊瑙f瀽缁撴灉 if (HttpDnsLog.isPrint()) { HttpDnsLog.d("wait for request finish"); } @@ -575,7 +575,7 @@ public class ResolveHostService { } if (callback != null) { - //可能是空结果,如果开启降级local dns,走local dns解析 + //鍙兘鏄┖缁撴灉锛屽鏋滃紑鍚檷绾ocal dns锛岃蛋local dns瑙f瀽 if ((result.getIps() == null || result.getIps().length == 0) && (result.getIpv6s() == null || result.getIpv6s().length == 0)) { if (mHttpDnsConfig.isEnableDegradationLocalDns()) { @@ -634,3 +634,4 @@ public class ResolveHostService { return callSdkApiEvent; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcher.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcher.java index ade2112..6694bf2 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcher.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcher.java @@ -9,7 +9,7 @@ import com.alibaba.sdk.android.httpdns.serverip.RegionServerScheduleService; import com.alibaba.sdk.android.httpdns.utils.Constants; /** - * 请求失败时,切换当前Region的服务IP,服务IP都切换过,更新服务IP + * 璇锋眰澶辫触鏃讹紝鍒囨崲褰撳墠Region鐨勬湇鍔P锛屾湇鍔P閮藉垏鎹㈣繃锛屾洿鏂版湇鍔P */ public class ShiftServerWatcher implements HttpRequestWatcher.Watcher { @@ -53,9 +53,9 @@ public class ShiftServerWatcher implements HttpRequestWatcher.Watcher { @Override public void onFail(HttpRequestConfig requestConfig, Throwable throwable) { long cost = System.currentTimeMillis() - mBeginRequestTime; - // 是否切换服务IP, 超过超时时间,我们也切换ip,花费时间太长,说明这个ip可能也有问题 + // 鏄惁鍒囨崲鏈嶅姟IP, 瓒呰繃瓒呮椂鏃堕棿锛屾垜浠篃鍒囨崲ip锛岃姳璐规椂闂村お闀匡紝璇存槑杩欎釜ip鍙兘涔熸湁闂 if (shouldShiftServer(throwable) || cost > requestConfig.getTimeout()) { - // 切换和更新请求的服务IP + // 鍒囨崲鍜屾洿鏂拌姹傜殑鏈嶅姟IP boolean isBackToFirstServer; if (requestConfig.getIpType() == RequestIpType.v6) { isBackToFirstServer = this.mHttpDnsConfig.getCurrentServer().shiftServerV6( @@ -69,7 +69,7 @@ public class ShiftServerWatcher implements HttpRequestWatcher.Watcher { requestConfig.setPort(this.mHttpDnsConfig.getCurrentServer().getPort()); } - // 所有服务IP都尝试过了,通知上层进一步处理 + // 鎵€鏈夋湇鍔P閮藉皾璇曡繃浜嗭紝閫氱煡涓婂眰杩涗竴姝ュ鐞? if (isBackToFirstServer && mScheduleService != null) { mScheduleService.updateRegionServerIps(Constants.UPDATE_REGION_SERVER_SCENES_SERVER_UNAVAILABLE); } @@ -83,9 +83,10 @@ public class ShiftServerWatcher implements HttpRequestWatcher.Watcher { if (throwable instanceof HttpException) { return ((HttpException)throwable).shouldShiftServer(); } - // 除了特定的一些错误(sdk问题或者客户配置问题,不是服务网络问题),都切换服务IP,这边避免个别服务节点真的访问不上 - // 一方面尽可能提高可用性,另一方面当客户发生异常时,也方便根据服务IP来判断是否是真的无网络,因为多个服务IP都访问不上的可能性较低 - // 还有一方面是 sniff模式是在切换服务IP的前提下触发的,这样也提高的sniff模式触发几率,在真的网络异常时,降低网络请求频次 + // 闄や簡鐗瑰畾鐨勪竴浜涢敊璇紙sdk闂鎴栬€呭鎴烽厤缃棶棰橈紝涓嶆槸鏈嶅姟缃戠粶闂锛夛紝閮藉垏鎹㈡湇鍔P锛岃繖杈归伩鍏嶄釜鍒湇鍔¤妭鐐圭湡鐨勮闂笉涓? + // 涓€鏂归潰灏藉彲鑳芥彁楂樺彲鐢ㄦ€э紝鍙︿竴鏂归潰褰撳鎴峰彂鐢熷紓甯告椂锛屼篃鏂逛究鏍规嵁鏈嶅姟IP鏉ュ垽鏂槸鍚︽槸鐪熺殑鏃犵綉缁滐紝鍥犱负澶氫釜鏈嶅姟IP閮借闂笉涓婄殑鍙兘鎬ц緝浣? + // 杩樻湁涓€鏂归潰鏄?sniff妯″紡鏄湪鍒囨崲鏈嶅姟IP鐨勫墠鎻愪笅瑙﹀彂鐨勶紝杩欐牱涔熸彁楂樼殑sniff妯″紡瑙﹀彂鍑犵巼锛屽湪鐪熺殑缃戠粶寮傚父鏃讹紝闄嶄綆缃戠粶璇锋眰棰戞 return true; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffException.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffException.java index dd04fbc..ade8a6b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffException.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffException.java @@ -6,3 +6,4 @@ public class SniffException extends Exception { super(message); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffResolveCategory.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffResolveCategory.java index 6731207..618688a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffResolveCategory.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/SniffResolveCategory.java @@ -11,7 +11,7 @@ import com.alibaba.sdk.android.httpdns.serverip.RegionServerScheduleService; import com.alibaba.sdk.android.httpdns.utils.Constants; /** - * 嗅探模式 + * 鍡呮帰妯″紡 */ public class SniffResolveCategory implements ResolveHostCategory { private final HttpDnsConfig mHttpDnsConfig; @@ -30,7 +30,7 @@ public class SniffResolveCategory implements ResolveHostCategory { public void resolve(HttpDnsConfig config, HttpRequestConfig requestConfig, RequestCallback callback) { long currentTimeMillis = System.currentTimeMillis(); - // 请求间隔 不小于timeInterval + // 璇锋眰闂撮殧 涓嶅皬浜巘imeInterval if (currentTimeMillis - mLastRequestTime < mTimeInterval) { callback.onFail(Constants.sniff_too_often); return; @@ -41,7 +41,7 @@ public class SniffResolveCategory implements ResolveHostCategory { requestConfig, new ResolveHostResponseParser(requestConfig.getAESEncryptService())); request = new HttpRequestWatcher<>(request, new SingleResolveHttpRequestStatusWatcher( mHttpDnsConfig.getObservableManager())); - // 切换服务IP,更新服务IP + // 鍒囨崲鏈嶅姟IP锛屾洿鏂版湇鍔P request = new HttpRequestWatcher<>(request, new ShiftServerWatcher(config, mScheduleService, mStatusControl)); @@ -60,3 +60,4 @@ public class SniffResolveCategory implements ResolveHostCategory { mLastRequestTime = 0L; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/StatusControl.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/StatusControl.java index 02cfca6..2d6c378 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/StatusControl.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/resolve/StatusControl.java @@ -1,16 +1,17 @@ package com.alibaba.sdk.android.httpdns.resolve; /** - * 模式控制接口 + * 妯″紡鎺у埗鎺ュ彛 */ public interface StatusControl { /** - * 下调 + * 涓嬭皟 */ void turnDown(); /** - * 上调 + * 涓婅皟 */ void turnUp(); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServer.java index dbe4765..4612609 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServer.java @@ -20,3 +20,4 @@ public class RegionServer { return CommonUtil.getPort(mPort, scheme); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpData.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpData.java index 13afde4..60a488a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpData.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpData.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns.serverip; /** - * 服务IP存储的数据 + * 鏈嶅姟IP瀛樺偍鐨勬暟鎹? */ public class RegionServerIpData { private final String mRegion; @@ -50,3 +50,4 @@ public class RegionServerIpData { return mServerV6Ports; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpRepo.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpRepo.java index 3122187..80e276d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpRepo.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerIpRepo.java @@ -5,8 +5,8 @@ import java.util.HashMap; import com.alibaba.sdk.android.httpdns.utils.CommonUtil; /** - * 服务ip数据仓库 - * 实现有效期逻辑,有效期内返回值,有效期外返回空 + * 鏈嶅姟ip鏁版嵁浠撳簱 + * 瀹炵幇鏈夋晥鏈熼€昏緫锛屾湁鏁堟湡鍐呰繑鍥炲€硷紝鏈夋晥鏈熷杩斿洖绌? */ public class RegionServerIpRepo { @@ -61,3 +61,4 @@ public class RegionServerIpRepo { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerScheduleService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerScheduleService.java index 310f760..4b1ff8c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerScheduleService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/RegionServerScheduleService.java @@ -6,7 +6,7 @@ import com.alibaba.sdk.android.httpdns.request.RequestCallback; import com.alibaba.sdk.android.httpdns.utils.CommonUtil; /** - * 服务IP的调度服务 + * 鏈嶅姟IP鐨勮皟搴︽湇鍔? */ public class RegionServerScheduleService { @@ -23,7 +23,7 @@ public class RegionServerScheduleService { } /** - * 修改region + * 淇敼region * * @param newRegion */ @@ -93,26 +93,27 @@ public class RegionServerScheduleService { } /** - * 更新服务ip + * 鏇存柊鏈嶅姟ip */ public void updateRegionServerIps(int scenes) { updateRegionServerIps(this.mHttpDnsConfig.getRegion(), scenes); } /** - * 设置服务IP的更新间隔 + * 璁剧疆鏈嶅姟IP鐨勬洿鏂伴棿闅? */ public void setTimeInterval(int timeInterval) { this.mServerIpRepo.setTimeInterval(timeInterval); } /** - * 服务ip更新时的回调接口 + * 鏈嶅姟ip鏇存柊鏃剁殑鍥炶皟鎺ュ彛 */ public interface OnRegionServerIpUpdate { /** - * 服务ip更新了 + * 鏈嶅姟ip鏇存柊浜? */ void serverIpUpdated(boolean regionUpdated); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ShiftRegionServerWatcher.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ShiftRegionServerWatcher.java index 791bc20..db66160 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ShiftRegionServerWatcher.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ShiftRegionServerWatcher.java @@ -4,7 +4,7 @@ import com.alibaba.sdk.android.httpdns.request.HttpRequestConfig; import com.alibaba.sdk.android.httpdns.request.HttpRequestWatcher; /** - * 请求失败时,切换服务IP,服务IP都切换过,使用初始IP + * 璇锋眰澶辫触鏃讹紝鍒囨崲鏈嶅姟IP锛屾湇鍔P閮藉垏鎹㈣繃锛屼娇鐢ㄥ垵濮婭P */ public class ShiftRegionServerWatcher implements HttpRequestWatcher.Watcher { @@ -26,13 +26,14 @@ public class ShiftRegionServerWatcher implements HttpRequestWatcher.Watcher { @Override public void onFail(HttpRequestConfig requestConfig, Throwable throwable) { - // 切换和更新请求的服务IP + // 鍒囨崲鍜屾洿鏂拌姹傜殑鏈嶅姟IP currentIndex++; if (currentIndex < mServers.length) { - // 更新请求用的IP + // 鏇存柊璇锋眰鐢ㄧ殑IP requestConfig.setIp(mServers[currentIndex].getServerIp()); requestConfig.setPort(mServers[currentIndex].getPort(requestConfig.getSchema())); } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerLocker.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerLocker.java index 3149ef1..5f84442 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerLocker.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerLocker.java @@ -22,8 +22,8 @@ public class UpdateRegionServerLocker { if (requestTime != null) { if (System.currentTimeMillis() - requestTime > mTimeout) { - // 超过五分钟了,还没有end。 - // 主动end + // 瓒呰繃浜斿垎閽熶簡锛岃繕娌℃湁end銆? + // 涓诲姩end end(region); } return false; @@ -44,3 +44,4 @@ public class UpdateRegionServerLocker { mCache.remove(region); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerResponse.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerResponse.java index b61dbc9..3c5be9f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerResponse.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerResponse.java @@ -9,7 +9,7 @@ import org.json.JSONException; import org.json.JSONObject; /** - * 更新服务IP返回接口 + * 鏇存柊鏈嶅姟IP杩斿洖鎺ュ彛 */ public class UpdateRegionServerResponse { private final boolean mEnable; @@ -162,3 +162,4 @@ public class UpdateRegionServerResponse { '}'; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerTask.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerTask.java index 42028b8..b0a2722 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerTask.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/UpdateRegionServerTask.java @@ -63,9 +63,9 @@ public class UpdateRegionServerTask { }); httpRequest = new HttpRequestWatcher<>(httpRequest, new UpdateRegionServerHttpRequestStatusWatcher(scenes, config.getObservableManager())); - // 增加切换ip,回到初始Ip的逻辑 + // 澧炲姞鍒囨崲ip锛屽洖鍒板垵濮婭p鐨勯€昏緫 httpRequest = new HttpRequestWatcher<>(httpRequest, new ShiftRegionServerWatcher(servers)); - // 重试,当前服务Ip和初始服务ip个数 + // 閲嶈瘯锛屽綋鍓嶆湇鍔p鍜屽垵濮嬫湇鍔p涓暟 httpRequest = new RetryHttpRequest<>(httpRequest, servers.length - 1); try { @@ -124,3 +124,4 @@ public class UpdateRegionServerTask { return ips.toArray(new String[0]); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingCallback.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingCallback.java index 7184119..c2279eb 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingCallback.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingCallback.java @@ -3,3 +3,4 @@ package com.alibaba.sdk.android.httpdns.serverip.ranking; public interface RegionServerRankingCallback { void onResult(String[] sortedIps, int[] ports); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingService.java index 0cbfb0f..f2eca93 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingService.java @@ -16,7 +16,7 @@ public class RegionServerRankingService { public void rankServiceIp(RegionServer regionServer) { - //对v4地址进行测速 + //瀵箆4鍦板潃杩涜娴嬮€? if (regionServer.getServerIps() != null && regionServer.getServerIps().length > 1) { if (HttpDnsLog.isPrint()) { HttpDnsLog.d("start ranking server ips: " + Arrays.toString(regionServer.getServerIps()) @@ -35,7 +35,7 @@ public class RegionServerRankingService { } } - //对v6地址进行测速,检测到仅支持IPv6才测速,这里和使用服务IP的策略一样 + //瀵箆6鍦板潃杩涜娴嬮€燂紝妫€娴嬪埌浠呮敮鎸両Pv6鎵嶆祴閫燂紝杩欓噷鍜屼娇鐢ㄦ湇鍔P鐨勭瓥鐣ヤ竴鏍? if (regionServer.getIpv6ServerIps() != null && regionServer.getIpv6ServerIps().length > 1 && (mHttpDnsConfig.getNetworkDetector().getNetType(mHttpDnsConfig.getContext()) == NetType.v6)) { if (HttpDnsLog.isPrint()) { @@ -56,3 +56,4 @@ public class RegionServerRankingService { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingTask.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingTask.java index 3c9de15..78cfe54 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingTask.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/serverip/ranking/RegionServerRankingTask.java @@ -82,3 +82,4 @@ public class RegionServerRankingTask implements Runnable { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/track/SessionTrackMgr.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/track/SessionTrackMgr.java index f498751..5554149 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/track/SessionTrackMgr.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/track/SessionTrackMgr.java @@ -37,3 +37,4 @@ public class SessionTrackMgr { return mSid; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/CommonUtil.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/CommonUtil.java index 160389b..f2be40c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/CommonUtil.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/CommonUtil.java @@ -23,14 +23,14 @@ import android.util.Pair; import org.json.JSONObject; /** - * 辅助类 + * 杈呭姪绫? */ public class CommonUtil { private static final int[] HEX_VALUES = new int[128]; static { - // 初始化查找表 + // 鍒濆鍖栨煡鎵捐〃 Arrays.fill(HEX_VALUES, -1); for (int i = '0'; i <= '9'; i++) { HEX_VALUES[i] = i - '0'; @@ -279,12 +279,12 @@ public class CommonUtil { return result; } - // 从旧代码中获取,逻辑待确定 + // 浠庢棫浠g爜涓幏鍙栵紝閫昏緫寰呯‘瀹? public static Map toMap(String extra) { if (extra != null && !extra.isEmpty()) { Map extras = new HashMap<>(); try { - // 测试验证 服务返回的extra字段进行了url encode处理,所以此处 通过Html转化一下。 + // 娴嬭瘯楠岃瘉 鏈嶅姟杩斿洖鐨別xtra瀛楁杩涜浜唘rl encode澶勭悊锛屾墍浠ユ澶?閫氳繃Html杞寲涓€涓嬨€? JSONObject jsonObjectExtra = new JSONObject( (Html.fromHtml((Html.fromHtml(extra)).toString())).toString()); Iterator var2 = jsonObjectExtra.keys(); @@ -310,8 +310,8 @@ public class CommonUtil { } /** - * 当没有指定port(port非法时)根据schema使用默认的port - * 当指定了port时, 使用指定的port + * 褰撴病鏈夋寚瀹歱ort锛坧ort闈炴硶鏃讹級鏍规嵁schema浣跨敤榛樿鐨刾ort + * 褰撴寚瀹氫簡port鏃讹紝 浣跨敤鎸囧畾鐨刾ort */ public static int getPort(int port, String schema) { if (port > 0) { @@ -341,7 +341,7 @@ public class CommonUtil { return new byte[0]; } - // 移除所有空格 + // 绉婚櫎鎵€鏈夌┖鏍? hex = hex.replaceAll("\\s", ""); if (hex.length() % 2 != 0) { @@ -355,7 +355,7 @@ public class CommonUtil { char high = hex.charAt(i); char low = hex.charAt(i + 1); - // 验证字符是否有效 + // 楠岃瘉瀛楃鏄惁鏈夋晥 if (high >= HEX_VALUES.length || low >= HEX_VALUES.length || HEX_VALUES[high] == -1 || HEX_VALUES[low] == -1) { throw new IllegalArgumentException("Invalid hex string"); @@ -379,3 +379,4 @@ public class CommonUtil { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/Constants.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/Constants.java index 89c204d..581ccac 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/Constants.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/Constants.java @@ -8,26 +8,26 @@ import com.alibaba.sdk.android.httpdns.request.HttpRequestConfig; public class Constants { - // region 定义 - // 默认的region + // region 瀹氫箟 + // 榛樿鐨剅egion public static final String REGION_DEFAULT = Constants.REGION_MAINLAND; - // 中国大陆 + // 涓浗澶ч檰 public static final String REGION_MAINLAND = ""; - // 中国香港 + // 涓浗棣欐腐 public static final String REGION_HK = "hk"; - // 新加坡 + // 鏂板姞鍧? public static final String REGION_SG = "sg"; - // 德国 + // 寰峰浗 public static final String REGION_DE = "de"; - //美国 + //缇庡浗 public static final String REGION_US = "us"; - //预发 + //棰勫彂 public static final String REGION_DEBUG_PRE = "pre"; - //TIPS 增加region需要去RegionServerManager添加策略 + //TIPS 澧炲姞region闇€瑕佸幓RegionServerManager娣诲姞绛栫暐 // global public static final String REGION_GLOBAL = "global"; - // 一些默认值 或者 单一场景定义 + // 涓€浜涢粯璁ゅ€?鎴栬€?鍗曚竴鍦烘櫙瀹氫箟 public static final int NO_PORT = -1; public static final int[] NO_PORTS = null; @@ -51,16 +51,16 @@ public class Constants { public static final String DEFAULT_SCHEMA = Constants.DEFAULT_ENABLE_HTTPS ? HttpRequestConfig.HTTPS_SCHEMA : HttpRequestConfig.HTTP_SCHEMA; /** - * 默认超时时间2s + * 榛樿瓒呮椂鏃堕棿2s */ public static final int DEFAULT_TIMEOUT = 2 * 1000; /** - * 同步锁的超时上限 + * 鍚屾閿佺殑瓒呮椂涓婇檺 */ public static final int SYNC_TIMEOUT_MAX_LIMIT = 5 * 1000; - // 配置缓存使用的变量 + // 閰嶇疆缂撳瓨浣跨敤鐨勫彉閲? public static final String CONFIG_CACHE_PREFIX = "httpdns_config_"; public static final String CONFIG_ENABLE = "enable"; @@ -81,3 +81,4 @@ public class Constants { public static final int UPDATE_REGION_SERVER_SCENES_REGION_CHANGE = 2; public static final int UPDATE_REGION_SERVER_SCENES_SERVER_UNAVAILABLE = 1; } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/NetworkUtil.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/NetworkUtil.java index d77f13c..2ac79a5 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/NetworkUtil.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/NetworkUtil.java @@ -33,7 +33,7 @@ public final class NetworkUtil { } NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network); - //是否已经连接到网络(连接上但不代表可以访问网络) + //鏄惁宸茬粡杩炴帴鍒扮綉缁?杩炴帴涓婁絾涓嶄唬琛ㄥ彲浠ヨ闂綉缁? if (capabilities == null || !capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) { return UNKNOWN; } @@ -79,7 +79,7 @@ public final class NetworkUtil { if (networkType == TelephonyManager.NETWORK_TYPE_UNKNOWN) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - // 在 Android 11 平台上,没有 READ_PHONE_STATE 权限时 + // 鍦?Android 11 骞冲彴涓婏紝娌℃湁 READ_PHONE_STATE 鏉冮檺鏃? return UNKNOWN; } @@ -110,7 +110,7 @@ public final class NetworkUtil { return G3; case TelephonyManager.NETWORK_TYPE_LTE: case TelephonyManager.NETWORK_TYPE_IWLAN: - case 19: //目前已知有车机客户使用该标记作为 4G 网络类型 TelephonyManager.NETWORK_TYPE_LTE_CA: + case 19: //鐩墠宸茬煡鏈夎溅鏈哄鎴蜂娇鐢ㄨ鏍囪浣滀负 4G 缃戠粶绫诲瀷 TelephonyManager.NETWORK_TYPE_LTE_CA: return G4; case TelephonyManager.NETWORK_TYPE_NR: return G5; @@ -123,7 +123,8 @@ public final class NetworkUtil { return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } - //6.0之前的版本,不做处理 + //6.0涔嬪墠鐨勭増鏈紝涓嶅仛澶勭悊 return false; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/ThreadUtil.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/ThreadUtil.java index ba8d694..b124973 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/ThreadUtil.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/main/java/com/alibaba/sdk/android/httpdns/utils/ThreadUtil.java @@ -242,3 +242,4 @@ public class ThreadUtil { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/HttpDns.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/HttpDns.java index 7712d51..b92df4e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/HttpDns.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/HttpDns.java @@ -9,7 +9,7 @@ import com.alibaba.sdk.android.httpdns.network.HttpDnsHttpAdapter; import com.alibaba.sdk.android.httpdns.utils.CommonUtil; /** - * Httpdns实例管理 + * Httpdns瀹炰緥绠$悊 */ public class HttpDns { @@ -17,8 +17,8 @@ public class HttpDns { new InstanceCreator()); /** - * 获取HttpDnsService对象 - * @param accountId HttpDns控制台分配的AccountID + * 鑾峰彇HttpDnsService瀵硅薄 + * @param accountId HttpDns鎺у埗鍙板垎閰嶇殑AccountID * @return */ public synchronized static HttpDnsService getService(final String accountId) { @@ -27,10 +27,10 @@ public class HttpDns { /** - * 获取HttpDnsService对象 - * 该方法已弃用,建议使用{@link HttpDns#getService(String)}方法 - * @param applicationContext 当前APP的Context - * @param accountID HttpDns控制台分配的AccountID + * 鑾峰彇HttpDnsService瀵硅薄 + * 璇ユ柟娉曞凡寮冪敤锛屽缓璁娇鐢▄@link HttpDns#getService(String)}鏂规硶 + * @param applicationContext 褰撳墠APP鐨凜ontext + * @param accountID HttpDns鎺у埗鍙板垎閰嶇殑AccountID * @return */ @Deprecated @@ -40,11 +40,11 @@ public class HttpDns { } /** - * 获取HttpDnsService对象,并启用鉴权功能 - * 该方法已弃用,建议使用{@link HttpDns#getService(String)}方法 - * @param applicationContext 当前APP的Context - * @param accountID HttpDns控制台分配的AccountID - * @param secretKey 用户鉴权私钥 + * 鑾峰彇HttpDnsService瀵硅薄锛屽苟鍚敤閴存潈鍔熻兘 + * 璇ユ柟娉曞凡寮冪敤锛屽缓璁娇鐢▄@link HttpDns#getService(String)}鏂规硶 + * @param applicationContext 褰撳墠APP鐨凜ontext + * @param accountID HttpDns鎺у埗鍙板垎閰嶇殑AccountID + * @param secretKey 鐢ㄦ埛閴存潈绉侀挜 * @return */ @Deprecated @@ -55,9 +55,9 @@ public class HttpDns { } /** - * 获取HttpDnsService对象,初始化时不传入任何参数,靠统一接入服务获取相关参数 - * 该方法已弃用,建议使用{@link HttpDns#getService(String)}方法 - * @param applicationContext 当前APP的Context + * 鑾峰彇HttpDnsService瀵硅薄锛屽垵濮嬪寲鏃朵笉浼犲叆浠讳綍鍙傛暟锛岄潬缁熶竴鎺ュ叆鏈嶅姟鑾峰彇鐩稿叧鍙傛暟 + * 璇ユ柟娉曞凡寮冪敤锛屽缓璁娇鐢▄@link HttpDns#getService(String)}鏂规硶 + * @param applicationContext 褰撳墠APP鐨凜ontext * @return */ @Deprecated @@ -67,9 +67,9 @@ public class HttpDns { } /** - * 初始化方法,该方法主要是保存{@link InitConfig},不会真正进行初始化。真正初始化是在{@link HttpDns#getService(Context, String)}中 - * 这么实现主要是为了兼容{@link InitConfig.Builder#buildFor(String)}方法,新客户使用该方法和旧的方法功能一致 - * @param accountId HttpDns控制台分配的AccountID + * 鍒濆鍖栨柟娉曪紝璇ユ柟娉曚富瑕佹槸淇濆瓨{@link InitConfig}锛屼笉浼氱湡姝h繘琛屽垵濮嬪寲銆傜湡姝e垵濮嬪寲鏄湪{@link HttpDns#getService(Context, String)}涓? + * 杩欎箞瀹炵幇涓昏鏄负浜嗗吋瀹箋@link InitConfig.Builder#buildFor(String)}鏂规硶锛屾柊瀹㈡埛浣跨敤璇ユ柟娉曞拰鏃х殑鏂规硶鍔熻兘涓€鑷? + * @param accountId HttpDns鎺у埗鍙板垎閰嶇殑AccountID * @param config {@link InitConfig} */ public static void init(String accountId, InitConfig config) { @@ -91,14 +91,15 @@ public class HttpDns { } /** - * 启用或者禁用httpdns,理论上这个是内部接口,不给外部使用的 - * 但是已经对外暴露,所以保留 + * 鍚敤鎴栬€呯鐢╤ttpdns锛岀悊璁轰笂杩欎釜鏄唴閮ㄦ帴鍙o紝涓嶇粰澶栭儴浣跨敤鐨? + * 浣嗘槸宸茬粡瀵瑰鏆撮湶锛屾墍浠ヤ繚鐣? * * @param enabled - * @deprecated 启用禁用应该调用实例的方法,而不是控制全部实例的方法 + * @deprecated 鍚敤绂佺敤搴旇璋冪敤瀹炰緥鐨勬柟娉曪紝鑰屼笉鏄帶鍒跺叏閮ㄥ疄渚嬬殑鏂规硶 */ @Deprecated public synchronized static void switchDnsService(boolean enabled) { // do nothing as deprecated } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java index 0544ada..c931409 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/InstanceCreator.java @@ -10,3 +10,4 @@ public class InstanceCreator implements HttpDnsCreator { return new NormalImpl(context, accountId, secretKey); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/NormalImpl.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/NormalImpl.java index 90878ed..3fad823 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/NormalImpl.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/normal/java/com/alibaba/sdk/android/httpdns/impl/NormalImpl.java @@ -12,3 +12,4 @@ public class NormalImpl extends HttpDnsServiceImpl { super.favorInit(context, accountId); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsE2E.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsE2E.java index a30c4af..8323a9c 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsE2E.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsE2E.java @@ -71,7 +71,7 @@ public class HttpDnsE2E { @Before public void setUp() { - // 设置日志接口 + // 璁剧疆鏃ュ織鎺ュ彛 HttpDnsLog.enable(true); logger = new ILogger() { private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); @@ -84,11 +84,11 @@ public class HttpDnsE2E { } }; HttpDnsLog.setLogger(logger); - // 重置实例 + // 閲嶇疆瀹炰緥 HttpDns.resetInstance(); - // 重置配置 + // 閲嶇疆閰嶇疆 InitConfig.removeConfig(null); - // 这里我们启动6个 服务节点用于测试 + // 杩欓噷鎴戜滑鍚姩6涓?鏈嶅姟鑺傜偣鐢ㄤ簬娴嬭瘯 server.start(); server1.start(); server2.start(); @@ -102,7 +102,7 @@ public class HttpDnsE2E { app1.configInitServer(REGION_DEFAULT, new HttpDnsServer[] {server, server1, server2}, null); app1.configSpeedTestSever(speedTestServer); - // 启动两个httpdns实例用于测试 + // 鍚姩涓や釜httpdns瀹炰緥鐢ㄤ簬娴嬭瘯 app.start(true); app1.start(true); } @@ -124,27 +124,27 @@ public class HttpDnsE2E { } /** - * 解析域名获取ipv4结果 + * 瑙f瀽鍩熷悕鑾峰彇ipv4缁撴灉 */ @Test public void resolveHostToIpv4s() { - // 请求域名解析,并返回空结果,因为是接口是异步的,所以第一次请求一个域名返回是空 + // 璇锋眰鍩熷悕瑙f瀽锛屽苟杩斿洖绌虹粨鏋滐紝鍥犱负鏄帴鍙f槸寮傛鐨勶紝鎵€浠ョ涓€娆¤姹備竴涓煙鍚嶈繑鍥炴槸绌? String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); - // 验证服务器收到了请求 - ServerStatusHelper.hasReceiveAppResolveHostRequest("当没有缓存时,会异步请求服务器", app, + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); + // 楠岃瘉鏈嶅姟鍣ㄦ敹鍒颁簡璇锋眰 + ServerStatusHelper.hasReceiveAppResolveHostRequest("褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, server, 1); String[] serverResponseIps = ServerStatusHelper.getServerResponseIps(app, server); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", ips, serverResponseIps); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, ips, serverResponseIps); } /** - * 启动日志,会在logcat输出日志 + * 鍚姩鏃ュ織锛屼細鍦╨ogcat杈撳嚭鏃ュ織 */ @Test public void enableLogWillPrintLogInLogcat() { @@ -155,7 +155,7 @@ public class HttpDnsE2E { } /** - * 停止日志,logcat无法获取日志 + * 鍋滄鏃ュ織锛宭ogcat鏃犳硶鑾峰彇鏃ュ織 */ @Test public void disableLogWillNotPrintLogInLogcat() { @@ -166,7 +166,7 @@ public class HttpDnsE2E { } /** - * 设置logger,会在logger中接收到日志 + * 璁剧疆logger锛屼細鍦╨ogger涓帴鏀跺埌鏃ュ織 */ @Test public void setLoggerWillPrintLogToLogger() { @@ -177,14 +177,14 @@ public class HttpDnsE2E { } /** - * 进行一些操作,触发日志 + * 杩涜涓€浜涙搷浣滐紝瑙﹀彂鏃ュ織 */ private void doSomethingTriggerLog() { resolveHostToIpv4s(); } /** - * 修改region,触发更新服务IP,获取新的服务 + * 淇敼region锛岃Е鍙戞洿鏂版湇鍔P锛岃幏鍙栨柊鐨勬湇鍔? */ @Test public void changeRegionWillUpdateServerIp() { @@ -192,36 +192,36 @@ public class HttpDnsE2E { final String otherRegion = Constants.REGION_HK == defaultRegion ? Constants.REGION_MAINLAND : Constants.REGION_HK; - // 设置不同region对应的服务信息 + // 璁剧疆涓嶅悓region瀵瑰簲鐨勬湇鍔′俊鎭? prepareUpdateServerResponse(defaultRegion, otherRegion); - // 修改region + // 淇敼region app.changeRegionTo(otherRegion); - // 连续请求多次 不影响 + // 杩炵画璇锋眰澶氭 涓嶅奖鍝? app.changeRegionTo(otherRegion); app.changeRegionTo(otherRegion); - ServerStatusHelper.hasReceiveRegionChange("修改region会触发更新服务IP请求", app, server, + ServerStatusHelper.hasReceiveRegionChange("淇敼region浼氳Е鍙戞洿鏂版湇鍔P璇锋眰", app, server, otherRegion); - // 请求域名解析 + // 璇锋眰鍩熷悕瑙f瀽 app.requestResolveHost(); - // 确认是另一个服务接受到请求 + // 纭鏄彟涓€涓湇鍔℃帴鍙楀埌璇锋眰 ServerStatusHelper.hasReceiveAppResolveHostRequest( - "切换region后,新的服务收到域名解析请求", app, server3, 1); + "鍒囨崲region鍚庯紝鏂扮殑鏈嶅姟鏀跺埌鍩熷悕瑙f瀽璇锋眰", app, server3, 1); - // 再把region切换回来 + // 鍐嶆妸region鍒囨崲鍥炴潵 app.changeRegionTo(defaultRegion); - ServerStatusHelper.hasReceiveRegionChange("修改region会触发更新服务IP请求", app, server3, + ServerStatusHelper.hasReceiveRegionChange("淇敼region浼氳Е鍙戞洿鏂版湇鍔P璇锋眰", app, server3, defaultRegion); app.requestResolveHost(); ServerStatusHelper.hasReceiveAppResolveHostRequest( - "切回region后,原来的服务收到域名解析请求", app, server, 1); + "鍒囧洖region鍚庯紝鍘熸潵鐨勬湇鍔℃敹鍒板煙鍚嶈В鏋愯姹?, app, server, 1); } /** - * 预设region更新请求 - * defaultRegion 对应 server 0 1 2 - * anotherRegion 对应 server 3 4 5 + * 棰勮region鏇存柊璇锋眰 + * defaultRegion 瀵瑰簲 server 0 1 2 + * anotherRegion 瀵瑰簲 server 3 4 5 * * @param defaultRegion * @param anotherRegion @@ -232,7 +232,7 @@ public class HttpDnsE2E { } private void prepareUpdateServerResponseForGroup2(String defaultRegion) { - // 给 group2(服务3、4、5) 设置 defaultRegion的服务IP是 服务 0 1 2 + // 缁?group2锛堟湇鍔?銆?銆?锛?璁剧疆 defaultRegion鐨勬湇鍔P鏄?鏈嶅姟 0 1 2 String anotherUpdateServerResponse = ServerIpsServer.createUpdateServerResponse( new String[] {server.getServerIp(), server1.getServerIp(), server2.getServerIp()}, RandomValue.randomIpv6s(), @@ -247,7 +247,7 @@ public class HttpDnsE2E { } private void prepareUpdateServerResponseForGroup1(String anotherRegion) { - // 给 group1(服务0、1、2) 设置 anotherRegion的服务IP是 服务 3 4 5 + // 缁?group1锛堟湇鍔?銆?銆?锛?璁剧疆 anotherRegion鐨勬湇鍔P鏄?鏈嶅姟 3 4 5 String updateServerResponse = ServerIpsServer.createUpdateServerResponse( new String[] {server3.getServerIp(), server4.getServerIp(), server5.getServerIp()}, RandomValue.randomIpv6s(), @@ -264,35 +264,35 @@ public class HttpDnsE2E { } /** - * 测试ip probe功能, - * 解析域名之后,对返回的ip进行测试,按照速度快慢排序 + * 娴嬭瘯ip probe鍔熻兘锛? + * 瑙f瀽鍩熷悕涔嬪悗锛屽杩斿洖鐨刬p杩涜娴嬭瘯锛屾寜鐓ч€熷害蹇參鎺掑簭 */ @Test public void sortIpArrayWithSpeedAfterResolveHost() { speedTestServer.watch(server); - // 配置IP优先 + // 閰嶇疆IP浼樺厛 app.enableIPRanking(); - // 请求数据触发IP优选 + // 璇锋眰鏁版嵁瑙﹀彂IP浼橀€? app.requestResolveHost(); - ServerStatusHelper.hasReceiveAppResolveHostRequest("服务接受到域名解析请求", app, server, + ServerStatusHelper.hasReceiveAppResolveHostRequest("鏈嶅姟鎺ュ彈鍒板煙鍚嶈В鏋愯姹?, app, server, 1); - // 判断返回的结果是优选的结果 + // 鍒ゆ柇杩斿洖鐨勭粨鏋滄槸浼橀€夌殑缁撴灉 String[] ips = app.requestResolveHost(); String[] sortedIps = speedTestServer.getSortedIpsFor(app.getRequestHost()); - UnitTestUtil.assertIpsEqual("设置ip优选后,返回的ip是优选之后的结果", ips, sortedIps); + UnitTestUtil.assertIpsEqual("璁剧疆ip浼橀€夊悗锛岃繑鍥炵殑ip鏄紭閫変箣鍚庣殑缁撴灉", ips, sortedIps); } /** - * 正常模式下,域名解析失败,会自动重试一次 + * 姝e父妯″紡涓嬶紝鍩熷悕瑙f瀽澶辫触锛屼細鑷姩閲嶈瘯涓€娆? */ @Test public void resolveHostRequestWillRetryOnceWhenFailed() { - // 预置第一次失败,第二次成功 + // 棰勭疆绗竴娆″け璐ワ紝绗簩娆℃垚鍔? server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), 400, "whatever", 1); @@ -300,187 +300,187 @@ public class HttpDnsE2E { app.getRequestHost()); server1.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, 1); - // 请求 + // 璇锋眰 app.requestResolveHost(); - // 判断服务器是否收到两次请求 + // 鍒ゆ柇鏈嶅姟鍣ㄦ槸鍚︽敹鍒颁袱娆¤姹? ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult(app, server, 400, "whatever"); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "正常模式域名解析失败会重试一次", app, server1, response); + "姝e父妯″紡鍩熷悕瑙f瀽澶辫触浼氶噸璇曚竴娆?, app, server1, response); String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("重试如果请求成功,可以正常获取到解析结果", ips, + UnitTestUtil.assertIpsEqual("閲嶈瘯濡傛灉璇锋眰鎴愬姛锛屽彲浠ユ甯歌幏鍙栧埌瑙f瀽缁撴灉", ips, response.getIps()); } /** - * 设置超时 + * 璁剧疆瓒呮椂 */ @Test public void configReqeustTimeout() { - // 预设请求超时 + // 棰勮璇锋眰瓒呮椂 server.getResolveHostServer().preSetRequestTimeout(app.getRequestHost(), -1); - // 设置超时时间 + // 璁剧疆瓒呮椂鏃堕棿 int timeout = 1000; app.setTimeout(timeout); - // 请求 并计时 + // 璇锋眰 骞惰鏃? long start = System.currentTimeMillis(); app.requestResolveHost(); - // 确实是否接受到请求,并超时 + // 纭疄鏄惁鎺ュ彈鍒拌姹傦紝骞惰秴鏃? ServerStatusHelper.hasReceiveAppResolveHostRequestButTimeout(app, server); long costTime = System.currentTimeMillis() - start; - // 3.05 是个经验数据,可以考虑调整。影响因素主要有重试次数和线程切换 + // 3.05 鏄釜缁忛獙鏁版嵁锛屽彲浠ヨ€冭檻璋冩暣銆傚奖鍝嶅洜绱犱富瑕佹湁閲嶈瘯娆℃暟鍜岀嚎绋嬪垏鎹? assertThat("requst timeout " + costTime, costTime < timeout * 3.05); } /** - * 解析域名时,如果服务不可用,会切换服务IP + * 瑙f瀽鍩熷悕鏃讹紝濡傛灉鏈嶅姟涓嶅彲鐢紝浼氬垏鎹㈡湇鍔P */ @Test public void interpretHostRequestWillShiftServerIpWhenCurrentServerNotAvailable() { - // 预设服务0超时 + // 棰勮鏈嶅姟0瓒呮椂 server.getResolveHostServer().preSetRequestTimeout(app.getRequestHost(), -1); - // 预设服务1正常返回 + // 棰勮鏈嶅姟1姝e父杩斿洖 ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse( app.getRequestHost()); server1.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, 1); - // 设置超时,并请求 + // 璁剧疆瓒呮椂锛屽苟璇锋眰 app.setTimeout(1000); app.requestResolveHost(); - // 确认服务0 接受到请求,超时 + // 纭鏈嶅姟0 鎺ュ彈鍒拌姹傦紝瓒呮椂 ServerStatusHelper.hasReceiveAppResolveHostRequestButTimeout(app, server); - // 确认服务1 正常返回 - ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("服务不可用时,会切换服务IP", + // 纭鏈嶅姟1 姝e父杩斿洖 + ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("鏈嶅姟涓嶅彲鐢ㄦ椂锛屼細鍒囨崲鏈嶅姟IP", app, server1, response); String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("切换服务如果请求成功,可以正常获取到解析结果", ips, + UnitTestUtil.assertIpsEqual("鍒囨崲鏈嶅姟濡傛灉璇锋眰鎴愬姛锛屽彲浠ユ甯歌幏鍙栧埌瑙f瀽缁撴灉", ips, response.getIps()); - // 确认后续请求都是实用切换后的服务 - ServerStatusHelper.requestResolveAnotherHost("切换服务IP后,后续请求都使用此服务", app, + // 纭鍚庣画璇锋眰閮芥槸瀹炵敤鍒囨崲鍚庣殑鏈嶅姟 + ServerStatusHelper.requestResolveAnotherHost("鍒囨崲鏈嶅姟IP鍚庯紝鍚庣画璇锋眰閮戒娇鐢ㄦ鏈嶅姟", app, server1); } /** - * 解析域名时,如果服务降级,会切换服务IP + * 瑙f瀽鍩熷悕鏃讹紝濡傛灉鏈嶅姟闄嶇骇锛屼細鍒囨崲鏈嶅姟IP */ @Test public void interpretHostRequestWillShiftServerIpWhenCurrentServerDegrade() { - // 预设服务0降级 + // 棰勮鏈嶅姟0闄嶇骇 ServerStatusHelper.degradeServer(server, app.getRequestHost(), 1); - // 预设服务1正常返回 + // 棰勮鏈嶅姟1姝e父杩斿洖 ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse( app.getRequestHost()); server1.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, 1); - // 设置超时,并请求 + // 璁剧疆瓒呮椂锛屽苟璇锋眰 app.setTimeout(1000); app.requestResolveHost(); - // 确认服务0 接受到请求,降级 + // 纭鏈嶅姟0 鎺ュ彈鍒拌姹傦紝闄嶇骇 ServerStatusHelper.hasReceiveAppResolveHostRequestWithDegrade(app, server); - // 确认服务1 正常返回 - ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("服务降级时会切换服务IP", + // 纭鏈嶅姟1 姝e父杩斿洖 + ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("鏈嶅姟闄嶇骇鏃朵細鍒囨崲鏈嶅姟IP", app, server1, response); String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("切换服务如果请求成功,可以正常获取到解析结果", ips, + UnitTestUtil.assertIpsEqual("鍒囨崲鏈嶅姟濡傛灉璇锋眰鎴愬姛锛屽彲浠ユ甯歌幏鍙栧埌瑙f瀽缁撴灉", ips, response.getIps()); - // 确认后续请求都是实用切换后的服务 - ServerStatusHelper.requestResolveAnotherHost("切换服务IP后,后续请求都使用此服务", app, + // 纭鍚庣画璇锋眰閮芥槸瀹炵敤鍒囨崲鍚庣殑鏈嶅姟 + ServerStatusHelper.requestResolveAnotherHost("鍒囨崲鏈嶅姟IP鍚庯紝鍚庣画璇锋眰閮戒娇鐢ㄦ鏈嶅姟", app, server1); } /** - * 当现有的服务IP都失败时,更新服务IP + * 褰撶幇鏈夌殑鏈嶅姟IP閮藉け璐ユ椂锛屾洿鏂版湇鍔P */ @Test public void updateServerIpWhenAllServerIpFail() { - // 设置更新服务IP数据 + // 璁剧疆鏇存柊鏈嶅姟IP鏁版嵁 prepareUpdateServerResponse(REGION_DEFAULT, REGION_DEFAULT); - // 前三个server设置为不可用 + // 鍓嶄笁涓猻erver璁剧疆涓轰笉鍙敤 ServerStatusHelper.degradeServer(server, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server1, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server2, app.getRequestHost(), -1); - // 请求 切换服务IP,每次请求 重试1次,请求两次,服务IP 换一轮,触发更新服务IP + // 璇锋眰 鍒囨崲鏈嶅姟IP锛屾瘡娆¤姹?閲嶈瘯1娆★紝璇锋眰涓ゆ锛屾湇鍔P 鎹竴杞紝瑙﹀彂鏇存柊鏈嶅姟IP app.requestResolveHost(app.getRequestHost()); app.waitForAppThread(); app.requestResolveHost(app.getRequestHost()); app.waitForAppThread(); - // 检查服务IP是否已经更新 - ServerStatusHelper.requestResolveAnotherHost("更新服务IP后,使用新服务解析域名", app, + // 妫€鏌ユ湇鍔P鏄惁宸茬粡鏇存柊 + ServerStatusHelper.requestResolveAnotherHost("鏇存柊鏈嶅姟IP鍚庯紝浣跨敤鏂版湇鍔¤В鏋愬煙鍚?, app, server3); } /** - * 当切换两个服务IP解析域名都是超时或者降级时,进入嗅探模式 + * 褰撳垏鎹袱涓湇鍔P瑙f瀽鍩熷悕閮芥槸瓒呮椂鎴栬€呴檷绾ф椂锛岃繘鍏ュ梾鎺㈡ā寮? */ @Test public void whenServerIpsFailTwiceEnterSniffMode() { - // 前两个server设置为不可用 + // 鍓嶄袱涓猻erver璁剧疆涓轰笉鍙敤 ServerStatusHelper.degradeServer(server, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server1, app.getRequestHost(), -1); - // 设置server2 一次请求失败,用于嗅探模式请求 + // 璁剧疆server2 涓€娆¤姹傚け璐ワ紝鐢ㄤ簬鍡呮帰妯″紡璇锋眰 ServerStatusHelper.setError(server2, app.getRequestHost(), 400, "whatever", 1); - // 请求 切换服务IP,重试1次,一共失败两次,触发sniff模式 + // 璇锋眰 鍒囨崲鏈嶅姟IP锛岄噸璇?娆★紝涓€鍏卞け璐ヤ袱娆★紝瑙﹀彂sniff妯″紡 app.requestResolveHost(); app.waitForAppThread(); - // 嗅探模式下请求一次 + // 鍡呮帰妯″紡涓嬭姹備竴娆? app.requestResolveHost(); - // 服务接受到一次请求,返回失败 + // 鏈嶅姟鎺ュ彈鍒颁竴娆¤姹傦紝杩斿洖澶辫触 ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult(app, server2, 400, "whatever", 1, true); - // 没有接收到第二次请求,即没有重试 - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("嗅探模式没有重试", app, server2); - // 再次请求 + // 娌℃湁鎺ユ敹鍒扮浜屾璇锋眰锛屽嵆娌℃湁閲嶈瘯 + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("鍡呮帰妯″紡娌℃湁閲嶈瘯", app, server2); + // 鍐嶆璇锋眰 app.requestResolveHost(app.getRequestHost()); - // 没有接收到第三次请求,即30s内不能重复请求 - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("嗅探模式30s内不能再次请求", app, + // 娌℃湁鎺ユ敹鍒扮涓夋璇锋眰锛屽嵆30s鍐呬笉鑳介噸澶嶈姹? + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("鍡呮帰妯″紡30s鍐呬笉鑳藉啀娆¤姹?, app, server2); } /** - * 嗅探模式下,请求成功,会退出嗅探模式 + * 鍡呮帰妯″紡涓嬶紝璇锋眰鎴愬姛锛屼細閫€鍑哄梾鎺㈡ā寮? */ @Test public void whenResolveHostSuccessExitSniffMode() { - // 前两个server设置为不可用 + // 鍓嶄袱涓猻erver璁剧疆涓轰笉鍙敤 ServerStatusHelper.degradeServer(server, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server1, app.getRequestHost(), -1); - // 设置server2 用于嗅探模式请求 + // 璁剧疆server2 鐢ㄤ簬鍡呮帰妯″紡璇锋眰 - // 请求 切换服务IP,重试1次,一共失败两次,触发sniff模式 + // 璇锋眰 鍒囨崲鏈嶅姟IP锛岄噸璇?娆★紝涓€鍏卞け璐ヤ袱娆★紝瑙﹀彂sniff妯″紡 app.requestResolveHost(app.getRequestHost()); app.waitForAppThread(); - // 嗅探模式下请求一次,恢复正常模式 - ServerStatusHelper.requestResolveAnotherHost("嗅探模式下,正常请求", app, server2); + // 鍡呮帰妯″紡涓嬭姹備竴娆★紝鎭㈠姝e父妯″紡 + ServerStatusHelper.requestResolveAnotherHost("鍡呮帰妯″紡涓嬶紝姝e父璇锋眰", app, server2); - // 清除服务的记录 + // 娓呴櫎鏈嶅姟鐨勮褰? server.getResolveHostServer().cleanRecord(); server1.getResolveHostServer().cleanRecord(); server2.getResolveHostServer().cleanRecord(); - // 设置一次失败 + // 璁剧疆涓€娆″け璐? server2.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), 400, "whatever", 1); app.requestResolveHost(app.getRequestHost()); - // 一次失败,一次正常 两次 - ServerStatusHelper.hasReceiveAppResolveHostRequest("恢复到正常模式后,请求一次。", app, + // 涓€娆″け璐ワ紝涓€娆℃甯?涓ゆ + ServerStatusHelper.hasReceiveAppResolveHostRequest("鎭㈠鍒版甯告ā寮忓悗锛岃姹備竴娆°€?, app, server2, 1); - ServerStatusHelper.hasReceiveAppResolveHostRequest("失败会切换服务,重试一次。", app, + ServerStatusHelper.hasReceiveAppResolveHostRequest("澶辫触浼氬垏鎹㈡湇鍔★紝閲嶈瘯涓€娆°€?, app, server, 1); } /** - * 更新服务IP有时间间隔限制 + * 鏇存柊鏈嶅姟IP鏈夋椂闂撮棿闅旈檺鍒? */ @Test public void setRegionHasTimeInterval() { @@ -490,53 +490,53 @@ public class HttpDnsE2E { prepareUpdateServerResponse(defaultRegion, otherRegion); - // 切换到hk + // 鍒囨崲鍒癶k app.changeRegionTo(otherRegion); - ServerStatusHelper.hasReceiveRegionChange("修改region会触发更新服务IP请求", app, server, + ServerStatusHelper.hasReceiveRegionChange("淇敼region浼氳Е鍙戞洿鏂版湇鍔P璇锋眰", app, server, otherRegion, true); - // 切回default + // 鍒囧洖default app.changeRegionTo(defaultRegion); - ServerStatusHelper.hasReceiveRegionChange("修改region会触发更新服务IP请求", app, server3, + ServerStatusHelper.hasReceiveRegionChange("淇敼region浼氳Е鍙戞洿鏂版湇鍔P璇锋眰", app, server3, defaultRegion, true); - // 再切换到hk,因为请求时间间隔太小,不会触发请求 + // 鍐嶅垏鎹㈠埌hk锛屽洜涓鸿姹傛椂闂撮棿闅斿お灏忥紝涓嶄細瑙﹀彂璇锋眰 app.changeRegionTo(otherRegion); - ServerStatusHelper.hasNotReceiveRegionChange("更新服务IP请求没有进行时间间隔限制", app, + ServerStatusHelper.hasNotReceiveRegionChange("鏇存柊鏈嶅姟IP璇锋眰娌℃湁杩涜鏃堕棿闂撮殧闄愬埗", app, server, otherRegion); - // 再切换回default,因为请求时间间隔太小,不会触发请求 + // 鍐嶅垏鎹㈠洖default锛屽洜涓鸿姹傛椂闂撮棿闅斿お灏忥紝涓嶄細瑙﹀彂璇锋眰 app.changeRegionTo(defaultRegion); - ServerStatusHelper.hasNotReceiveRegionChange("更新服务IP请求没有进行时间间隔限制", app, + ServerStatusHelper.hasNotReceiveRegionChange("鏇存柊鏈嶅姟IP璇锋眰娌℃湁杩涜鏃堕棿闂撮殧闄愬埗", app, server, defaultRegion); - // 缩短请求间隔 + // 缂╃煭璇锋眰闂撮殧 app.setUpdateServerTimeInterval(1000); try { Thread.sleep(1001); } catch (InterruptedException e) { e.printStackTrace(); } - // 切换到hk + // 鍒囨崲鍒癶k app.changeRegionTo(otherRegion); - ServerStatusHelper.hasReceiveRegionChange("更新服务IP请求超过时间间隔才允许请求", app, + ServerStatusHelper.hasReceiveRegionChange("鏇存柊鏈嶅姟IP璇锋眰瓒呰繃鏃堕棿闂撮殧鎵嶅厑璁歌姹?, app, server, otherRegion); - // 切回default + // 鍒囧洖default app.changeRegionTo(defaultRegion); - ServerStatusHelper.hasReceiveRegionChange("更新服务IP请求超过时间间隔才允许请求", app, + ServerStatusHelper.hasReceiveRegionChange("鏇存柊鏈嶅姟IP璇锋眰瓒呰繃鏃堕棿闂撮殧鎵嶅厑璁歌姹?, app, server3, defaultRegion); } /** - * 更新服务IP有时间间隔 + * 鏇存柊鏈嶅姟IP鏈夋椂闂撮棿闅? * * @throws InterruptedException */ @Test public void updateServerIpsHasTimeInterval() throws InterruptedException { - // 设置更新服务IP数据 + // 璁剧疆鏇存柊鏈嶅姟IP鏁版嵁 prepareUpdateServerResponse(REGION_DEFAULT, REGION_DEFAULT); - //设置所有的服务为不可用 + //璁剧疆鎵€鏈夌殑鏈嶅姟涓轰笉鍙敤 ServerStatusHelper.degradeServer(server, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server1, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server2, app.getRequestHost(), -1); @@ -544,45 +544,45 @@ public class HttpDnsE2E { ServerStatusHelper.degradeServer(server4, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server5, app.getRequestHost(), -1); - // 请求 切换服务IP,每次请求 重试1次,一共请求两次,进入嗅探模式 + // 璇锋眰 鍒囨崲鏈嶅姟IP锛屾瘡娆¤姹?閲嶈瘯1娆★紝涓€鍏辫姹備袱娆★紝杩涘叆鍡呮帰妯″紡 app.requestResolveHost(app.getRequestHost()); app.waitForAppThread(); - // 请求一次, 切换服务IP,触发服务IP更新 + // 璇锋眰涓€娆★紝 鍒囨崲鏈嶅姟IP锛岃Е鍙戞湇鍔P鏇存柊 app.requestResolveHost(app.getRequestHost()); - // 检查更新服务IP请求是否触发 - ServerStatusHelper.hasReceiveRegionChange("服务IP切换一遍后,触发服务IP更新", app, server, + // 妫€鏌ユ洿鏂版湇鍔P璇锋眰鏄惁瑙﹀彂 + ServerStatusHelper.hasReceiveRegionChange("鏈嶅姟IP鍒囨崲涓€閬嶅悗锛岃Е鍙戞湇鍔P鏇存柊", app, server, REGION_DEFAULT, true); - // 更新之后,退出嗅探模式, 再来一次 - // 请求 切换服务IP,每次请求 重试1次,一共请求两次,进入嗅探模式 + // 鏇存柊涔嬪悗锛岄€€鍑哄梾鎺㈡ā寮忥紝 鍐嶆潵涓€娆? + // 璇锋眰 鍒囨崲鏈嶅姟IP锛屾瘡娆¤姹?閲嶈瘯1娆★紝涓€鍏辫姹備袱娆★紝杩涘叆鍡呮帰妯″紡 app.requestResolveHost(app.getRequestHost()); app.waitForAppThread(); - // 请求一次, 切换服务IP,触发服务IP更新 + // 璇锋眰涓€娆★紝 鍒囨崲鏈嶅姟IP锛岃Е鍙戞湇鍔P鏇存柊 app.requestResolveHost(app.getRequestHost()); - // 因为间隔过小,不会请求服务器 - ServerStatusHelper.hasNotReceiveRegionChange("更新服务IP没有设置时间间隔", app, server, + // 鍥犱负闂撮殧杩囧皬锛屼笉浼氳姹傛湇鍔″櫒 + ServerStatusHelper.hasNotReceiveRegionChange("鏇存柊鏈嶅姟IP娌℃湁璁剧疆鏃堕棿闂撮殧", app, server, REGION_DEFAULT); - ServerStatusHelper.hasNotReceiveRegionChange("更新服务IP没有设置时间间隔", app, server3, + ServerStatusHelper.hasNotReceiveRegionChange("鏇存柊鏈嶅姟IP娌℃湁璁剧疆鏃堕棿闂撮殧", app, server3, REGION_DEFAULT); - // 缩短时间间隔 + // 缂╃煭鏃堕棿闂撮殧 app.setUpdateServerTimeInterval(1000); - // 缩短嗅探的时间间隔 + // 缂╃煭鍡呮帰鐨勬椂闂撮棿闅? app.setSniffTimeInterval(500); - // 嗅探模式下,连续请求三次,触发服务IP更新 + // 鍡呮帰妯″紡涓嬶紝杩炵画璇锋眰涓夋锛岃Е鍙戞湇鍔P鏇存柊 Thread.sleep(500); app.requestResolveHost(app.getRequestHost()); Thread.sleep(500); app.requestResolveHost(app.getRequestHost()); Thread.sleep(500); app.requestResolveHost(app.getRequestHost()); - // 确认服务IP请求触发 + // 纭鏈嶅姟IP璇锋眰瑙﹀彂 ServerStatusHelper.hasReceiveRegionChange( - "更新服务IP超过时间间隔才能请求,如果在嗅探模式下,也需要缩短嗅探的时间间隔", app, + "鏇存柊鏈嶅姟IP瓒呰繃鏃堕棿闂撮殧鎵嶈兘璇锋眰,濡傛灉鍦ㄥ梾鎺㈡ā寮忎笅锛屼篃闇€瑕佺缉鐭梾鎺㈢殑鏃堕棿闂撮殧", app, server3, REGION_DEFAULT); } /** - * 更新服务IP请求失败,会切换服务尝试 + * 鏇存柊鏈嶅姟IP璇锋眰澶辫触锛屼細鍒囨崲鏈嶅姟灏濊瘯 */ @Test public void updateServerFailWhenRetryAnotherServer() { @@ -593,24 +593,24 @@ public class HttpDnsE2E { RandomValue.randomIpv6s(), new int[] {server3.getPort(), server4.getPort(), server5.getPort()}, RandomValue.randomPorts()); - // 第一个服务失败 + // 绗竴涓湇鍔″け璐? server.getServerIpsServer().preSetRequestResponse(hkRegion, 400, "whatever", 1); server1.getServerIpsServer().preSetRequestResponse(hkRegion, 200, updateServerResponse, -1); server2.getServerIpsServer().preSetRequestResponse(hkRegion, 200, updateServerResponse, -1); - // 触发服务IP更新,第一次失败,使用第二个服务 + // 瑙﹀彂鏈嶅姟IP鏇存柊锛岀涓€娆″け璐ワ紝浣跨敤绗簩涓湇鍔? app.changeRegionTo(hkRegion); - ServerStatusHelper.hasReceiveRegionChange("服务收到更新请求", app, server, hkRegion); - ServerStatusHelper.hasReceiveRegionChange("更新服务IP时,失败了但是没有遍历尝试其它服务", + ServerStatusHelper.hasReceiveRegionChange("鏈嶅姟鏀跺埌鏇存柊璇锋眰", app, server, hkRegion); + ServerStatusHelper.hasReceiveRegionChange("鏇存柊鏈嶅姟IP鏃讹紝澶辫触浜嗕絾鏄病鏈夐亶鍘嗗皾璇曞叾瀹冩湇鍔?, app, server1, hkRegion); ServerStatusHelper.hasNotReceiveRegionChange( - "更新服务IP时,一旦有一个成功,就不会尝试其它服务了", app, server2, hkRegion); + "鏇存柊鏈嶅姟IP鏃讹紝涓€鏃︽湁涓€涓垚鍔燂紝灏变笉浼氬皾璇曞叾瀹冩湇鍔′簡", app, server2, hkRegion); } /** - * 当前的服务更新服务IP都失败了,就使用初始服务IP尝试 + * 褰撳墠鐨勬湇鍔℃洿鏂版湇鍔P閮藉け璐ヤ簡锛屽氨浣跨敤鍒濆鏈嶅姟IP灏濊瘯 */ @Test public void updateServerAllFailWhenRetryInitServer() { @@ -620,58 +620,58 @@ public class HttpDnsE2E { String defaultRegion = REGION_DEFAULT; prepareUpdateServerResponseForGroup1(otherRegion); - // 设置服务不可用 + // 璁剧疆鏈嶅姟涓嶅彲鐢? server3.getServerIpsServer().preSetRequestResponse(defaultRegion, 400, "whatever", 1); server4.getServerIpsServer().preSetRequestResponse(defaultRegion, 400, "whatever", 1); server5.getServerIpsServer().preSetRequestResponse(defaultRegion, 400, "whatever", 1); - // 先更新一次服务IP + // 鍏堟洿鏂颁竴娆℃湇鍔P app.changeRegionTo(otherRegion); - ServerStatusHelper.hasReceiveRegionChange("服务收到更新服务IP请求", app, server, + ServerStatusHelper.hasReceiveRegionChange("鏈嶅姟鏀跺埌鏇存柊鏈嶅姟IP璇锋眰", app, server, otherRegion); - // 再触发一次服务IP更新,此时全部失败,会切换会初始服务请求 + // 鍐嶈Е鍙戜竴娆℃湇鍔P鏇存柊锛屾鏃跺叏閮ㄥけ璐ワ紝浼氬垏鎹細鍒濆鏈嶅姟璇锋眰 app.changeRegionTo(defaultRegion); - ServerStatusHelper.hasReceiveRegionChange("更新服务IP都失败时,没有切换回初始化服务IP尝试", + ServerStatusHelper.hasReceiveRegionChange("鏇存柊鏈嶅姟IP閮藉け璐ユ椂锛屾病鏈夊垏鎹㈠洖鍒濆鍖栨湇鍔P灏濊瘯", app, server, defaultRegion); } /** - * 不同的account使用不同的实例,相互之间不影响 + * 涓嶅悓鐨刟ccount浣跨敤涓嶅悓鐨勫疄渚嬶紝鐩镐簰涔嬮棿涓嶅奖鍝? */ @Test public void differentAcountUseDifferentInstance() { - // 确认一般的域名解析请求都正常 - ServerStatusHelper.requestResolveAnotherHost("应用0域名解析服务正常", app, server); - ServerStatusHelper.requestResolveAnotherHost("应用1域名解析服务正常", app1, server); + // 纭涓€鑸殑鍩熷悕瑙f瀽璇锋眰閮芥甯? + ServerStatusHelper.requestResolveAnotherHost("搴旂敤0鍩熷悕瑙f瀽鏈嶅姟姝e父", app, server); + ServerStatusHelper.requestResolveAnotherHost("搴旂敤1鍩熷悕瑙f瀽鏈嶅姟姝e父", app1, server); String defaultRegion = REGION_DEFAULT; String otherRegion = Constants.REGION_HK == REGION_DEFAULT ? Constants.REGION_MAINLAND : Constants.REGION_HK; prepareUpdateServerResponse(defaultRegion, otherRegion); - // 应用0切换到 hk + // 搴旂敤0鍒囨崲鍒?hk app.changeRegionTo(otherRegion); - ServerStatusHelper.hasReceiveRegionChange("应用0切换到 其它region", app, server, + ServerStatusHelper.hasReceiveRegionChange("搴旂敤0鍒囨崲鍒?鍏跺畠region", app, server, otherRegion); - // 应用1正常使用 - ServerStatusHelper.requestResolveAnotherHost("应用1不受应用0切region影响", app1, server); + // 搴旂敤1姝e父浣跨敤 + ServerStatusHelper.requestResolveAnotherHost("搴旂敤1涓嶅彈搴旂敤0鍒噐egion褰卞搷", app1, server); ServerStatusHelper.degradeServer(server, app1.getRequestHost(), -1); ServerStatusHelper.degradeServer(server1, app1.getRequestHost(), -1); ServerStatusHelper.setError(server2, app1.getRequestHost(), 400, "whatever", -1); - // 请求,服务降级,进入嗅探模式 + // 璇锋眰锛屾湇鍔¢檷绾э紝杩涘叆鍡呮帰妯″紡 app1.requestResolveHost(app1.getRequestHost()); app1.waitForAppThread(); - // 请求失败, 短时间不能再次嗅探请求 + // 璇锋眰澶辫触, 鐭椂闂翠笉鑳藉啀娆″梾鎺㈣姹? app1.requestResolveHost(app1.getRequestHost()); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult(app1, server2, 400, "whatever", 1, true); app1.requestResolveHost(app1.getRequestHost()); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("短时间内无法再次嗅探请求", app1, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("鐭椂闂村唴鏃犳硶鍐嶆鍡呮帰璇锋眰", app1, server2); - ServerStatusHelper.requestResolveAnotherHost("应用0不受应用1嗅探状态影响", app, server3); + ServerStatusHelper.requestResolveAnotherHost("搴旂敤0涓嶅彈搴旂敤1鍡呮帰鐘舵€佸奖鍝?, app, server3); app1.changeRegionTo(otherRegion); app1.waitForAppThread(); @@ -685,18 +685,18 @@ public class HttpDnsE2E { app.requestResolveHost(sameHost); app.waitForAppThread(); - assertThat("应用0获取自己的结果", server3.getResolveHostServer() + assertThat("搴旂敤0鑾峰彇鑷繁鐨勭粨鏋?, server3.getResolveHostServer() .hasRequestForArgWithResult(sameHost, response, 1, true)); app1.requestResolveHost(sameHost); app1.waitForAppThread(); - assertThat("应用1获取自己的结果", server3.getResolveHostServer() + assertThat("搴旂敤1鑾峰彇鑷繁鐨勭粨鏋?, server3.getResolveHostServer() .hasRequestForArgWithResult(sameHost, response1, 1, true)); - assertThat("应用0、应用1结果不干扰", app.requestResolveHost(sameHost), + assertThat("搴旂敤0銆佸簲鐢?缁撴灉涓嶅共鎵?, app.requestResolveHost(sameHost), Matchers.not(Matchers.arrayContaining(app1.requestResolveHost(sameHost)))); } /** - * 相同的账号实用相同的实例 + * 鐩稿悓鐨勮处鍙峰疄鐢ㄧ浉鍚岀殑瀹炰緥 */ @Test public void sameAccountUseSameInstance() { @@ -704,7 +704,7 @@ public class HttpDnsE2E { } /** - * ipv6支持测试 + * ipv6鏀寔娴嬭瘯 */ @Test public void supportIpv6Resolve() { @@ -714,24 +714,24 @@ public class HttpDnsE2E { ResolveHostServer.ResolveHostArg.create(app.getRequestHost(), RequestIpType.v6), response, -1); - // 请求域名解析,并返回空结果,因为是接口是异步的,所以第一次请求一个域名返回是空 + // 璇锋眰鍩熷悕瑙f瀽锛屽苟杩斿洖绌虹粨鏋滐紝鍥犱负鏄帴鍙f槸寮傛鐨勶紝鎵€浠ョ涓€娆¤姹備竴涓煙鍚嶈繑鍥炴槸绌? String[] ipv6s = app.requestResolveHostForIpv6(); - UnitTestUtil.assertIpsEmpty("解析域名,没有缓存时,返回空", ipv6s); - // 验证服务器收到了请求 + UnitTestUtil.assertIpsEmpty("瑙f瀽鍩熷悕锛屾病鏈夌紦瀛樻椂锛岃繑鍥炵┖", ipv6s); + // 楠岃瘉鏈嶅姟鍣ㄦ敹鍒颁簡璇锋眰 ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "服务应该收到ipv6域名解析请求", app, + "鏈嶅姟搴旇鏀跺埌ipv6鍩熷悕瑙f瀽璇锋眰", app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost(), RequestIpType.v6), server, response, 1, true); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? ipv6s = app.requestResolveHostForIpv6(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("有缓存,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("鏈夌紦瀛橈紝涓嶄細璇锋眰鏈嶅姟鍣?, app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost(), RequestIpType.v6), server); - UnitTestUtil.assertIpsEqual("解析结果是服务返回的值", ipv6s, response.getIpsV6()); + UnitTestUtil.assertIpsEqual("瑙f瀽缁撴灉鏄湇鍔¤繑鍥炵殑鍊?, ipv6s, response.getIpsV6()); } /** - * 测试对SDNS的支持 + * 娴嬭瘯瀵筍DNS鐨勬敮鎸? */ @Test public void testSDNS() { @@ -751,26 +751,26 @@ public class HttpDnsE2E { extras), sdnsResponse, -1); HTTPDNSResult result = app.requestSDNSResolveHost(extras, cacheKey); - UnitTestUtil.assertIpsEmpty("和其它域名解析一样,sdns解析第一次没有缓存时,返回空", + UnitTestUtil.assertIpsEmpty("鍜屽叾瀹冨煙鍚嶈В鏋愪竴鏍凤紝sdns瑙f瀽绗竴娆℃病鏈夌紦瀛樻椂锛岃繑鍥炵┖", result.getIps()); - ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("服务器应该接收到sdns请求", + ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("鏈嶅姟鍣ㄥ簲璇ユ帴鏀跺埌sdns璇锋眰", app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost(), RequestIpType.v4, extras), server, sdnsResponse, 1, true); result = app.requestSDNSResolveHost(extras, cacheKey); - UnitTestUtil.assertIpsEqual("sdns解析结果和预期值一致", result.getIps(), + UnitTestUtil.assertIpsEqual("sdns瑙f瀽缁撴灉鍜岄鏈熷€间竴鑷?, result.getIps(), sdnsResponse.getIps()); String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("解析时没有缓存,返回空", ips); - ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("一般解析和sdns解析互不干扰", + UnitTestUtil.assertIpsEmpty("瑙f瀽鏃舵病鏈夌紦瀛橈紝杩斿洖绌?, ips); + ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("涓€鑸В鏋愬拰sdns瑙f瀽浜掍笉骞叉壈", app, server, normalResponse); ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("一般解析结果和预期一致", ips, normalResponse.getIps()); + UnitTestUtil.assertIpsEqual("涓€鑸В鏋愮粨鏋滃拰棰勬湡涓€鑷?, ips, normalResponse.getIps()); } /** - * 测试SDNS全局参数 + * 娴嬭瘯SDNS鍏ㄥ眬鍙傛暟 */ @Test public void testGlobalParamsSDNS() { @@ -787,21 +787,21 @@ public class HttpDnsE2E { String cacheKey1 = "sdns1"; String cacheKey2 = "sdns2"; - // 一般sdns结果 + // 涓€鑸瑂dns缁撴灉 ResolveHostResponse sdnsResponse = ResolveHostServer.randomResolveHostResponse( app.getRequestHost()); server.getResolveHostServer().preSetRequestResponse( ResolveHostServer.ResolveHostArg.create(app.getRequestHost(), RequestIpType.v4, extras), sdnsResponse, -1); - // 仅global参数 + // 浠単lobal鍙傛暟 ResolveHostResponse gsdnsResponse = ResolveHostServer.randomResolveHostResponse( app.getRequestHost()); server.getResolveHostServer().preSetRequestResponse( ResolveHostServer.ResolveHostArg.create(app.getRequestHost(), RequestIpType.v4, globalParams), gsdnsResponse, -1); - // global参数 + 一般参数 + // global鍙傛暟 + 涓€鑸弬鏁? HashMap all = new HashMap(); all.putAll(globalParams); all.putAll(extras); @@ -814,32 +814,32 @@ public class HttpDnsE2E { app.requestSDNSResolveHost(extras, cacheKey); app.waitForAppThread(); HTTPDNSResult result = app.requestSDNSResolveHost(extras, cacheKey); - UnitTestUtil.assertIpsEqual("sdns解析结果应该和预期值一致", result.getIps(), + UnitTestUtil.assertIpsEqual("sdns瑙f瀽缁撴灉搴旇鍜岄鏈熷€间竴鑷?, result.getIps(), sdnsResponse.getIps()); app.setGlobalParams(globalParams); app.requestSDNSResolveHost(null, globalCacheKey); app.waitForAppThread(); HTTPDNSResult gResult = app.requestSDNSResolveHost(null, globalCacheKey); - UnitTestUtil.assertIpsEqual("仅global参数,sdns解析结果和预期值一致", gResult.getIps(), + UnitTestUtil.assertIpsEqual("浠単lobal鍙傛暟锛宻dns瑙f瀽缁撴灉鍜岄鏈熷€间竴鑷?, gResult.getIps(), gsdnsResponse.getIps()); app.requestSDNSResolveHost(extras, cacheKey1); app.waitForAppThread(); HTTPDNSResult result1 = app.requestSDNSResolveHost(extras, cacheKey1); - UnitTestUtil.assertIpsEqual("global参数+定制参数,sdns解析结果和预期值一致", + UnitTestUtil.assertIpsEqual("global鍙傛暟+瀹氬埗鍙傛暟锛宻dns瑙f瀽缁撴灉鍜岄鏈熷€间竴鑷?, result1.getIps(), sdnsResponse1.getIps()); app.cleanGlobalParams(); app.requestSDNSResolveHost(extras, cacheKey2); app.waitForAppThread(); HTTPDNSResult result2 = app.requestSDNSResolveHost(extras, cacheKey2); - UnitTestUtil.assertIpsEqual("清楚global参数后,sdns解析结果和仅定制参数的解析结果一致", + UnitTestUtil.assertIpsEqual("娓呮global鍙傛暟鍚庯紝sdns瑙f瀽缁撴灉鍜屼粎瀹氬埗鍙傛暟鐨勮В鏋愮粨鏋滀竴鑷?, result2.getIps(), sdnsResponse.getIps()); } /** - * 测试SDNS解析ipv6 + * 娴嬭瘯SDNS瑙f瀽ipv6 */ @Test public void testSDNSForIpv6() { @@ -855,19 +855,19 @@ public class HttpDnsE2E { extras), sdnsResponse, -1); HTTPDNSResult result = app.requestSDNSResolveHostForIpv6(extras, cacheKey); - UnitTestUtil.assertIpsEmpty("和其它域名解析一样,sdns解析第一次没有缓存时,返回空", + UnitTestUtil.assertIpsEmpty("鍜屽叾瀹冨煙鍚嶈В鏋愪竴鏍凤紝sdns瑙f瀽绗竴娆℃病鏈夌紦瀛樻椂锛岃繑鍥炵┖", result.getIps()); - ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("服务器应该接收到sdns请求", + ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("鏈嶅姟鍣ㄥ簲璇ユ帴鏀跺埌sdns璇锋眰", app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost(), RequestIpType.v6, extras), server, sdnsResponse, 1, true); result = app.requestSDNSResolveHostForIpv6(extras, cacheKey); - UnitTestUtil.assertIpsEqual("sdns解析结果和预期值一致", result.getIpv6s(), + UnitTestUtil.assertIpsEqual("sdns瑙f瀽缁撴灉鍜岄鏈熷€间竴鑷?, result.getIpv6s(), sdnsResponse.getIpsV6()); } /** - * 预解析ipv4 + * 棰勮В鏋恑pv4 */ @Test public void preResolveHostForIpv4() { @@ -891,16 +891,16 @@ public class HttpDnsE2E { String[] ips1 = app.requestResolveHost(host1); String[] ips2 = app.requestResolveHost(host2); String[] ips3 = app.requestResolveHost(host3); - UnitTestUtil.assertIpsEqual("预解析ipv4之后,可以直接获取解析结果", ips1, + UnitTestUtil.assertIpsEqual("棰勮В鏋恑pv4涔嬪悗锛屽彲浠ョ洿鎺ヨ幏鍙栬В鏋愮粨鏋?, ips1, response.getHostItem(host1, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析ipv4之后,可以直接获取解析结果", ips2, + UnitTestUtil.assertIpsEqual("棰勮В鏋恑pv4涔嬪悗锛屽彲浠ョ洿鎺ヨ幏鍙栬В鏋愮粨鏋?, ips2, response.getHostItem(host2, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析ipv4之后,可以直接获取解析结果", ips3, + UnitTestUtil.assertIpsEqual("棰勮В鏋恑pv4涔嬪悗锛屽彲浠ョ洿鎺ヨ幏鍙栬В鏋愮粨鏋?, ips3, response.getHostItem(host3, RequestIpType.v4).getIps()); } /** - * 预解析ipv6 + * 棰勮В鏋恑pv6 */ @Test public void preResolveHostForIpv6() { @@ -925,16 +925,16 @@ public class HttpDnsE2E { String[] ips1 = app.requestResolveHostForIpv6(host1); String[] ips2 = app.requestResolveHostForIpv6(host2); String[] ips3 = app.requestResolveHostForIpv6(host3); - UnitTestUtil.assertIpsEqual("预解析ipv6之后,可以直接获取解析结果", ips1, + UnitTestUtil.assertIpsEqual("棰勮В鏋恑pv6涔嬪悗锛屽彲浠ョ洿鎺ヨ幏鍙栬В鏋愮粨鏋?, ips1, response.getHostItem(host1, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析ipv6之后,可以直接获取解析结果", ips2, + UnitTestUtil.assertIpsEqual("棰勮В鏋恑pv6涔嬪悗锛屽彲浠ョ洿鎺ヨ幏鍙栬В鏋愮粨鏋?, ips2, response.getHostItem(host2, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析ipv6之后,可以直接获取解析结果", ips3, + UnitTestUtil.assertIpsEqual("棰勮В鏋恑pv6涔嬪悗锛屽彲浠ョ洿鎺ヨ幏鍙栬В鏋愮粨鏋?, ips3, response.getHostItem(host3, RequestIpType.v6).getIps()); } /** - * 预解析 4 6 + * 棰勮В鏋?4 6 */ @Test public void preResolveHost() { @@ -958,26 +958,26 @@ public class HttpDnsE2E { String[] ips1 = app.requestResolveHost(host1); String[] ips2 = app.requestResolveHost(host2); String[] ips3 = app.requestResolveHost(host3); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips1, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips1, response.getHostItem(host1, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips2, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips2, response.getHostItem(host2, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips3, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips3, response.getHostItem(host3, RequestIpType.v4).getIps()); String[] ips4 = app.requestResolveHostForIpv6(host1); String[] ips5 = app.requestResolveHostForIpv6(host2); String[] ips6 = app.requestResolveHostForIpv6(host3); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips4, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips4, response.getHostItem(host1, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips5, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips5, response.getHostItem(host2, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips6, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips6, response.getHostItem(host3, RequestIpType.v6).getIps()); } /** - * 当预解析域名超过5个场景 + * 褰撻瑙f瀽鍩熷悕瓒呰繃5涓満鏅? */ @Test public void preResolveHostMoreThan5() { @@ -1024,19 +1024,19 @@ public class HttpDnsE2E { String[] ips5 = app.requestResolveHost(host5); String[] ips6 = app.requestResolveHost(host6); String[] ips7 = app.requestResolveHost(host7); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips1, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips1, response1.getHostItem(host1, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips2, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips2, response1.getHostItem(host2, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips3, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips3, response1.getHostItem(host3, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips4, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips4, response1.getHostItem(host4, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ips5, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips5, response1.getHostItem(host5, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("超过5个,预解析之后,可以直接获取解析结果", ips6, + UnitTestUtil.assertIpsEqual("瓒呰繃5涓紝棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips6, response2.getHostItem(host6, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("超过5个,预解析之后,可以直接获取解析结果", ips7, + UnitTestUtil.assertIpsEqual("瓒呰繃5涓紝棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ips7, response2.getHostItem(host7, RequestIpType.v4).getIps()); String[] ipv6s1 = app.requestResolveHostForIpv6(host1); @@ -1046,24 +1046,24 @@ public class HttpDnsE2E { String[] ipv6s5 = app.requestResolveHostForIpv6(host5); String[] ipv6s6 = app.requestResolveHostForIpv6(host6); String[] ipv6s7 = app.requestResolveHostForIpv6(host7); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ipv6s1, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ipv6s1, response1.getHostItem(host1, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ipv6s2, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ipv6s2, response1.getHostItem(host2, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ipv6s3, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ipv6s3, response1.getHostItem(host3, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ipv6s4, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ipv6s4, response1.getHostItem(host4, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("预解析之后,可以直接获取解析结果", ipv6s5, + UnitTestUtil.assertIpsEqual("棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ipv6s5, response1.getHostItem(host5, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("超过5个,预解析之后,可以直接获取解析结果", ipv6s6, + UnitTestUtil.assertIpsEqual("瓒呰繃5涓紝棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ipv6s6, response2.getHostItem(host6, RequestIpType.v6).getIps()); - UnitTestUtil.assertIpsEqual("超过5个,预解析之后,可以直接获取解析结果", ipv6s7, + UnitTestUtil.assertIpsEqual("瓒呰繃5涓紝棰勮В鏋愪箣鍚庯紝鍙互鐩存帴鑾峰彇瑙f瀽缁撴灉", ipv6s7, response2.getHostItem(host7, RequestIpType.v6).getIps()); } /** - * 测试 ttl 有效性 + * 娴嬭瘯 ttl 鏈夋晥鎬? * * @throws InterruptedException */ @@ -1073,37 +1073,37 @@ public class HttpDnsE2E { ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse( app.getRequestHost(), 1); server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, -1); - // 请求域名解析,并返回空结果,因为是接口是异步的,所以第一次请求一个域名返回是空 + // 璇锋眰鍩熷悕瑙f瀽锛屽苟杩斿洖绌虹粨鏋滐紝鍥犱负鏄帴鍙f槸寮傛鐨勶紝鎵€浠ョ涓€娆¤姹備竴涓煙鍚嶈繑鍥炴槸绌? String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); - // 验证服务器收到了请求 + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); + // 楠岃瘉鏈嶅姟鍣ㄦ敹鍒颁簡璇锋眰 ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "当没有缓存时,会异步请求服务器", app, + "褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost()), server, response, 1, true); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", response.getIps(), ips); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, response.getIps(), ips); Thread.sleep(1000); - // ttl 过期后请求ip + // ttl 杩囨湡鍚庤姹俰p ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("ip过期后,返回空", ips); + UnitTestUtil.assertIpsEmpty("ip杩囨湡鍚庯紝杩斿洖绌?, ips); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "ttl过期后,再次请求会触发网络请求", app, + "ttl杩囨湡鍚庯紝鍐嶆璇锋眰浼氳Е鍙戠綉缁滆姹?, app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost()), server, response, 1, true); - // 再次请求,获取再次请求服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栧啀娆¤姹傛湇鍔″櫒杩斿洖鐨勭粨鏋? ips = app.requestResolveHost(); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", response.getIps(), ips); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, response.getIps(), ips); } /** - * 测试允许返回过期IP功能 + * 娴嬭瘯鍏佽杩斿洖杩囨湡IP鍔熻兘 * * @throws InterruptedException */ @@ -1116,196 +1116,196 @@ public class HttpDnsE2E { app.getRequestHost()); server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, 1); server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response1, -1); - // 请求域名解析,并返回空结果,因为是接口是异步的,所以第一次请求一个域名返回是空 + // 璇锋眰鍩熷悕瑙f瀽锛屽苟杩斿洖绌虹粨鏋滐紝鍥犱负鏄帴鍙f槸寮傛鐨勶紝鎵€浠ョ涓€娆¤姹備竴涓煙鍚嶈繑鍥炴槸绌? String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); app.waitForAppThread(); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? app.requestResolveHost(); Thread.sleep(1000); - // ttl 过期后请求ip + // ttl 杩囨湡鍚庤姹俰p ips = app.requestResolveHost(); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("启用过期IP,请求时域名过期,仍会返回过期IP", response.getIps(), + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("鍚敤杩囨湡IP锛岃姹傛椂鍩熷悕杩囨湡锛屼粛浼氳繑鍥炶繃鏈烮P", response.getIps(), ips); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "ttl过期后,再次请求会触发网络请求", app, + "ttl杩囨湡鍚庯紝鍐嶆璇锋眰浼氳Е鍙戠綉缁滆姹?, app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost()), server, response1 , 1, true); - // 再次请求,获取再次请求服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栧啀娆¤姹傛湇鍔″櫒杩斿洖鐨勭粨鏋? ips = app.requestResolveHost(); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", response1.getIps(), ips); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, response1.getIps(), ips); } /** - * 当前服务节点的状态会缓存,比如当前正使用哪个服务节点 + * 褰撳墠鏈嶅姟鑺傜偣鐨勭姸鎬佷細缂撳瓨锛屾瘮濡傚綋鍓嶆浣跨敤鍝釜鏈嶅姟鑺傜偣 */ @Test public void testServerCache() { - // 先通过请求失败,切换一次服务IP + // 鍏堥€氳繃璇锋眰澶辫触锛屽垏鎹竴娆℃湇鍔P ServerStatusHelper.degradeServer(server, app.getRequestHost(), 1); ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse( app.getRequestHost()); server1.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, 1); app.requestResolveHost(); ServerStatusHelper.hasReceiveAppResolveHostRequestWithDegrade(app, server); - ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("服务降级时会切换服务IP", + ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("鏈嶅姟闄嶇骇鏃朵細鍒囨崲鏈嶅姟IP", app, server1, response); String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("切换服务如果请求成功,可以正常获取到解析结果", ips, + UnitTestUtil.assertIpsEqual("鍒囨崲鏈嶅姟濡傛灉璇锋眰鎴愬姛锛屽彲浠ユ甯歌幏鍙栧埌瑙f瀽缁撴灉", ips, response.getIps()); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); - // 确认后续请求都是使用切换后的服务 - ServerStatusHelper.requestResolveAnotherHost("读取缓存应该是直接使用切换后的服务", app, + // 纭鍚庣画璇锋眰閮芥槸浣跨敤鍒囨崲鍚庣殑鏈嶅姟 + ServerStatusHelper.requestResolveAnotherHost("璇诲彇缂撳瓨搴旇鏄洿鎺ヤ娇鐢ㄥ垏鎹㈠悗鐨勬湇鍔?, app, server1); } /** - * 测试 当前服务节点不是初始服务节点的 状态缓存 + * 娴嬭瘯 褰撳墠鏈嶅姟鑺傜偣涓嶆槸鍒濆鏈嶅姟鑺傜偣鐨?鐘舵€佺紦瀛? */ @Test public void testServerCacheWhenServerIsNotInitServer() { - // 先通过请求失败,切换服务IP + // 鍏堥€氳繃璇锋眰澶辫触锛屽垏鎹㈡湇鍔P prepareUpdateServerResponse(REGION_DEFAULT, REGION_DEFAULT); - // 前三个server设置为不可用 + // 鍓嶄笁涓猻erver璁剧疆涓轰笉鍙敤 ServerStatusHelper.degradeServer(server, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server1, app.getRequestHost(), -1); ServerStatusHelper.degradeServer(server2, app.getRequestHost(), -1); - // 请求 切换服务IP,每次请求 重试1次,请求两次,服务IP 换一轮,触发更新服务IP + // 璇锋眰 鍒囨崲鏈嶅姟IP锛屾瘡娆¤姹?閲嶈瘯1娆★紝璇锋眰涓ゆ锛屾湇鍔P 鎹竴杞紝瑙﹀彂鏇存柊鏈嶅姟IP app.requestResolveHost(app.getRequestHost()); app.waitForAppThread(); app.requestResolveHost(app.getRequestHost()); app.waitForAppThread(); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); - // 检查服务IP是否已经更新 - ServerStatusHelper.requestResolveAnotherHost("更新服务IP后,使用新服务解析域名", app, + // 妫€鏌ユ湇鍔P鏄惁宸茬粡鏇存柊 + ServerStatusHelper.requestResolveAnotherHost("鏇存柊鏈嶅姟IP鍚庯紝浣跨敤鏂版湇鍔¤В鏋愬煙鍚?, app, server3); } /** - * 默认未开启IP缓存,下次开启IP缓存,也读取不到数据 + * 榛樿鏈紑鍚疘P缂撳瓨锛屼笅娆″紑鍚疘P缂撳瓨锛屼篃璇诲彇涓嶅埌鏁版嵁 */ @Test public void testCacheControll() { - // 先发起一些请求,因为没有开启缓存,所以不会缓存 + // 鍏堝彂璧蜂竴浜涜姹傦紝鍥犱负娌℃湁寮€鍚紦瀛橈紝鎵€浠ヤ笉浼氱紦瀛? String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); - ServerStatusHelper.hasReceiveAppResolveHostRequest("当没有缓存时,会异步请求服务器", app, + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); + ServerStatusHelper.hasReceiveAppResolveHostRequest("褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, server, 1); String[] serverResponseIps = ServerStatusHelper.getServerResponseIps(app, server); ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", serverResponseIps, ips); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, serverResponseIps, ips); - // 重置实例 + // 閲嶇疆瀹炰緥 HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(false); ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("之前没有缓存,应该返回空", ips); - ServerStatusHelper.hasReceiveAppResolveHostRequest("当没有缓存时,会异步请求服务器", app, + UnitTestUtil.assertIpsEmpty("涔嬪墠娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); + ServerStatusHelper.hasReceiveAppResolveHostRequest("褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, server, 1); } /** - * 开启缓存的情况下, IP会缓存到本地 - * 下次读取时 如果 标记clean,会在读取缓存后,删除缓存 + * 寮€鍚紦瀛樼殑鎯呭喌涓嬶紝 IP浼氱紦瀛樺埌鏈湴 + * 涓嬫璇诲彇鏃?濡傛灉 鏍囪clean锛屼細鍦ㄨ鍙栫紦瀛樺悗锛屽垹闄ょ紦瀛? */ @Test public void testCacheClean() { app.enableCache(false); - // 先发起一些请求,缓存一些Ip结果 + // 鍏堝彂璧蜂竴浜涜姹傦紝缂撳瓨涓€浜汭p缁撴灉 String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); - ServerStatusHelper.hasReceiveAppResolveHostRequest("当没有缓存时,会异步请求服务器", app, + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); + ServerStatusHelper.hasReceiveAppResolveHostRequest("褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, server, 1); String[] serverResponseIps = ServerStatusHelper.getServerResponseIps(app, server); ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", serverResponseIps, ips); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, serverResponseIps, ips); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(true); - // 此时返回缓存,然后由于是数据库读取的,触发一次解析 + // 姝ゆ椂杩斿洖缂撳瓨锛岀劧鍚庣敱浜庢槸鏁版嵁搴撹鍙栫殑锛岃Е鍙戜竴娆¤В鏋? ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("解析域名返回缓存结果", serverResponseIps, ips); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖缂撳瓨缁撴灉", serverResponseIps, ips); app.waitForAppThread(); - // 由于从数据库读取的结果会触发一次解析更新,所以此处我们在此清除数据库缓存 + // 鐢变簬浠庢暟鎹簱璇诲彇鐨勭粨鏋滀細瑙﹀彂涓€娆¤В鏋愭洿鏂帮紝鎵€浠ユ澶勬垜浠湪姝ゆ竻闄ゆ暟鎹簱缂撳瓨 app.enableCache(true); server.getResolveHostServer().cleanRecord(); - // 重置实例, + // 閲嶇疆瀹炰緥锛? HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(false); ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("上次读取缓存时把缓存清除了,应该返回空", ips); - ServerStatusHelper.hasReceiveAppResolveHostRequest("当没有缓存时,会异步请求服务器", app, + UnitTestUtil.assertIpsEmpty("涓婃璇诲彇缂撳瓨鏃舵妸缂撳瓨娓呴櫎浜嗭紝搴旇杩斿洖绌?, ips); + ServerStatusHelper.hasReceiveAppResolveHostRequest("褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, server, 1); } /** - * 测试 IP 缓存 + * 娴嬭瘯 IP 缂撳瓨 */ @Test public void testIpCache() { app.enableCache(false); - // 先发起一些请求,缓存一些Ip结果 + // 鍏堝彂璧蜂竴浜涜姹傦紝缂撳瓨涓€浜汭p缁撴灉 String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); - ServerStatusHelper.hasReceiveAppResolveHostRequest("当没有缓存时,会异步请求服务器", app, + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); + ServerStatusHelper.hasReceiveAppResolveHostRequest("褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, server, 1); String[] serverResponseIps = ServerStatusHelper.getServerResponseIps(app, server); ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", serverResponseIps, ips); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, serverResponseIps, ips); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(false); ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("解析域名返回缓存结果", serverResponseIps, ips); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖缂撳瓨缁撴灉", serverResponseIps, ips); } /** - * 1. 当开启IP缓存功能时,从缓存读取的IP,即使不允许返回过期IP,也会返回 - * 2. 当IP更新后,不再认为是从本地缓存读取,过期了,就返回空 + * 1. 褰撳紑鍚疘P缂撳瓨鍔熻兘鏃讹紝浠庣紦瀛樿鍙栫殑IP锛屽嵆浣夸笉鍏佽杩斿洖杩囨湡IP锛屼篃浼氳繑鍥? + * 2. 褰揑P鏇存柊鍚庯紝涓嶅啀璁や负鏄粠鏈湴缂撳瓨璇诲彇锛岃繃鏈熶簡锛屽氨杩斿洖绌? * * @throws InterruptedException */ @@ -1313,7 +1313,7 @@ public class HttpDnsE2E { public void testIpCacheWhenExpired() throws InterruptedException { app.enableCache(false); app.enableExpiredIp(false); - // 先发起一些请求,缓存一些Ip结果 + // 鍏堝彂璧蜂竴浜涜姹傦紝缂撳瓨涓€浜汭p缁撴灉 ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse( app.getRequestHost(), 1); ResolveHostResponse response1 = ResolveHostServer.randomResolveHostResponse( @@ -1321,41 +1321,41 @@ public class HttpDnsE2E { server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, 1); server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response1, -1); String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "当没有缓存时,会异步请求服务器", app, + "褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost()), server, response, 1, true); ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", response.getIps(), ips); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, response.getIps(), ips); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); Thread.sleep(1000); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(false); app.enableExpiredIp(false); ips = app.requestResolveHost(); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "本地缓存过期时,会触发网络请求", app, server, response1); - UnitTestUtil.assertIpsEqual("本地缓存即使过期也会返回ip", ips, response.getIps()); + "鏈湴缂撳瓨杩囨湡鏃讹紝浼氳Е鍙戠綉缁滆姹?, app, server, response1); + UnitTestUtil.assertIpsEqual("鏈湴缂撳瓨鍗充娇杩囨湡涔熶細杩斿洖ip", ips, response.getIps()); Thread.sleep(1000); ips = app.requestResolveHost(); - ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("ttl过期,会触发网络请求", + ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult("ttl杩囨湡锛屼細瑙﹀彂缃戠粶璇锋眰", app, server, response1); - UnitTestUtil.assertIpsEmpty("后续更新后,不会判定为从本地缓存读取,应该返回空", ips); + UnitTestUtil.assertIpsEmpty("鍚庣画鏇存柊鍚庯紝涓嶄細鍒ゅ畾涓轰粠鏈湴缂撳瓨璇诲彇锛屽簲璇ヨ繑鍥炵┖", ips); } /** - * 测试 域名解析拦截 接口 + * 娴嬭瘯 鍩熷悕瑙f瀽鎷︽埅 鎺ュ彛 */ @Test public void testHostFilter() { @@ -1364,15 +1364,15 @@ public class HttpDnsE2E { app.requestResolveHost(); app.waitForAppThread(); String[] ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("因为域名过滤了,不会请求服务器", + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("鍥犱负鍩熷悕杩囨护浜?涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - UnitTestUtil.assertIpsEmpty("因为域名过滤了解析一直为空", ips); + UnitTestUtil.assertIpsEmpty("鍥犱负鍩熷悕杩囨护浜嗚В鏋愪竴鐩翠负绌?, ips); - ServerStatusHelper.requestResolveAnotherHost("其它域名不受过滤影响", app, server); + ServerStatusHelper.requestResolveAnotherHost("鍏跺畠鍩熷悕涓嶅彈杩囨护褰卞搷", app, server); } /** - * 测试 域名解析拦截 在 预解析上也生效 + * 娴嬭瘯 鍩熷悕瑙f瀽鎷︽埅 鍦?棰勮В鏋愪笂涔熺敓鏁? */ @Test public void testHostFilterForResolve() { @@ -1385,15 +1385,15 @@ public class HttpDnsE2E { app.preResolveHost(list, RequestIpType.v4); app.waitForAppThread(); String[] ips = app.requestResolveHost(); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("因为域名过滤了,不会请求服务器", + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("鍥犱负鍩熷悕杩囨护浜?涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - UnitTestUtil.assertIpsEmpty("因为域名过滤了解析一直为空", ips); + UnitTestUtil.assertIpsEmpty("鍥犱负鍩熷悕杩囨护浜嗚В鏋愪竴鐩翠负绌?, ips); list.remove(app.getRequestHost()); } /** - * 测试 加签能力 + * 娴嬭瘯 鍔犵鑳藉姏 */ @Test public void testAuthSign() { @@ -1413,15 +1413,15 @@ public class HttpDnsE2E { params.add("s"); params.add("t"); params.add("host"); - MatcherAssert.assertThat("请求服务器时,发出的是带签名的请求", + MatcherAssert.assertThat("璇锋眰鏈嶅姟鍣ㄦ椂锛屽彂鍑虹殑鏄甫绛惧悕鐨勮姹?, server.getResolveHostServer().hasRequestForArgWithParams( ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v4), params, 1, false)); } /** - * 测试 签名失效的场景 - * 测试 校正时间能力 + * 娴嬭瘯 绛惧悕澶辨晥鐨勫満鏅? + * 娴嬭瘯 鏍℃鏃堕棿鑳藉姏 */ @Test public void testAuthSignValid() { @@ -1442,20 +1442,20 @@ public class HttpDnsE2E { params.add("s"); params.add("t"); params.add("host"); - MatcherAssert.assertThat("超过有效期,服务不处理", !server.getResolveHostServer() + MatcherAssert.assertThat("瓒呰繃鏈夋晥鏈燂紝鏈嶅姟涓嶅鐞?, !server.getResolveHostServer() .hasRequestForArgWithParams( ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v4), params, 1, false)); } /** - * 测试 网络变化后的预解析能力 + * 娴嬭瘯 缃戠粶鍙樺寲鍚庣殑棰勮В鏋愯兘鍔? */ @Test @Config(shadows = {ShadowNetworkInfo.class}) public void testResolveAfterNetworkChanged() { app.changeToNetwork(ConnectivityManager.TYPE_WIFI); - // 先解析域名,使缓存有数据 + // 鍏堣В鏋愬煙鍚嶏紝浣跨紦瀛樻湁鏁版嵁 String host1 = RandomValue.randomHost(); String host2 = RandomValue.randomHost(); String host3 = RandomValue.randomHost(); @@ -1475,27 +1475,27 @@ public class HttpDnsE2E { app.changeToNetwork(ConnectivityManager.TYPE_MOBILE); app.waitForAppThread(); - UnitTestUtil.assertIpsEqual("网络变化之后,会重新解析已解析的域名", + UnitTestUtil.assertIpsEqual("缃戠粶鍙樺寲涔嬪悗锛屼細閲嶆柊瑙f瀽宸茶В鏋愮殑鍩熷悕", app.requestResolveHost(host1), server.getBatchResolveHostServer().getResponseForHost(host1, RequestIpType.v4).getHostItem(host1, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("网络变化之后,会重新解析已解析的域名", + UnitTestUtil.assertIpsEqual("缃戠粶鍙樺寲涔嬪悗锛屼細閲嶆柊瑙f瀽宸茶В鏋愮殑鍩熷悕", app.requestResolveHost(host2), server.getBatchResolveHostServer().getResponseForHost(host2, RequestIpType.v4).getHostItem(host2, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("网络变化之后,会重新解析已解析的域名", + UnitTestUtil.assertIpsEqual("缃戠粶鍙樺寲涔嬪悗锛屼細閲嶆柊瑙f瀽宸茶В鏋愮殑鍩熷悕", app.requestResolveHost(host3), server.getBatchResolveHostServer().getResponseForHost(host3, RequestIpType.v4).getHostItem(host3, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("网络变化之后,会重新解析已解析的域名", + UnitTestUtil.assertIpsEqual("缃戠粶鍙樺寲涔嬪悗锛屼細閲嶆柊瑙f瀽宸茶В鏋愮殑鍩熷悕", app.requestResolveHost(host4), server.getBatchResolveHostServer().getResponseForHost(host4, RequestIpType.v4).getHostItem(host4, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("网络变化之后,会重新解析已解析的域名", + UnitTestUtil.assertIpsEqual("缃戠粶鍙樺寲涔嬪悗锛屼細閲嶆柊瑙f瀽宸茶В鏋愮殑鍩熷悕", app.requestResolveHost(host5), server.getBatchResolveHostServer().getResponseForHost(host5, RequestIpType.v4).getHostItem(host5, RequestIpType.v4).getIps()); - UnitTestUtil.assertIpsEqual("网络变化之后,会重新解析已解析的域名", + UnitTestUtil.assertIpsEqual("缃戠粶鍙樺寲涔嬪悗锛屼細閲嶆柊瑙f瀽宸茶В鏋愮殑鍩熷悕", app.requestResolveHost(host6), server.getBatchResolveHostServer().getResponseForHost(host6, RequestIpType.v4).getHostItem(host6, RequestIpType.v4).getIps()); @@ -1505,11 +1505,11 @@ public class HttpDnsE2E { app.waitForAppThread(); String[] ips = app.requestResolveHost(host3); - UnitTestUtil.assertIpsEmpty("没有开启网络变化预解析时,网络变换只会清除现有缓存", ips); + UnitTestUtil.assertIpsEmpty("娌℃湁寮€鍚綉缁滃彉鍖栭瑙f瀽鏃讹紝缃戠粶鍙樻崲鍙細娓呴櫎鐜版湁缂撳瓨", ips); } /** - * 断网时,不会触发预解析 + * 鏂綉鏃讹紝涓嶄細瑙﹀彂棰勮В鏋? */ @Test @Config(shadows = {ShadowNetworkInfo.class}) @@ -1517,7 +1517,7 @@ public class HttpDnsE2E { app.changeToNetwork(ConnectivityManager.TYPE_MOBILE); - // 先解析域名,使缓存有数据 + // 鍏堣В鏋愬煙鍚嶏紝浣跨紦瀛樻湁鏁版嵁 String host1 = RandomValue.randomHost(); String host2 = RandomValue.randomHost(); String host3 = RandomValue.randomHost(); @@ -1540,28 +1540,28 @@ public class HttpDnsE2E { app.changeToNetwork(ConnectivityManager.TYPE_MOBILE); app.waitForAppThread(); - UnitTestUtil.assertIpsEqual("网络断开再连上相同网络,解析的缓存不变", + UnitTestUtil.assertIpsEqual("缃戠粶鏂紑鍐嶈繛涓婄浉鍚岀綉缁滐紝瑙f瀽鐨勭紦瀛樹笉鍙?, app.requestResolveHost(host1), server.getResolveHostServer().getResponse(host1, 1, false).get(0).getIps()); - UnitTestUtil.assertIpsEqual("网络断开再连上相同网络,解析的缓存不变", + UnitTestUtil.assertIpsEqual("缃戠粶鏂紑鍐嶈繛涓婄浉鍚岀綉缁滐紝瑙f瀽鐨勭紦瀛樹笉鍙?, app.requestResolveHost(host2), server.getResolveHostServer().getResponse(host2, 1, false).get(0).getIps()); - UnitTestUtil.assertIpsEqual("网络断开再连上相同网络,解析的缓存不变", + UnitTestUtil.assertIpsEqual("缃戠粶鏂紑鍐嶈繛涓婄浉鍚岀綉缁滐紝瑙f瀽鐨勭紦瀛樹笉鍙?, app.requestResolveHost(host3), server.getResolveHostServer().getResponse(host3, 1, false).get(0).getIps()); - UnitTestUtil.assertIpsEqual("网络断开再连上相同网络,解析的缓存不变", + UnitTestUtil.assertIpsEqual("缃戠粶鏂紑鍐嶈繛涓婄浉鍚岀綉缁滐紝瑙f瀽鐨勭紦瀛樹笉鍙?, app.requestResolveHost(host4), server.getResolveHostServer().getResponse(host4, 1, false).get(0).getIps()); - UnitTestUtil.assertIpsEqual("网络断开再连上相同网络,解析的缓存不变", + UnitTestUtil.assertIpsEqual("缃戠粶鏂紑鍐嶈繛涓婄浉鍚岀綉缁滐紝瑙f瀽鐨勭紦瀛樹笉鍙?, app.requestResolveHost(host5), server.getResolveHostServer().getResponse(host5, 1, false).get(0).getIps()); - UnitTestUtil.assertIpsEqual("网络断开再连上相同网络,解析的缓存不变", + UnitTestUtil.assertIpsEqual("缃戠粶鏂紑鍐嶈繛涓婄浉鍚岀綉缁滐紝瑙f瀽鐨勭紦瀛樹笉鍙?, app.requestResolveHost(host6), server.getResolveHostServer().getResponse(host6, 1, false).get(0).getIps()); } /** - * 当前服务节点,每天更新一次 + * 褰撳墠鏈嶅姟鑺傜偣锛屾瘡澶╂洿鏂颁竴娆? */ @Test public void serverIpWillUpdateEveryday() { @@ -1590,29 +1590,29 @@ public class HttpDnsE2E { server2.getServerIpsServer().preSetRequestResponse(region, 200, updateServerResponseFor012, -1); - // 修改region,更新服务IP 到 server 3 4 5 + // 淇敼region锛屾洿鏂版湇鍔P 鍒?server 3 4 5 app.changeRegionTo(region); app.waitForAppThread(); - // 因为我们没法模拟时间经过1天,所以直接修改存储的时间到一天前 + // 鍥犱负鎴戜滑娌℃硶妯℃嫙鏃堕棿缁忚繃1澶╋紝鎵€浠ョ洿鎺ヤ慨鏀瑰瓨鍌ㄧ殑鏃堕棿鍒颁竴澶╁墠 app.changeServerIpUpdateTimeTo(System.currentTimeMillis() - 24 * 60 * 60 * 1000); - // 重置实例 + // 閲嶇疆瀹炰緥 HttpDns.resetInstance(); - // 重新初始化应用,自动更新服务IP 到 1 2 3 + // 閲嶆柊鍒濆鍖栧簲鐢紝鑷姩鏇存柊鏈嶅姟IP 鍒?1 2 3 app.start(false); app.waitForAppThread(); - ServerStatusHelper.hasReceiveRegionChange("服务IP超过一天自动更新", app, server3, region, + ServerStatusHelper.hasReceiveRegionChange("鏈嶅姟IP瓒呰繃涓€澶╄嚜鍔ㄦ洿鏂?, app, server3, region, true); - ServerStatusHelper.requestResolveAnotherHost("服务IP更新后使用新的服务解析域名", app, + ServerStatusHelper.requestResolveAnotherHost("鏈嶅姟IP鏇存柊鍚庝娇鐢ㄦ柊鐨勬湇鍔¤В鏋愬煙鍚?, app, server); } /** - * 测试远程降级能力 + * 娴嬭瘯杩滅▼闄嶇骇鑳藉姏 */ @Test public void testDisableService() { @@ -1620,7 +1620,7 @@ public class HttpDnsE2E { String disableResponse = ServerIpsServer.createUpdateServerDisableResponse(); server.getServerIpsServer().preSetRequestResponse(region, 200, disableResponse, -1); - // 修改region,触发禁止服务 + // 淇敼region锛岃Е鍙戠姝㈡湇鍔? app.changeRegionTo(region); app.waitForAppThread(); @@ -1630,16 +1630,16 @@ public class HttpDnsE2E { app.waitForAppThread(); ips = app.requestResolveHost(host); app.waitForAppThread(); - UnitTestUtil.assertIpsEmpty("服务禁用之后,不会再解析IP", ips); + UnitTestUtil.assertIpsEmpty("鏈嶅姟绂佺敤涔嬪悗锛屼笉浼氬啀瑙f瀽IP", ips); app.requestResolveHostForIpv6(host); app.waitForAppThread(); ips = app.requestResolveHostForIpv6(host); - UnitTestUtil.assertIpsEmpty("服务禁用之后,不会再解析IP", ips); + UnitTestUtil.assertIpsEmpty("鏈嶅姟绂佺敤涔嬪悗锛屼笉浼氬啀瑙f瀽IP", ips); } /** - * 测试 连续调用时 实际网络请求只会发一次 + * 娴嬭瘯 杩炵画璋冪敤鏃?瀹為檯缃戠粶璇锋眰鍙細鍙戜竴娆? */ @Test public void testMultiThreadForSameHost() { @@ -1652,7 +1652,7 @@ public class HttpDnsE2E { } catch (InterruptedException e) { } } - ServerStatusHelper.hasReceiveAppResolveHostRequest("同一个域名同时只会请求一次", app, + ServerStatusHelper.hasReceiveAppResolveHostRequest("鍚屼竴涓煙鍚嶅悓鏃跺彧浼氳姹備竴娆?, app, server, 1); String host1 = RandomValue.randomHost(); @@ -1679,7 +1679,7 @@ public class HttpDnsE2E { } /** - * 测试同步接口 + * 娴嬭瘯鍚屾鎺ュ彛 * * @throws InterruptedException */ @@ -1696,7 +1696,7 @@ public class HttpDnsE2E { server.getResolveHostServer().preSetRequestResponse(host, response, 1); String[] ips = app.requestResolveHostSync(host); try { - UnitTestUtil.assertIpsEqual("解析结果和预期相同", ips, response.getIps()); + UnitTestUtil.assertIpsEqual("瑙f瀽缁撴灉鍜岄鏈熺浉鍚?, ips, response.getIps()); } catch (Throwable e) { exceptions[0] = e; e.printStackTrace(); @@ -1711,7 +1711,7 @@ public class HttpDnsE2E { } /** - * 测试频繁调用的情况下,会不会崩溃 + * 娴嬭瘯棰戠箒璋冪敤鐨勬儏鍐典笅锛屼細涓嶄細宕╂簝 */ @Test public void testNotCrashWhenCallTwoManyTime() { @@ -1768,32 +1768,32 @@ public class HttpDnsE2E { } } catch (Throwable throwable) { throwable.printStackTrace(); - MatcherAssert.assertThat("调用次数多,不应该崩溃", false); + MatcherAssert.assertThat("璋冪敤娆℃暟澶氾紝涓嶅簲璇ュ穿婧?, false); } } /** - * 测试 清除指定域名缓存功能 + * 娴嬭瘯 娓呴櫎鎸囧畾鍩熷悕缂撳瓨鍔熻兘 */ @Test public void cleanHostCacheWillRemoveLocalCache() { app.requestResolveHost(); app.waitForAppThread(); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? String[] ips = app.requestResolveHost(); - MatcherAssert.assertThat("先解析域名确保有缓存", ips.length > 0 && !ips[0].isEmpty()); + MatcherAssert.assertThat("鍏堣В鏋愬煙鍚嶇‘淇濇湁缂撳瓨", ips.length > 0 && !ips[0].isEmpty()); ArrayList hosts = new ArrayList<>(); hosts.add(app.getRequestHost()); app.cleanHostCache(hosts); ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("清除缓存之后,请求会返回空", ips); + UnitTestUtil.assertIpsEmpty("娓呴櫎缂撳瓨涔嬪悗锛岃姹備細杩斿洖绌?, ips); } /** - * 测试 清除全部域名缓存功能 + * 娴嬭瘯 娓呴櫎鍏ㄩ儴鍩熷悕缂撳瓨鍔熻兘 */ @Test public void cleanHostCacheWithoutHostWillRemoveAllHostCache() { @@ -1805,83 +1805,83 @@ public class HttpDnsE2E { String[] ips1 = app.requestResolveHost(host1); String[] ips2 = app.requestResolveHost(host2); - MatcherAssert.assertThat("当前 host1 host2 都有缓存", + MatcherAssert.assertThat("褰撳墠 host1 host2 閮芥湁缂撳瓨", ips1.length > 0 && !ips1[0].isEmpty() && ips2.length > 0 && !ips2[0].isEmpty()); app.cleanHostCache(null); ips1 = app.requestResolveHost(host1); ips2 = app.requestResolveHost(host2); - UnitTestUtil.assertIpsEmpty("清除缓存之后,请求会返回空", ips1); - UnitTestUtil.assertIpsEmpty("清除缓存之后,请求会返回空", ips2); + UnitTestUtil.assertIpsEmpty("娓呴櫎缂撳瓨涔嬪悗锛岃姹備細杩斿洖绌?, ips1); + UnitTestUtil.assertIpsEmpty("娓呴櫎缂撳瓨涔嬪悗锛岃姹備細杩斿洖绌?, ips2); } /** - * 测试对本地缓存的清理 + * 娴嬭瘯瀵规湰鍦扮紦瀛樼殑娓呯悊 */ @Test public void cleanHostCacheWillCleanCacheInLocalDB() { - // 启动缓存 + // 鍚姩缂撳瓨 app.enableCache(false); - // 先发起一些请求,缓存一些Ip结果 + // 鍏堝彂璧蜂竴浜涜姹傦紝缂撳瓨涓€浜汭p缁撴灉 app.requestResolveHost(); app.waitForAppThread(); String[] ips1 = app.requestResolveHost(); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(false); - // 读取缓存 + // 璇诲彇缂撳瓨 String[] ips2 = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("确认缓存生效", ips1, ips2); + UnitTestUtil.assertIpsEqual("纭缂撳瓨鐢熸晥", ips1, ips2); app.waitForAppThread(); - // 获取新的缓存值 + // 鑾峰彇鏂扮殑缂撳瓨鍊? ips2 = app.requestResolveHost(); - // 重置实例, + // 閲嶇疆瀹炰緥锛? HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(false); String[] ips3 = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("确认缓存没有被清除,一直存在", ips3, ips2); + UnitTestUtil.assertIpsEqual("纭缂撳瓨娌℃湁琚竻闄わ紝涓€鐩村瓨鍦?, ips3, ips2); app.waitForAppThread(); ArrayList hosts = new ArrayList<>(); hosts.add(app.getRequestHost()); app.cleanHostCache(hosts); - // 重置实例, + // 閲嶇疆瀹炰緥锛? HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); app.enableCache(false); String[] ips4 = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("清除缓存会把数据库缓存也清除", ips4); + UnitTestUtil.assertIpsEmpty("娓呴櫎缂撳瓨浼氭妸鏁版嵁搴撶紦瀛樹篃娓呴櫎", ips4); } /** - * 这个应该手动执行,耗时太长 - * 测试 多线程并发请求的情况下,接口的耗时情况 + * 杩欎釜搴旇鎵嬪姩鎵ц锛岃€楁椂澶暱 + * 娴嬭瘯 澶氱嚎绋嬪苟鍙戣姹傜殑鎯呭喌涓嬶紝鎺ュ彛鐨勮€楁椂鎯呭喌 */ - @Ignore("耗时太长,需要手动执行") + @Ignore("鑰楁椂澶暱锛岄渶瑕佹墜鍔ㄦ墽琛?) @Test public void multiThreadTest() { HttpDnsLog.removeLogger(logger); app.setTimeout(10 * 1000); HttpDnsLog.enable(false); - // 测试时总的域名数 + // 娴嬭瘯鏃舵€荤殑鍩熷悕鏁? final int hostCount = 10; - // 会超时的域名数 + // 浼氳秴鏃剁殑鍩熷悕鏁? final int timeoutCount = 3; final String timeoutPrefix = "TIMEOUT"; final ArrayList hosts = new ArrayList<>(hostCount); @@ -1892,7 +1892,7 @@ public class HttpDnsE2E { hosts.add(timeoutPrefix + RandomValue.randomHost()); } - // 预置超时响应 + // 棰勭疆瓒呮椂鍝嶅簲 for (int i = 0; i < hostCount; i++) { if (hosts.get(i).startsWith(timeoutPrefix)) { server.getResolveHostServer().preSetRequestTimeout(hosts.get(i), -1); @@ -1903,15 +1903,15 @@ public class HttpDnsE2E { } } - // 并发线程数 + // 骞跺彂绾跨▼鏁? final int threadCount = 10; - // 测试时长 ms + // 娴嬭瘯鏃堕暱 ms final int time = 1 * 60 * 1000; - // 测试结束锁 + // 娴嬭瘯缁撴潫閿? final CountDownLatch testLatch = new CountDownLatch(threadCount); final AtomicInteger slowCount = new AtomicInteger(0); ExecutorService service = Executors.newFixedThreadPool(threadCount); - // 并发启动锁 + // 骞跺彂鍚姩閿? final CountDownLatch startLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { service.execute(new Runnable() { @@ -1961,14 +1961,14 @@ public class HttpDnsE2E { testLatch.await(); } catch (InterruptedException e) { } - MatcherAssert.assertThat("返回慢的调用应该为0", slowCount.get(), + MatcherAssert.assertThat("杩斿洖鎱㈢殑璋冪敤搴旇涓?", slowCount.get(), Matchers.is(Matchers.equalTo(0))); } /** - * https://aone.alibaba-inc.com/req/38989131 + * https://aone.Aliyun.com/req/38989131 *

- * 服务IP不是当前region的服务IP时,不能用于域名解析 + * 鏈嶅姟IP涓嶆槸褰撳墠region鐨勬湇鍔P鏃讹紝涓嶈兘鐢ㄤ簬鍩熷悕瑙f瀽 */ @Test public void stopResolveHostWhenServerIpDoNotBelongCurrentRegion() { @@ -1976,85 +1976,85 @@ public class HttpDnsE2E { final String otherRegion = Constants.REGION_HK == defaultRegion ? Constants.REGION_MAINLAND : Constants.REGION_HK; - // 设置不同region对应的服务信息 + // 璁剧疆涓嶅悓region瀵瑰簲鐨勬湇鍔′俊鎭? prepareUpdateServerResponse(defaultRegion, otherRegion); - // 修改region + // 淇敼region app.changeRegionTo(otherRegion); - // 修改region之后马上请求解析域名 + // 淇敼region涔嬪悗椹笂璇锋眰瑙f瀽鍩熷悕 app.requestResolveHost(); - // 此时 region应该还没有切换完成,域名解析时应该会发现当前服务IP不属于我们设置的region - // 所以应该 当前服务IP没有接收到解析请求,region更新之后的服务IP也没有接收到解析请求 + // 姝ゆ椂 region搴旇杩樻病鏈夊垏鎹㈠畬鎴愶紝鍩熷悕瑙f瀽鏃跺簲璇ヤ細鍙戠幇褰撳墠鏈嶅姟IP涓嶅睘浜庢垜浠缃殑region + // 鎵€浠ュ簲璇?褰撳墠鏈嶅姟IP娌℃湁鎺ユ敹鍒拌В鏋愯姹傦紝region鏇存柊涔嬪悗鐨勬湇鍔P涔熸病鏈夋帴鏀跺埌瑙f瀽璇锋眰 ServerStatusHelper.hasNotReceiveAppResolveHostRequest( - "服务IP和region不匹配, 应该停止解析,直接返回,不应该请求当前服务IP进行解析", app, + "鏈嶅姟IP鍜宺egion涓嶅尮閰? 搴旇鍋滄瑙f瀽锛岀洿鎺ヨ繑鍥烇紝涓嶅簲璇ヨ姹傚綋鍓嶆湇鍔P杩涜瑙f瀽", app, server); ServerStatusHelper.hasNotReceiveAppResolveHostRequest( - "region更新还未完成,应该不会请求到新的服务IP", app, server3); + "region鏇存柊杩樻湭瀹屾垚锛屽簲璇ヤ笉浼氳姹傚埌鏂扮殑鏈嶅姟IP", app, server3); } /** - * 修改region后,马上清除缓存,避免获取错误的IP + * 淇敼region鍚庯紝椹笂娓呴櫎缂撳瓨锛岄伩鍏嶈幏鍙栭敊璇殑IP */ @Test public void changeRegionWillCleanCachePreventGetWrongIp() { final String defaultRegion = REGION_DEFAULT; final String otherRegion = Constants.REGION_HK == defaultRegion ? Constants.REGION_MAINLAND : Constants.REGION_HK; - // 设置不同region对应的服务信息 + // 璁剧疆涓嶅悓region瀵瑰簲鐨勬湇鍔′俊鎭? prepareUpdateServerResponse(defaultRegion, otherRegion); app.requestResolveHost(); app.waitForAppThread(); String[] ips = app.requestResolveHost(); - // 确定已经有缓存 - MatcherAssert.assertThat("已经有缓存", ips != null && ips.length > 0); + // 纭畾宸茬粡鏈夌紦瀛? + MatcherAssert.assertThat("宸茬粡鏈夌紦瀛?, ips != null && ips.length > 0); - // 修改region + // 淇敼region app.changeRegionTo(otherRegion); - // 修改region之后马上请求解析域名 + // 淇敼region涔嬪悗椹笂璇锋眰瑙f瀽鍩熷悕 String[] ipsAfterChagneRegion = app.requestResolveHost(); - MatcherAssert.assertThat("region切换,清除了缓存", + MatcherAssert.assertThat("region鍒囨崲锛屾竻闄や簡缂撳瓨", ipsAfterChagneRegion == null || ipsAfterChagneRegion.length == 0); } /** - * IP缓存仅读取当前region的缓存 + * IP缂撳瓨浠呰鍙栧綋鍓峳egion鐨勭紦瀛? */ @Test public void cacheWillLoadCurrentRegion() { final String defaultRegion = REGION_DEFAULT; final String otherRegion = Constants.REGION_HK == defaultRegion ? Constants.REGION_MAINLAND : Constants.REGION_HK; - // 设置不同region对应的服务信息 + // 璁剧疆涓嶅悓region瀵瑰簲鐨勬湇鍔′俊鎭? prepareUpdateServerResponse(defaultRegion, otherRegion); app.enableCache(false); - // 先发起一些请求,缓存一些Ip结果 + // 鍏堝彂璧蜂竴浜涜姹傦紝缂撳瓨涓€浜汭p缁撴灉 app.requestResolveHost(); app.waitForAppThread(); String[] cachedIps = app.requestResolveHost(); - MatcherAssert.assertThat("确认缓存存在", cachedIps.length > 0); + MatcherAssert.assertThat("纭缂撳瓨瀛樺湪", cachedIps.length > 0); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); app.waitForAppThread(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); - // 切换region + // 鍒囨崲region app.changeRegionTo(otherRegion); - // 再加载缓存 + // 鍐嶅姞杞界紦瀛? app.enableCache(false); String[] ips = app.requestResolveHost(); - MatcherAssert.assertThat("缓存被清除了,此时返回是空", ips == null || ips.length == 0); + MatcherAssert.assertThat("缂撳瓨琚竻闄や簡锛屾鏃惰繑鍥炴槸绌?, ips == null || ips.length == 0); } /** - * 通过初始化 开启IP缓存 + * 閫氳繃鍒濆鍖?寮€鍚疘P缂撳瓨 */ @Test public void enableCacheWhenInit() { @@ -2069,28 +2069,28 @@ public class HttpDnsE2E { app.configSpeedTestSever(speedTestServer); app.start(true); - // 先发起一些请求,缓存一些Ip结果 + // 鍏堝彂璧蜂竴浜涜姹傦紝缂撳瓨涓€浜汭p缁撴灉 app.requestResolveHost(); app.waitForAppThread(); String[] ips = app.requestResolveHost(); - MatcherAssert.assertThat("确定有缓存了", ips.length > 0); - ServerStatusHelper.hasReceiveAppResolveHostRequest("读取缓存之前请求了一次服务器", app, + MatcherAssert.assertThat("纭畾鏈夌紦瀛樹簡", ips.length > 0); + ServerStatusHelper.hasReceiveAppResolveHostRequest("璇诲彇缂撳瓨涔嬪墠璇锋眰浜嗕竴娆℃湇鍔″櫒", app, server, 1); - // 重置实例,确保下次读取的信息是从本地缓存来的 + // 閲嶇疆瀹炰緥锛岀‘淇濅笅娆¤鍙栫殑淇℃伅鏄粠鏈湴缂撳瓨鏉ョ殑 HttpDns.resetInstance(); - // 重启应用,获取新的实例 + // 閲嶅惎搴旂敤锛岃幏鍙栨柊鐨勫疄渚? app.start(true); String[] ips2 = app.requestResolveHost(); ServerStatusHelper.hasReceiveAppResolveHostRequest( - "有缓存,但是由于无法判断之前和之后的网络是否一致,还是需要再请求一次", app, server, 2); - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", ips2, ips); + "鏈夌紦瀛橈紝浣嗘槸鐢变簬鏃犳硶鍒ゆ柇涔嬪墠鍜屼箣鍚庣殑缃戠粶鏄惁涓€鑷达紝杩樻槸闇€瑕佸啀璇锋眰涓€娆?, app, server, 2); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, ips2, ips); } /** - * 通过初始化设置region + * 閫氳繃鍒濆鍖栬缃畆egion */ @Test public void setRegionWhenInit() { @@ -2106,12 +2106,12 @@ public class HttpDnsE2E { app.start(false); - ServerStatusHelper.hasReceiveRegionChange("初始化时更新HK节点, 一次", app, server, + ServerStatusHelper.hasReceiveRegionChange("鍒濆鍖栨椂鏇存柊HK鑺傜偣, 涓€娆?, app, server, Constants.REGION_HK, 1, true); } /** - * 通过初始化 禁用过期IP + * 閫氳繃鍒濆鍖?绂佺敤杩囨湡IP * * @throws InterruptedException */ @@ -2134,35 +2134,35 @@ public class HttpDnsE2E { app.getRequestHost()); server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response, 1); server.getResolveHostServer().preSetRequestResponse(app.getRequestHost(), response1, -1); - // 请求域名解析,并返回空结果,因为是接口是异步的,所以第一次请求一个域名返回是空 + // 璇锋眰鍩熷悕瑙f瀽锛屽苟杩斿洖绌虹粨鏋滐紝鍥犱负鏄帴鍙f槸寮傛鐨勶紝鎵€浠ョ涓€娆¤姹備竴涓煙鍚嶈繑鍥炴槸绌? String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); app.waitForAppThread(); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? app.requestResolveHost(); Thread.sleep(1000); - // ttl 过期后请求ip + // ttl 杩囨湡鍚庤姹俰p ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEmpty("不启用过期IP,返回空", ips); + UnitTestUtil.assertIpsEmpty("涓嶅惎鐢ㄨ繃鏈烮P锛岃繑鍥炵┖", ips); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "ttl过期后,请求会触发网络请求", app, + "ttl杩囨湡鍚庯紝璇锋眰浼氳Е鍙戠綉缁滆姹?, app, ResolveHostServer.ResolveHostArg.create(app.getRequestHost()), server, response1 , 1, true); - // 再次请求,获取再次请求服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栧啀娆¤姹傛湇鍔″櫒杩斿洖鐨勭粨鏋? ips = app.requestResolveHost(); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", response1.getIps(), ips); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, response1.getIps(), ips); } /** - * 通过初始化设置超时 + * 閫氳繃鍒濆鍖栬缃秴鏃? */ @Test public void setTimeoutWhenInit() { String accountId = RandomValue.randomStringWithFixedLength(10); - // 设置超时时间 + // 璁剧疆瓒呮椂鏃堕棿 int timeout = 1000; new InitConfig.Builder() .setTimeout(timeout) @@ -2172,22 +2172,22 @@ public class HttpDnsE2E { app.configSpeedTestSever(speedTestServer); app.start(true); - // 预设请求超时 + // 棰勮璇锋眰瓒呮椂 server.getResolveHostServer().preSetRequestTimeout(app.getRequestHost(), -1); - // 请求 并计时 + // 璇锋眰 骞惰鏃? long start = System.currentTimeMillis(); app.requestResolveHost(); - // 确实是否接受到请求,并超时 + // 纭疄鏄惁鎺ュ彈鍒拌姹傦紝骞惰秴鏃? ServerStatusHelper.hasReceiveAppResolveHostRequestButTimeout(app, server); long costTime = System.currentTimeMillis() - start; - // 3.05 是个经验数据,可以考虑调整。影响因素主要有重试次数和线程切换 + // 3.05 鏄釜缁忛獙鏁版嵁锛屽彲浠ヨ€冭檻璋冩暣銆傚奖鍝嶅洜绱犱富瑕佹湁閲嶈瘯娆℃暟鍜岀嚎绋嬪垏鎹? assertThat("requst timeout " + costTime, costTime < timeout * 3.05); } /** - * 通过初始化设置测速配置 + * 閫氳繃鍒濆鍖栬缃祴閫熼厤缃? */ @Test public void configProbeWhenInit() { @@ -2203,26 +2203,26 @@ public class HttpDnsE2E { app.configSpeedTestSever(speedTestServer); app.start(true); - // 请求数据触发IP优选 + // 璇锋眰鏁版嵁瑙﹀彂IP浼橀€? app.requestResolveHost(host); app.waitForAppThread(); - // 判断返回的结果是优选的结果 + // 鍒ゆ柇杩斿洖鐨勭粨鏋滄槸浼橀€夌殑缁撴灉 String[] ips = app.requestResolveHost(host); String[] sortedIps = speedTestServer.getSortedIpsFor(host); - UnitTestUtil.assertIpsEqual("设置ip优选后,返回的ip是优选之后的结果", ips, sortedIps); + UnitTestUtil.assertIpsEqual("璁剧疆ip浼橀€夊悗锛岃繑鍥炵殑ip鏄紭閫変箣鍚庣殑缁撴灉", ips, sortedIps); } /** - * 加载本地缓存应该在region切换之后,避免加载错误的缓存 + * 鍔犺浇鏈湴缂撳瓨搴旇鍦╮egion鍒囨崲涔嬪悗锛岄伩鍏嶅姞杞介敊璇殑缂撳瓨 */ @Test public void loadCacheAfterRegionChangeWhenInit() { final String defaultRegion = REGION_DEFAULT; final String otherRegion = Constants.REGION_HK == defaultRegion ? Constants.REGION_MAINLAND : Constants.REGION_HK; - // 设置不同region对应的服务信息 + // 璁剧疆涓嶅悓region瀵瑰簲鐨勬湇鍔′俊鎭? prepareUpdateServerResponse(defaultRegion, otherRegion); String accountId = RandomValue.randomStringWithFixedLength(10); @@ -2237,8 +2237,8 @@ public class HttpDnsE2E { app.requestResolveHost(); app.waitForAppThread(); String[] ips = app.requestResolveHost(); - // 确定已经有缓存 - MatcherAssert.assertThat("已经有缓存", ips != null && ips.length > 0); + // 纭畾宸茬粡鏈夌紦瀛? + MatcherAssert.assertThat("宸茬粡鏈夌紦瀛?, ips != null && ips.length > 0); HttpDns.resetInstance(); app.waitForAppThread(); @@ -2247,13 +2247,13 @@ public class HttpDnsE2E { .setEnableCacheIp(true) .setRegion(otherRegion) .buildFor(accountId); - // 这里上个实例刚更新过服务节点,所以本地启动不会更新服务节点 + // 杩欓噷涓婁釜瀹炰緥鍒氭洿鏂拌繃鏈嶅姟鑺傜偣锛屾墍浠ユ湰鍦板惎鍔ㄤ笉浼氭洿鏂版湇鍔¤妭鐐? app.start(false); app.waitForAppThread(); String[] ipsAfterChangeRegion = app.requestResolveHost(); - MatcherAssert.assertThat("region切换,无法读取到原region的缓存", + MatcherAssert.assertThat("region鍒囨崲锛屾棤娉曡鍙栧埌鍘焤egion鐨勭紦瀛?, ipsAfterChangeRegion == null || ipsAfterChangeRegion.length == 0); HttpDns.resetInstance(); @@ -2263,12 +2263,13 @@ public class HttpDnsE2E { .setEnableCacheIp(true) .setRegion(otherRegion) .buildFor(accountId); - // 这里上个实例刚更新过服务节点,所以本地启动不会更新服务节点 + // 杩欓噷涓婁釜瀹炰緥鍒氭洿鏂拌繃鏈嶅姟鑺傜偣锛屾墍浠ユ湰鍦板惎鍔ㄤ笉浼氭洿鏂版湇鍔¤妭鐐? app.start(false); app.waitForAppThread(); String[] ipsWhenRegionNotChange = app.requestResolveHost(); - MatcherAssert.assertThat("region保持一致,读取到原region的缓存", + MatcherAssert.assertThat("region淇濇寔涓€鑷达紝璇诲彇鍒板師region鐨勭紦瀛?, ipsWhenRegionNotChange != null && ipsWhenRegionNotChange.length > 0); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsResultTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsResultTest.java index 1c15227..478c651 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsResultTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/HttpDnsResultTest.java @@ -31,28 +31,28 @@ public class HttpDnsResultTest { null, null, RandomValue.randomIpv4s(), 60); httpdnsResult.update(record); - MatcherAssert.assertThat("使用HostRecord更新result", httpdnsResult.getIps(), + MatcherAssert.assertThat("浣跨敤HostRecord鏇存柊result", httpdnsResult.getIps(), Matchers.is(Matchers.equalTo(record.getIps()))); HostRecord record1 = HostRecord.create(Constants.REGION_MAINLAND, host, RequestIpType.v6, null, null, RandomValue.randomIpv6s(), 60); httpdnsResult.update(record1); - MatcherAssert.assertThat("更新ipv6 不会影响v4的结果", httpdnsResult.getIps(), + MatcherAssert.assertThat("鏇存柊ipv6 涓嶄細褰卞搷v4鐨勭粨鏋?, httpdnsResult.getIps(), Matchers.is(Matchers.equalTo(record.getIps()))); - MatcherAssert.assertThat("更新ipv6", httpdnsResult.getIpv6s(), + MatcherAssert.assertThat("鏇存柊ipv6", httpdnsResult.getIpv6s(), Matchers.is(Matchers.equalTo(record1.getIps()))); record.setQueryTime(0); httpdnsResult.update(record); - MatcherAssert.assertThat("更新为过期", httpdnsResult.isExpired()); + MatcherAssert.assertThat("鏇存柊涓鸿繃鏈?, httpdnsResult.isExpired()); record1.setExtra( "{\"name\":\"BeJson\",\"url\":\"http://www.bejson.com\",\"page\":88," + "\"isNonProfit\":true}"); httpdnsResult.update(record1); - MatcherAssert.assertThat("更新为不过期", !httpdnsResult.isExpired()); - MatcherAssert.assertThat("更新extra", httpdnsResult.getExtras().get("name"), + MatcherAssert.assertThat("鏇存柊涓轰笉杩囨湡", !httpdnsResult.isExpired()); + MatcherAssert.assertThat("鏇存柊extra", httpdnsResult.getExtras().get("name"), Matchers.is(Matchers.equalTo("BeJson"))); } @@ -75,14 +75,15 @@ public class HttpDnsResultTest { records.add(record1); result.update(records); - MatcherAssert.assertThat("更新ip", result.getIps(), + MatcherAssert.assertThat("鏇存柊ip", result.getIps(), Matchers.is(Matchers.equalTo(record.getIps()))); - MatcherAssert.assertThat("更新ipv6", result.getIpv6s(), + MatcherAssert.assertThat("鏇存柊ipv6", result.getIpv6s(), Matchers.is(Matchers.equalTo(record1.getIps()))); - MatcherAssert.assertThat("更新过期时间", result.isExpired()); - MatcherAssert.assertThat("更新Extra", result.getExtras().get("name"), + MatcherAssert.assertThat("鏇存柊杩囨湡鏃堕棿", result.isExpired()); + MatcherAssert.assertThat("鏇存柊Extra", result.getExtras().get("name"), Matchers.is(Matchers.equalTo("BeJson"))); - MatcherAssert.assertThat("更新isFromDB", result.isFromDB()); + MatcherAssert.assertThat("鏇存柊isFromDB", result.isFromDB()); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/InitConfigTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/InitConfigTest.java index e13b608..8c7f914 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/InitConfigTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/InitConfigTest.java @@ -29,7 +29,7 @@ public class InitConfigTest { String accountId = RandomValue.randomStringWithFixedLength(10); InitConfig config = new InitConfig.Builder().buildFor(accountId); - MatcherAssert.assertThat("创建的config可以通过get方法获取", InitConfig.getInitConfig(accountId), Matchers.is(config)); + MatcherAssert.assertThat("鍒涘缓鐨刢onfig鍙互閫氳繃get鏂规硶鑾峰彇", InitConfig.getInitConfig(accountId), Matchers.is(config)); } @Test @@ -38,13 +38,13 @@ public class InitConfigTest { new InitConfig.Builder().buildFor(accountId); InitConfig config = InitConfig.getInitConfig(accountId); - MatcherAssert.assertThat("默认允许过期IP", config.isEnableExpiredIp(), Matchers.is(true)); - MatcherAssert.assertThat("默认不本地缓存IP", config.isEnableCacheIp(), Matchers.is(false)); - MatcherAssert.assertThat("默认不开启https", config.isEnableHttps(), Matchers.is(false)); - MatcherAssert.assertThat("默认region正确", config.getRegion(), Matchers.is(InitConfig.NOT_SET)); - MatcherAssert.assertThat("默认超时时间是15s", config.getTimeout(), Matchers.is(15 * 1000)); - MatcherAssert.assertThat("默认不测速", config.getIPRankingList(), Matchers.nullValue()); - MatcherAssert.assertThat("默认不修改缓存ttl配置", config.getCacheTtlChanger(), Matchers.nullValue()); + MatcherAssert.assertThat("榛樿鍏佽杩囨湡IP", config.isEnableExpiredIp(), Matchers.is(true)); + MatcherAssert.assertThat("榛樿涓嶆湰鍦扮紦瀛業P", config.isEnableCacheIp(), Matchers.is(false)); + MatcherAssert.assertThat("榛樿涓嶅紑鍚痟ttps", config.isEnableHttps(), Matchers.is(false)); + MatcherAssert.assertThat("榛樿region姝g‘", config.getRegion(), Matchers.is(InitConfig.NOT_SET)); + MatcherAssert.assertThat("榛樿瓒呮椂鏃堕棿鏄?5s", config.getTimeout(), Matchers.is(15 * 1000)); + MatcherAssert.assertThat("榛樿涓嶆祴閫?, config.getIPRankingList(), Matchers.nullValue()); + MatcherAssert.assertThat("榛樿涓嶄慨鏀圭紦瀛榯tl閰嶇疆", config.getCacheTtlChanger(), Matchers.nullValue()); } @Test @@ -62,13 +62,14 @@ public class InitConfigTest { .buildFor(accountId); InitConfig config = InitConfig.getInitConfig(accountId); - MatcherAssert.assertThat("不允许过期IP", config.isEnableExpiredIp(), Matchers.is(false)); - MatcherAssert.assertThat("本地缓存IP", config.isEnableCacheIp(), Matchers.is(true)); - MatcherAssert.assertThat("开启https", config.isEnableHttps(), Matchers.is(true)); - MatcherAssert.assertThat("region是HK", config.getRegion(), Matchers.is(Constants.REGION_HK)); - MatcherAssert.assertThat("超时时间是5s", config.getTimeout(), Matchers.is(5 * 1000)); - MatcherAssert.assertThat("测速", config.getIPRankingList().get(0).getHostName(), Matchers.is(Matchers.equalTo("aa"))); - MatcherAssert.assertThat("测速", config.getIPRankingList().get(0).getPort(), Matchers.is(43)); - MatcherAssert.assertThat("配置的有ttlChanger", config.getCacheTtlChanger(), Matchers.is(ttlChanger)); + MatcherAssert.assertThat("涓嶅厑璁歌繃鏈烮P", config.isEnableExpiredIp(), Matchers.is(false)); + MatcherAssert.assertThat("鏈湴缂撳瓨IP", config.isEnableCacheIp(), Matchers.is(true)); + MatcherAssert.assertThat("寮€鍚痟ttps", config.isEnableHttps(), Matchers.is(true)); + MatcherAssert.assertThat("region鏄疕K", config.getRegion(), Matchers.is(Constants.REGION_HK)); + MatcherAssert.assertThat("瓒呮椂鏃堕棿鏄?s", config.getTimeout(), Matchers.is(5 * 1000)); + MatcherAssert.assertThat("娴嬮€?, config.getIPRankingList().get(0).getHostName(), Matchers.is(Matchers.equalTo("aa"))); + MatcherAssert.assertThat("娴嬮€?, config.getIPRankingList().get(0).getPort(), Matchers.is(43)); + MatcherAssert.assertThat("閰嶇疆鐨勬湁ttlChanger", config.getCacheTtlChanger(), Matchers.is(ttlChanger)); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelperTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelperTest.java index d076213..8545015 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelperTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/cache/RecordDBHelperTest.java @@ -36,11 +36,11 @@ public class RecordDBHelperTest { @Test public void testSaveAndGet() { - // 初始数据 + // 鍒濆鏁版嵁 List records = randomRecord(Constants.REGION_MAINLAND, 30); helper.insertOrUpdate(records); - // 读取 + // 璇诲彇 List records3 = helper.readFromDb(Constants.REGION_MAINLAND); ArrayList saved = new ArrayList<>(); @@ -53,11 +53,11 @@ public class RecordDBHelperTest { @Test public void testDeleted() { - // 初始数据 + // 鍒濆鏁版嵁 List records = randomRecord(Constants.REGION_MAINLAND, 30); helper.insertOrUpdate(records); - // 删除一些 + // 鍒犻櫎涓€浜? ArrayList left = new ArrayList<>(records); ArrayList deleted = new ArrayList<>(); for (int i = 0; i < 10; i++) { @@ -65,7 +65,7 @@ public class RecordDBHelperTest { } helper.delete(deleted); - // 读取 + // 璇诲彇 List records3 = helper.readFromDb(Constants.REGION_MAINLAND); ArrayList saved = new ArrayList<>(); @@ -78,15 +78,15 @@ public class RecordDBHelperTest { @Test public void testAdd() { - // 初始数据 + // 鍒濆鏁版嵁 List records = randomRecord(Constants.REGION_MAINLAND, 30); helper.insertOrUpdate(records); - // 新增一些 + // 鏂板涓€浜? List records1 = randomRecord(Constants.REGION_MAINLAND, 10); helper.insertOrUpdate(records1); - // 读取 + // 璇诲彇 List records3 = helper.readFromDb(Constants.REGION_MAINLAND); ArrayList saved = new ArrayList<>(); @@ -100,15 +100,15 @@ public class RecordDBHelperTest { @Test public void testUpdate() { - // 初始数据 + // 鍒濆鏁版嵁 List records = randomRecord(Constants.REGION_MAINLAND, 30); helper.insertOrUpdate(records); - // 新增一些 + // 鏂板涓€浜? List records1 = randomRecord(Constants.REGION_MAINLAND, 10); helper.insertOrUpdate(records1); - // 更新一些 + // 鏇存柊涓€浜? ArrayList records2 = new ArrayList<>(); for (HostRecord record : records1) { if (record.getType() == RequestIpType.v4.ordinal()) { @@ -121,7 +121,7 @@ public class RecordDBHelperTest { } helper.insertOrUpdate(records2); - // 读取 + // 璇诲彇 List records3 = helper.readFromDb(Constants.REGION_MAINLAND); ArrayList saved = new ArrayList<>(); @@ -135,11 +135,11 @@ public class RecordDBHelperTest { @Test public void testCache() { - // 初始数据 + // 鍒濆鏁版嵁 List records = randomRecord(Constants.REGION_MAINLAND, 30); helper.insertOrUpdate(records); - // 删除一些 + // 鍒犻櫎涓€浜? ArrayList left = new ArrayList<>(records); ArrayList deleted = new ArrayList<>(); for (int i = 0; i < 10; i++) { @@ -147,11 +147,11 @@ public class RecordDBHelperTest { } helper.delete(deleted); - // 新增一些 + // 鏂板涓€浜? List records1 = randomRecord(Constants.REGION_MAINLAND, 10); helper.insertOrUpdate(records1); - // 更新一些 + // 鏇存柊涓€浜? ArrayList records2 = new ArrayList<>(); for (HostRecord record : records1) { if (record.getType() == RequestIpType.v4.ordinal()) { @@ -164,7 +164,7 @@ public class RecordDBHelperTest { } helper.insertOrUpdate(records2); - // 读取 + // 璇诲彇 List records3 = helper.readFromDb(Constants.REGION_MAINLAND); ArrayList saved = new ArrayList<>(); @@ -179,14 +179,14 @@ public class RecordDBHelperTest { @Test public void readCacheByRegion() { - // 初始数据 + // 鍒濆鏁版嵁 List records = randomRecord(Constants.REGION_MAINLAND, 30); helper.insertOrUpdate(records); List recordsInHK = randomRecord(Constants.REGION_HK, 30); helper.insertOrUpdate(recordsInHK); - // 读取 + // 璇诲彇 List records3 = helper.readFromDb(Constants.REGION_MAINLAND); ArrayList saved = new ArrayList<>(); @@ -207,7 +207,7 @@ public class RecordDBHelperTest { List records5 = helper.readFromDb(Constants.REGION_SG); - MatcherAssert.assertThat("根据region读取缓存, sg的缓存应该为0", records5.size() == 0); + MatcherAssert.assertThat("鏍规嵁region璇诲彇缂撳瓨, sg鐨勭紦瀛樺簲璇ヤ负0", records5.size() == 0); } private void assertRecordsEqual(ArrayList saved, ArrayList read) { @@ -224,9 +224,9 @@ public class RecordDBHelperTest { } }); - MatcherAssert.assertThat("写入和读取的应该一样", read.size() == saved.size()); + MatcherAssert.assertThat("鍐欏叆鍜岃鍙栫殑搴旇涓€鏍?, read.size() == saved.size()); for (int i = 0; i < read.size(); i++) { - MatcherAssert.assertThat("写入和读取的应该一样", read.get(i), Matchers.is(saved.get(i))); + MatcherAssert.assertThat("鍐欏叆鍜岃鍙栫殑搴旇涓€鏍?, read.get(i), Matchers.is(saved.get(i))); } } @@ -255,3 +255,4 @@ public class RecordDBHelperTest { } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptServiceTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptServiceTest.java index 5b80d15..940dfc8 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptServiceTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/AESEncryptServiceTest.java @@ -19,7 +19,7 @@ import java.util.HashMap; class AESEncryptServiceTest { private AESEncryptService service; - private static final String TEST_KEY = "0123456789ABCDEF0123456789ABCDEF"; // 32字节密钥 + private static final String TEST_KEY = "0123456789ABCDEF0123456789ABCDEF"; // 32瀛楄妭瀵嗛挜 private static final String TEST_DATA = "Hello World!"; @Before @@ -46,4 +46,5 @@ class AESEncryptServiceTest { new AESEncryptService("").encrypt(TEST_DATA, EncryptionMode.AES_GCM); } -} \ No newline at end of file +} + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorderTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorderTest.java index cf6866e..c80e3e0 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorderTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HostResolveRecorderTest.java @@ -28,19 +28,19 @@ public class HostResolveRecorderTest { public void canNotBeginResolveSameHostTwice() { String host = RandomValue.randomHost(); - MatcherAssert.assertThat("host没有解析时,可以成功开始解析", recorder.beginResolve(host, RequestIpType.v4)); - MatcherAssert.assertThat("host解析时,不可以再解析", !recorder.beginResolve(host, RequestIpType.v4)); + MatcherAssert.assertThat("host娌℃湁瑙f瀽鏃讹紝鍙互鎴愬姛寮€濮嬭В鏋?, recorder.beginResolve(host, RequestIpType.v4)); + MatcherAssert.assertThat("host瑙f瀽鏃讹紝涓嶅彲浠ュ啀瑙f瀽", !recorder.beginResolve(host, RequestIpType.v4)); recorder.endResolve(host, RequestIpType.v4); - MatcherAssert.assertThat("host解析完之后,可以再次开始解析", recorder.beginResolve(host, RequestIpType.v4)); - MatcherAssert.assertThat("可以同时解析v4 v6", recorder.beginResolve(host, RequestIpType.v6)); - MatcherAssert.assertThat("解析v4 v6时,不可以再次解析v4 v6", !recorder.beginResolve(host, RequestIpType.both)); + MatcherAssert.assertThat("host瑙f瀽瀹屼箣鍚庯紝鍙互鍐嶆寮€濮嬭В鏋?, recorder.beginResolve(host, RequestIpType.v4)); + MatcherAssert.assertThat("鍙互鍚屾椂瑙f瀽v4 v6", recorder.beginResolve(host, RequestIpType.v6)); + MatcherAssert.assertThat("瑙f瀽v4 v6鏃讹紝涓嶅彲浠ュ啀娆¤В鏋恦4 v6", !recorder.beginResolve(host, RequestIpType.both)); recorder.endResolve(host, RequestIpType.v6); - MatcherAssert.assertThat("解析v4时,可以再一起解析v4 v6", recorder.beginResolve(host, RequestIpType.both)); + MatcherAssert.assertThat("瑙f瀽v4鏃讹紝鍙互鍐嶄竴璧疯В鏋恦4 v6", recorder.beginResolve(host, RequestIpType.both)); recorder.endResolve(host, RequestIpType.v4); - MatcherAssert.assertThat("一起解析时,不可以再解析v4", !recorder.beginResolve(host, RequestIpType.v4)); - MatcherAssert.assertThat("一起解析时,不可以再解析v6", !recorder.beginResolve(host, RequestIpType.v6)); + MatcherAssert.assertThat("涓€璧疯В鏋愭椂锛屼笉鍙互鍐嶈В鏋恦4", !recorder.beginResolve(host, RequestIpType.v4)); + MatcherAssert.assertThat("涓€璧疯В鏋愭椂锛屼笉鍙互鍐嶈В鏋恦6", !recorder.beginResolve(host, RequestIpType.v6)); recorder.endResolve(host, RequestIpType.both); - MatcherAssert.assertThat("host解析完之后,可以再次开始解析", recorder.beginResolve(host, RequestIpType.v6)); + MatcherAssert.assertThat("host瑙f瀽瀹屼箣鍚庯紝鍙互鍐嶆寮€濮嬭В鏋?, recorder.beginResolve(host, RequestIpType.v6)); recorder.endResolve(host, RequestIpType.v6); } @@ -51,13 +51,13 @@ public class HostResolveRecorderTest { String cacheKey1 = null; String cacheKey2 = RandomValue.randomStringWithFixedLength(8); String cacheKey3 = RandomValue.randomStringWithFixedLength(8); - MatcherAssert.assertThat("host没有解析时,可以成功开始解析", recorder.beginResolve(host, RequestIpType.v4, cacheKey1)); - MatcherAssert.assertThat("有和没有cacheKey的解析状态单独计算", recorder.beginResolve(host, RequestIpType.v4, cacheKey2)); - MatcherAssert.assertThat("不同cacheKey的解析状态单独计算", recorder.beginResolve(host, RequestIpType.v4, cacheKey3)); - MatcherAssert.assertThat("默认cacheKey为null", !recorder.beginResolve(host, RequestIpType.v4)); - MatcherAssert.assertThat("相同cacheKey,v4 v6状态单独计算", recorder.beginResolve(host, RequestIpType.v6, cacheKey2)); + MatcherAssert.assertThat("host娌℃湁瑙f瀽鏃讹紝鍙互鎴愬姛寮€濮嬭В鏋?, recorder.beginResolve(host, RequestIpType.v4, cacheKey1)); + MatcherAssert.assertThat("鏈夊拰娌℃湁cacheKey鐨勮В鏋愮姸鎬佸崟鐙绠?, recorder.beginResolve(host, RequestIpType.v4, cacheKey2)); + MatcherAssert.assertThat("涓嶅悓cacheKey鐨勮В鏋愮姸鎬佸崟鐙绠?, recorder.beginResolve(host, RequestIpType.v4, cacheKey3)); + MatcherAssert.assertThat("榛樿cacheKey涓簄ull", !recorder.beginResolve(host, RequestIpType.v4)); + MatcherAssert.assertThat("鐩稿悓cacheKey锛寁4 v6鐘舵€佸崟鐙绠?, recorder.beginResolve(host, RequestIpType.v6, cacheKey2)); recorder.endResolve(host, RequestIpType.v4, cacheKey2); - MatcherAssert.assertThat("其它和没有cacheKey时逻辑一致", recorder.beginResolve(host, RequestIpType.both, cacheKey2)); + MatcherAssert.assertThat("鍏跺畠鍜屾病鏈塩acheKey鏃堕€昏緫涓€鑷?, recorder.beginResolve(host, RequestIpType.both, cacheKey2)); } @Test @@ -110,8 +110,9 @@ public class HostResolveRecorderTest { } for (String host : hosts) { - MatcherAssert.assertThat("状态应该保持一致,最终可以再次解析", recorder.beginResolve(host, RequestIpType.v4)); - MatcherAssert.assertThat("状态应该保持一致,最终可以再次解析", recorder.beginResolve(host, RequestIpType.v6)); + MatcherAssert.assertThat("鐘舵€佸簲璇ヤ繚鎸佷竴鑷达紝鏈€缁堝彲浠ュ啀娆¤В鏋?, recorder.beginResolve(host, RequestIpType.v4)); + MatcherAssert.assertThat("鐘舵€佸簲璇ヤ繚鎸佷竴鑷达紝鏈€缁堝彲浠ュ啀娆¤В鏋?, recorder.beginResolve(host, RequestIpType.v6)); } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfigTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfigTest.java index 44061c5..5992818 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfigTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsConfigTest.java @@ -134,14 +134,14 @@ public class HttpDnsConfigTest { config.getCurrentServer().markOkServer(config.getCurrentServer().getServerIp(), config.getCurrentServer().getPort()); HttpDnsConfig another = new HttpDnsConfig(RuntimeEnvironment.application, account); - MatcherAssert.assertThat("当前服务更新后会缓存到本地,再次创建时读取缓存", another.getCurrentServer().getServerIp(), Matchers.equalTo(config.getCurrentServer().getServerIp())); - MatcherAssert.assertThat("当前服务更新后会缓存到本地,再次创建时读取缓存", another.getCurrentServer().getPort(), Matchers.equalTo(config.getCurrentServer().getPort())); + MatcherAssert.assertThat("褰撳墠鏈嶅姟鏇存柊鍚庝細缂撳瓨鍒版湰鍦帮紝鍐嶆鍒涘缓鏃惰鍙栫紦瀛?, another.getCurrentServer().getServerIp(), Matchers.equalTo(config.getCurrentServer().getServerIp())); + MatcherAssert.assertThat("褰撳墠鏈嶅姟鏇存柊鍚庝細缂撳瓨鍒版湰鍦帮紝鍐嶆鍒涘缓鏃惰鍙栫紦瀛?, another.getCurrentServer().getPort(), Matchers.equalTo(config.getCurrentServer().getPort())); config.getCurrentServer().setServerIps(null, RandomValue.randomIpv4s(), RandomValue.randomPorts(), null, null); another = new HttpDnsConfig(RuntimeEnvironment.application, account); - MatcherAssert.assertThat("服务更新后会缓存到本地,再次创建时读取缓存", another.getCurrentServer().getServerIp(), Matchers.equalTo(config.getCurrentServer().getServerIp())); - MatcherAssert.assertThat("服务更新后会缓存到本地,再次创建时读取缓存", another.getCurrentServer().getPort(), Matchers.equalTo(config.getCurrentServer().getPort())); + MatcherAssert.assertThat("鏈嶅姟鏇存柊鍚庝細缂撳瓨鍒版湰鍦帮紝鍐嶆鍒涘缓鏃惰鍙栫紦瀛?, another.getCurrentServer().getServerIp(), Matchers.equalTo(config.getCurrentServer().getServerIp())); + MatcherAssert.assertThat("鏈嶅姟鏇存柊鍚庝細缂撳瓨鍒版湰鍦帮紝鍐嶆鍒涘缓鏃惰鍙栫紦瀛?, another.getCurrentServer().getPort(), Matchers.equalTo(config.getCurrentServer().getPort())); } @Test @@ -149,37 +149,38 @@ public class HttpDnsConfigTest { String otherRegion = Constants.REGION_HK; - // 这一条验证和HttpDnsConfig无关 - MatcherAssert.assertThat("默认region是通过gradle配置的", Constants.REGION_DEFAULT, Matchers.is(Matchers.equalTo(BuildConfig.DEFAULT_REGION))); + // 杩欎竴鏉¢獙璇佸拰HttpDnsConfig鏃犲叧 + MatcherAssert.assertThat("榛樿region鏄€氳繃gradle閰嶇疆鐨?, Constants.REGION_DEFAULT, Matchers.is(Matchers.equalTo(BuildConfig.DEFAULT_REGION))); - // HttpDnsConfig默认的region应该和测试方法setInitServer的值一致 - MatcherAssert.assertThat("默认region正确", config.getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); - MatcherAssert.assertThat("默认服务节点的region是默认region", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); - MatcherAssert.assertThat("默认配置是region匹配", config.isCurrentRegionMatch(), Matchers.is(true)); + // HttpDnsConfig榛樿鐨剅egion搴旇鍜屾祴璇曟柟娉晄etInitServer鐨勫€间竴鑷? + MatcherAssert.assertThat("榛樿region姝g‘", config.getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); + MatcherAssert.assertThat("榛樿鏈嶅姟鑺傜偣鐨剅egion鏄粯璁egion", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); + MatcherAssert.assertThat("榛樿閰嶇疆鏄痳egion鍖归厤", config.isCurrentRegionMatch(), Matchers.is(true)); String regionBak = config.getRegion(); config.setRegion(otherRegion); - MatcherAssert.assertThat("setRegion 更新成功", config.getRegion(), Matchers.is(Matchers.equalTo(otherRegion))); - MatcherAssert.assertThat("setRegion不影响服务节点的region", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(regionBak))); - MatcherAssert.assertThat("setRegion 导致region不匹配", config.isCurrentRegionMatch(), Matchers.is(false)); + MatcherAssert.assertThat("setRegion 鏇存柊鎴愬姛", config.getRegion(), Matchers.is(Matchers.equalTo(otherRegion))); + MatcherAssert.assertThat("setRegion涓嶅奖鍝嶆湇鍔¤妭鐐圭殑region", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(regionBak))); + MatcherAssert.assertThat("setRegion 瀵艰嚧region涓嶅尮閰?, config.isCurrentRegionMatch(), Matchers.is(false)); config.getCurrentServer().setServerIps(otherRegion, RandomValue.randomIpv4s(), RandomValue.randomPorts(), null, null); - MatcherAssert.assertThat("setServerIps更像服务节点", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(otherRegion))); - MatcherAssert.assertThat("服务节点更新后,region匹配", config.isCurrentRegionMatch(), Matchers.is(true)); + MatcherAssert.assertThat("setServerIps鏇村儚鏈嶅姟鑺傜偣", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(otherRegion))); + MatcherAssert.assertThat("鏈嶅姟鑺傜偣鏇存柊鍚庯紝region鍖归厤", config.isCurrentRegionMatch(), Matchers.is(true)); regionBak = config.getRegion(); config.setRegion(REGION_DEFAULT); - MatcherAssert.assertThat("setRegion 更新成功", config.getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); - MatcherAssert.assertThat("setRegion不影响服务节点的region", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(regionBak))); - MatcherAssert.assertThat("setRegion 导致region不匹配", config.isCurrentRegionMatch(), Matchers.is(false)); + MatcherAssert.assertThat("setRegion 鏇存柊鎴愬姛", config.getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); + MatcherAssert.assertThat("setRegion涓嶅奖鍝嶆湇鍔¤妭鐐圭殑region", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(regionBak))); + MatcherAssert.assertThat("setRegion 瀵艰嚧region涓嶅尮閰?, config.isCurrentRegionMatch(), Matchers.is(false)); config.getCurrentServer().setServerIps(REGION_DEFAULT, RandomValue.randomIpv4s(), RandomValue.randomPorts(), null, null); - MatcherAssert.assertThat("setServerIps更新服务节点", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); - MatcherAssert.assertThat("服务节点更新后,region匹配", config.isCurrentRegionMatch(), Matchers.is(true)); + MatcherAssert.assertThat("setServerIps鏇存柊鏈嶅姟鑺傜偣", config.getCurrentServer().getRegion(), Matchers.is(Matchers.equalTo(REGION_DEFAULT))); + MatcherAssert.assertThat("鏈嶅姟鑺傜偣鏇存柊鍚庯紝region鍖归厤", config.isCurrentRegionMatch(), Matchers.is(true)); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolderTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolderTest.java index 45b6a6b..b3915f3 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolderTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/HttpDnsInstanceHolderTest.java @@ -72,3 +72,4 @@ public class HttpDnsInstanceHolderTest { Mockito.verify(service2, Mockito.never()).setSecret(Mockito.anyString()); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/SignServiceTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/SignServiceTest.java index 68598cd..cef384b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/SignServiceTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/impl/SignServiceTest.java @@ -22,7 +22,7 @@ public class SignServiceTest { public void noSign() { SignService service = new SignService(null); HashMap params = service.getSigns(RandomValue.randomHost()); - MatcherAssert.assertThat("没有密钥不签名", params == null); + MatcherAssert.assertThat("娌℃湁瀵嗛挜涓嶇鍚?, params == null); } @Test @@ -33,14 +33,14 @@ public class SignServiceTest { HashMap params = service.getSigns(host); String t = params.get("t"); String s = params.get("s"); - MatcherAssert.assertThat("验证签名算法逻辑", s.equals(CommonUtil.getMD5String(host + "-" + secret + "-" + t))); + MatcherAssert.assertThat("楠岃瘉绛惧悕绠楁硶閫昏緫", s.equals(CommonUtil.getMD5String(host + "-" + secret + "-" + t))); String secret1 = RandomValue.randomStringWithFixedLength(10); service.setSecret(secret1); params = service.getSigns(host); t = params.get("t"); s = params.get("s"); - MatcherAssert.assertThat("验证密钥更新的情况", s.equals(CommonUtil.getMD5String(host + "-" + secret1 + "-" + t))); + MatcherAssert.assertThat("楠岃瘉瀵嗛挜鏇存柊鐨勬儏鍐?, s.equals(CommonUtil.getMD5String(host + "-" + secret1 + "-" + t))); } @Test @@ -54,12 +54,13 @@ public class SignServiceTest { HashMap params = service.getSigns(host); String t = params.get("t"); String s = params.get("s"); - MatcherAssert.assertThat("验证签名算法逻辑", s.equals(CommonUtil.getMD5String(host + "-" + secret + "-" + t))); + MatcherAssert.assertThat("楠岃瘉绛惧悕绠楁硶閫昏緫", s.equals(CommonUtil.getMD5String(host + "-" + secret + "-" + t))); long requestTime = Long.parseLong(t); long abs = Math.abs(requestTime - 10 - System.currentTimeMillis() / 1000 - 600); - MatcherAssert.assertThat("请求有效期是10分钟,设置的校正偏差是10s. 差距: " + abs, abs < 2); + MatcherAssert.assertThat("璇锋眰鏈夋晥鏈熸槸10鍒嗛挓锛岃缃殑鏍℃鍋忓樊鏄?0s. 宸窛锛?" + abs, abs < 2); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/log/HttpdnsLogTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/log/HttpdnsLogTest.java index ed11934..12ef7fd 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/log/HttpdnsLogTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/log/HttpdnsLogTest.java @@ -150,3 +150,4 @@ public class HttpdnsLogTest { ShadowLog.clear(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/probe/IPRankingTaskTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/probe/IPRankingTaskTest.java index 4fc1bb3..cfb013d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/probe/IPRankingTaskTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/probe/IPRankingTaskTest.java @@ -39,3 +39,4 @@ public class IPRankingTaskTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpExceptionTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpExceptionTest.java index a2725f5..b34aa7b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpExceptionTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpExceptionTest.java @@ -31,3 +31,4 @@ public class HttpExceptionTest { assertThat(exception.getMessage(), is(equalTo("hello"))); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTest.java index 4d0c4ef..1c87a9d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestTest.java @@ -78,3 +78,4 @@ public class HttpRequestTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcherTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcherTest.java index 4e1a759..37a60be 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcherTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWatcherTest.java @@ -43,3 +43,4 @@ public class HttpRequestWatcherTest { Mockito.verify(watcher, Mockito.never()).onSuccess(Mockito.eq(requestConfig), Mockito.any(HttpRequestConfig.class)); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapperTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapperTest.java index 5d214c6..67a2fbf 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapperTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/HttpRequestWrapperTest.java @@ -43,3 +43,4 @@ public class HttpRequestWrapperTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequestTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequestTest.java index cef2415..44efa85 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequestTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/request/RetryHttpRequestTest.java @@ -41,3 +41,4 @@ public class RetryHttpRequestTest { } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/BaseCategoryTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/BaseCategoryTest.java index 33739e7..2c920c3 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/BaseCategoryTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/BaseCategoryTest.java @@ -30,7 +30,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** - * 域名解析策略相同部分的测试 + * 鍩熷悕瑙f瀽绛栫暐鐩稿悓閮ㄥ垎鐨勬祴璇? * * @author zonglin.nzl * @date 2020/10/16 @@ -239,3 +239,4 @@ public class BaseCategoryTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/CategoryControllerTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/CategoryControllerTest.java index 73b41f7..767431b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/CategoryControllerTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/CategoryControllerTest.java @@ -63,3 +63,4 @@ public class CategoryControllerTest { categoryController.getCategory() instanceof NormalResolveCategory); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/HostFilterTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/HostFilterTest.java index 3202c4e..40fe005 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/HostFilterTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/HostFilterTest.java @@ -24,7 +24,8 @@ public class HostFilterTest { hostFilter.setFilter(filter); - MatcherAssert.assertThat("过滤的域名", hostFilter.isFiltered(blockHost)); - MatcherAssert.assertThat("不过滤的域名", hostFilter.isFiltered(blockHost)); + MatcherAssert.assertThat("杩囨护鐨勫煙鍚?, hostFilter.isFiltered(blockHost)); + MatcherAssert.assertThat("涓嶈繃婊ょ殑鍩熷悕", hostFilter.isFiltered(blockHost)); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/NormalCategoryTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/NormalCategoryTest.java index b03a57a..14c10a5 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/NormalCategoryTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/NormalCategoryTest.java @@ -6,7 +6,7 @@ import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; /** - * 域名解析任务的测试 + * 鍩熷悕瑙f瀽浠诲姟鐨勬祴璇? * * @author zonglin.nzl * @date 2020/10/16 @@ -34,3 +34,4 @@ public class NormalCategoryTest extends BaseCategoryTest { MatcherAssert.assertThat("normal category retry request when failed", requestTwice); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseTest.java index a5b8ac6..1a84dec 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResponseTest.java @@ -62,3 +62,4 @@ public class ResolveHostResponseTest { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest.java index 9a52597..dee112d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest.java @@ -62,67 +62,67 @@ public class ResolveHostResultRepoTest { } /** - * 解析结果的 存 读 清除 + * 瑙f瀽缁撴灉鐨?瀛?璇?娓呴櫎 */ @Test public void testSaveUpdateGet() { - MatcherAssert.assertThat("没有解析过的域名返回空", + MatcherAssert.assertThat("娌℃湁瑙f瀽杩囩殑鍩熷悕杩斿洖绌?, repo.getIps(host, RequestIpType.v4, null) == null); - MatcherAssert.assertThat("没有解析过的域名返回空", + MatcherAssert.assertThat("娌℃湁瑙f瀽杩囩殑鍩熷悕杩斿洖绌?, repo.getIps(host, RequestIpType.v6, null) == null); - MatcherAssert.assertThat("没有解析过的域名返回空", + MatcherAssert.assertThat("娌℃湁瑙f瀽杩囩殑鍩熷悕杩斿洖绌?, repo.getIps(host, RequestIpType.both, null) == null); ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse(host); repo.save(REGION_DEFAULT, host, RequestIpType.v4, null, null, response); - UnitTestUtil.assertIpsEqual("解析过的域名返回上次的解析结果", + UnitTestUtil.assertIpsEqual("瑙f瀽杩囩殑鍩熷悕杩斿洖涓婃鐨勮В鏋愮粨鏋?, repo.getIps(host, RequestIpType.v4, null).getIps(), response.getIps()); - MatcherAssert.assertThat("没有解析过的域名返回空", + MatcherAssert.assertThat("娌℃湁瑙f瀽杩囩殑鍩熷悕杩斿洖绌?, repo.getIps(host, RequestIpType.v6, null) == null); - MatcherAssert.assertThat("get方法传入both时,返回空", + MatcherAssert.assertThat("get鏂规硶浼犲叆both鏃讹紝杩斿洖绌?, repo.getIps(host, RequestIpType.both, null) == null); repo.save(REGION_DEFAULT, host, RequestIpType.v6, null, null, response); - UnitTestUtil.assertIpsEqual("解析过的域名返回上次的解析结果", + UnitTestUtil.assertIpsEqual("瑙f瀽杩囩殑鍩熷悕杩斿洖涓婃鐨勮В鏋愮粨鏋?, repo.getIps(host, RequestIpType.v4, null).getIps(), response.getIps()); - UnitTestUtil.assertIpsEqual("解析过的域名返回上次的解析结果", + UnitTestUtil.assertIpsEqual("瑙f瀽杩囩殑鍩熷悕杩斿洖涓婃鐨勮В鏋愮粨鏋?, repo.getIps(host, RequestIpType.v6, null).getIpv6s(), response.getIpsV6()); - UnitTestUtil.assertIpsEqual("get方法传入both时,返回ipv4 ipv6的结果", + UnitTestUtil.assertIpsEqual("get鏂规硶浼犲叆both鏃讹紝杩斿洖ipv4 ipv6鐨勭粨鏋?, repo.getIps(host, RequestIpType.both, null).getIps(), response.getIps()); - UnitTestUtil.assertIpsEqual("get方法传入both时,返回ipv4 ipv6的结果", + UnitTestUtil.assertIpsEqual("get鏂规硶浼犲叆both鏃讹紝杩斿洖ipv4 ipv6鐨勭粨鏋?, repo.getIps(host, RequestIpType.both, null).getIpv6s(), response.getIpsV6()); repo.update(host, RequestIpType.v4, null, ips); - UnitTestUtil.assertIpsEqual("更新结果之后再请求,返回更新后的结果", + UnitTestUtil.assertIpsEqual("鏇存柊缁撴灉涔嬪悗鍐嶈姹傦紝杩斿洖鏇存柊鍚庣殑缁撴灉", repo.getIps(host, RequestIpType.v4, null).getIps(), ips); repo.update(host, RequestIpType.v6, null, ipv6s); - UnitTestUtil.assertIpsEqual("更新结果之后再请求,返回更新后的结果", + UnitTestUtil.assertIpsEqual("鏇存柊缁撴灉涔嬪悗鍐嶈姹傦紝杩斿洖鏇存柊鍚庣殑缁撴灉", repo.getIps(host, RequestIpType.v6, null).getIpv6s(), ipv6s); ResolveHostResponse response1 = ResolveHostServer.randomResolveHostResponse(host); repo.save(REGION_DEFAULT, host, RequestIpType.both, null, null, response1); - UnitTestUtil.assertIpsEqual("新的解析结果会覆盖原来的解析结果", + UnitTestUtil.assertIpsEqual("鏂扮殑瑙f瀽缁撴灉浼氳鐩栧師鏉ョ殑瑙f瀽缁撴灉", repo.getIps(host, RequestIpType.v4, null).getIps(), response1.getIps()); - UnitTestUtil.assertIpsEqual("新的解析结果会覆盖原来的解析结果", + UnitTestUtil.assertIpsEqual("鏂扮殑瑙f瀽缁撴灉浼氳鐩栧師鏉ョ殑瑙f瀽缁撴灉", repo.getIps(host, RequestIpType.v6, null).getIpv6s(), response1.getIpsV6()); - UnitTestUtil.assertIpsEqual("新的解析结果会覆盖原来的解析结果", + UnitTestUtil.assertIpsEqual("鏂扮殑瑙f瀽缁撴灉浼氳鐩栧師鏉ョ殑瑙f瀽缁撴灉", repo.getIps(host, RequestIpType.both, null).getIps(), response1.getIps()); - UnitTestUtil.assertIpsEqual("新的解析结果会覆盖原来的解析结果", + UnitTestUtil.assertIpsEqual("鏂扮殑瑙f瀽缁撴灉浼氳鐩栧師鏉ョ殑瑙f瀽缁撴灉", repo.getIps(host, RequestIpType.both, null).getIpv6s(), response1.getIpsV6()); repo.clear(); - MatcherAssert.assertThat("清除记录之后返回空", + MatcherAssert.assertThat("娓呴櫎璁板綍涔嬪悗杩斿洖绌?, repo.getIps(host, RequestIpType.v4, null) == null); - MatcherAssert.assertThat("清除记录之后返回空", + MatcherAssert.assertThat("娓呴櫎璁板綍涔嬪悗杩斿洖绌?, repo.getIps(host, RequestIpType.v6, null) == null); - MatcherAssert.assertThat("清除记录之后返回空", + MatcherAssert.assertThat("娓呴櫎璁板綍涔嬪悗杩斿洖绌?, repo.getIps(host, RequestIpType.both, null) == null); } /** - * 解析结果的 存储 更新 本地缓存 + * 瑙f瀽缁撴灉鐨?瀛樺偍 鏇存柊 鏈湴缂撳瓨 * * @throws JSONException */ @@ -138,7 +138,7 @@ public class ResolveHostResultRepoTest { HashMap cacheKeys = new HashMap<>(); HashMap extras = new HashMap<>(); - // 存储预解析数据 + // 瀛樺偍棰勮В鏋愭暟鎹? for (int k = 0; k < 3; k++) { RequestIpType type = RequestIpType.values()[k]; int preCount = RandomValue.randomInt(10) + 5; @@ -168,7 +168,7 @@ public class ResolveHostResultRepoTest { } } - // 存储解析数据 + // 瀛樺偍瑙f瀽鏁版嵁 for (int i = 0; i < 50; i++) { String host = RandomValue.randomHost(); ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse(host); @@ -184,7 +184,7 @@ public class ResolveHostResultRepoTest { } ArrayList hosts = new ArrayList<>(responses.keySet()); - // 更新30个记录 + // 鏇存柊30涓褰? for (int i = 0; i < 30; i++) { String host = hosts.get(RandomValue.randomInt(hosts.size())); ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse(host); @@ -193,7 +193,7 @@ public class ResolveHostResultRepoTest { responses.put(host, response); } - // 更新30个ip记录 + // 鏇存柊30涓猧p璁板綍 for (int i = 0; i < 30; i++) { String host = hosts.get(RandomValue.randomInt(hosts.size())); if (types.get(host) != RequestIpType.v6) { @@ -216,22 +216,22 @@ public class ResolveHostResultRepoTest { for (String host : hosts) { HTTPDNSResult result = anotherRepo.getIps(host, types.get(host), cacheKeys.get(host)); if (types.get(host) != RequestIpType.v4) { - UnitTestUtil.assertIpsEqual("测试repo本地缓存", result.getIpv6s(), + UnitTestUtil.assertIpsEqual("娴嬭瘯repo鏈湴缂撳瓨", result.getIpv6s(), responses.get(host).getIpsV6()); } if (types.get(host) != RequestIpType.v6) { - UnitTestUtil.assertIpsEqual("测试repo本地缓存", result.getIps(), + UnitTestUtil.assertIpsEqual("娴嬭瘯repo鏈湴缂撳瓨", result.getIps(), responses.get(host).getIps()); } if (cacheKeys.get(host) != null) { - assertExtras("测试repo本地缓存", result.getExtras(), + assertExtras("娴嬭瘯repo鏈湴缂撳瓨", result.getExtras(), responses.get(host).getExtras()); } } } /** - * 测试定制ttl + * 娴嬭瘯瀹氬埗ttl * * @throws InterruptedException */ @@ -249,7 +249,7 @@ public class ResolveHostResultRepoTest { originTtl); repo.save(REGION_DEFAULT, host, RequestIpType.v4, null, null, response); Thread.sleep(1000); - MatcherAssert.assertThat("没有设置ttlChanger时,ttl是" + originTtl + ", 1s内不会过期", + MatcherAssert.assertThat("娌℃湁璁剧疆ttlChanger鏃讹紝ttl鏄? + originTtl + ", 1s鍐呬笉浼氳繃鏈?, !repo.getIps(host, RequestIpType.v4, null).isExpired()); repo.setCacheTtlChanger(changer); @@ -259,14 +259,14 @@ public class ResolveHostResultRepoTest { // RequestIpType.v4, null).isExpired()); Thread.sleep(1001); // TestLogger.log("end " + System.currentTimeMillis()); - MatcherAssert.assertThat("设置ttlChanger时,ttl是" + changedTtl + ", 1s会过期", + MatcherAssert.assertThat("璁剧疆ttlChanger鏃讹紝ttl鏄? + changedTtl + ", 1s浼氳繃鏈?, repo.getIps(host, RequestIpType.v4, null).isExpired()); Mockito.verify(changer).changeCacheTtl(host, RequestIpType.v4, originTtl); repo.setCacheTtlChanger(null); repo.save(REGION_DEFAULT, host, RequestIpType.v4, null, null, response); Thread.sleep(1000); - MatcherAssert.assertThat("移除ttlchanger后,ttl是" + originTtl + ", 1s不会过期", + MatcherAssert.assertThat("绉婚櫎ttlchanger鍚庯紝ttl鏄? + originTtl + ", 1s涓嶄細杩囨湡", !repo.getIps(host, RequestIpType.v4, null).isExpired()); final String resolveHost = RandomValue.randomHost(); @@ -282,14 +282,14 @@ public class ResolveHostResultRepoTest { repo.save(REGION_DEFAULT, RequestIpType.v4, resolveHostResponse); Mockito.verify(changer).changeCacheTtl(resolveHost, RequestIpType.v4, originTtl); Thread.sleep(1001); - MatcherAssert.assertThat("设置ttlChanger时,ttl是" + changedTtl + ", 1s会过期", + MatcherAssert.assertThat("璁剧疆ttlChanger鏃讹紝ttl鏄? + changedTtl + ", 1s浼氳繃鏈?, repo.getIps(resolveHost, RequestIpType.v4, null).isExpired()); Mockito.verify(changer).changeCacheTtl(resolveHost, RequestIpType.v4, originTtl); } /** - * 清理特定host的缓存 + * 娓呯悊鐗瑰畾host鐨勭紦瀛? */ @Test public void testClearTargetHosts() { @@ -324,18 +324,18 @@ public class ResolveHostResultRepoTest { repo.clear(hostToBeClear); for (String hostCleared : hostToBeClear) { - MatcherAssert.assertThat("清除缓存后没有数据", + MatcherAssert.assertThat("娓呴櫎缂撳瓨鍚庢病鏈夋暟鎹?, repo.getIps(hostCleared, RequestIpType.v4, null) == null); } for (String hostNotCleared : hostNotClear) { - MatcherAssert.assertThat("未清除缓存的域名有数据", + MatcherAssert.assertThat("鏈竻闄ょ紦瀛樼殑鍩熷悕鏈夋暟鎹?, repo.getIps(hostNotCleared, RequestIpType.v4, null) != null); } } /** - * 清理内存缓存 + * 娓呯悊鍐呭瓨缂撳瓨 */ @Test public void testClearMemoryCache() { @@ -345,34 +345,34 @@ public class ResolveHostResultRepoTest { for (int i = 0; i < 5; i++) { hosts.add(RandomValue.randomHost()); } - // 开启本地缓存 + // 寮€鍚湰鍦扮紦瀛? repo.setCachedIPEnabled(true, false); - // 触发缓存 + // 瑙﹀彂缂撳瓨 repo.save(REGION_DEFAULT, host, RequestIpType.v4, null, null, response); repo.save(REGION_DEFAULT, RequestIpType.v4, BatchResolveHostServer.randomResolveHostResponse(hosts, RequestIpType.v4)); - // 清除内存缓存 + // 娓呴櫎鍐呭瓨缂撳瓨 repo.clearMemoryCache(); - MatcherAssert.assertThat("清除缓存后没有数据", + MatcherAssert.assertThat("娓呴櫎缂撳瓨鍚庢病鏈夋暟鎹?, repo.getIps(host, RequestIpType.v4, null) == null); - // 再次设置开启本地缓存,触发读取本地缓存操作 + // 鍐嶆璁剧疆寮€鍚湰鍦扮紦瀛橈紝瑙﹀彂璇诲彇鏈湴缂撳瓨鎿嶄綔 repo.setCachedIPEnabled(true, false); try { worker.await(); } catch (InterruptedException e) { e.printStackTrace(); } - UnitTestUtil.assertIpsEqual("本地缓存不会被清除", + UnitTestUtil.assertIpsEqual("鏈湴缂撳瓨涓嶄細琚竻闄?, repo.getIps(host, RequestIpType.v4, null).getIps(), response.getIps()); for (String tmp : hosts) { - MatcherAssert.assertThat("本地缓存不会被清除", + MatcherAssert.assertThat("鏈湴缂撳瓨涓嶄細琚竻闄?, repo.getIps(tmp, RequestIpType.v4, null) != null); } } /** - * 测试 主站域名的本地缓存,强制开启 + * 娴嬭瘯 涓荤珯鍩熷悕鐨勬湰鍦扮紦瀛橈紝寮哄埗寮€鍚? */ @Test public void testDiskCacheForHostWithFixedIP() { @@ -394,12 +394,12 @@ public class ResolveHostResultRepoTest { } } - // 设置主站域名 + // 璁剧疆涓荤珯鍩熷悕 repo.setHostListWhichIpFixed(hostsWithFixedIP); - // 关闭本地缓存,避免干扰 + // 鍏抽棴鏈湴缂撳瓨锛岄伩鍏嶅共鎵? repo.setCachedIPEnabled(false, false); - // 触发缓存 + // 瑙﹀彂缂撳瓨 repo.save(REGION_DEFAULT, hostWithFixedIP, RequestIpType.v4, null, null, responseForHostWithFixedIP); repo.save(REGION_DEFAULT, hostWithoutFixedIP, RequestIpType.v4, null, null, @@ -408,16 +408,16 @@ public class ResolveHostResultRepoTest { BatchResolveHostServer.randomResolveHostResponse(hosts, RequestIpType.v4)); String[] updatedIps = RandomValue.randomIpv4s(); repo.update(hostWithFixedIP, RequestIpType.v4, null, updatedIps); - // 等待本地缓存完成 + // 绛夊緟鏈湴缂撳瓨瀹屾垚 try { worker.await(); } catch (InterruptedException e) { e.printStackTrace(); } - // 清除内存缓存 + // 娓呴櫎鍐呭瓨缂撳瓨 repo.clearMemoryCache(); - // 再次设置开启本地缓存,触发读取本地缓存操作 + // 鍐嶆璁剧疆寮€鍚湰鍦扮紦瀛橈紝瑙﹀彂璇诲彇鏈湴缂撳瓨鎿嶄綔 repo.setCachedIPEnabled(true, false); try { worker.await(); @@ -425,18 +425,18 @@ public class ResolveHostResultRepoTest { e.printStackTrace(); } - MatcherAssert.assertThat("非主站域名缓存不存在", + MatcherAssert.assertThat("闈炰富绔欏煙鍚嶇紦瀛樹笉瀛樺湪", repo.getIps(hostWithoutFixedIP, RequestIpType.v4, null) == null); for (String tmp : hostsWithFixedIP) { - MatcherAssert.assertThat("主站域名从本地缓存恢复", + MatcherAssert.assertThat("涓荤珯鍩熷悕浠庢湰鍦扮紦瀛樻仮澶?, repo.getIps(tmp, RequestIpType.v4, null) != null); } - UnitTestUtil.assertIpsEqual("主站域名从本地缓存恢复", + UnitTestUtil.assertIpsEqual("涓荤珯鍩熷悕浠庢湰鍦扮紦瀛樻仮澶?, repo.getIps(hostWithFixedIP, RequestIpType.v4, null).getIps(), updatedIps); } /** - * 测试 清除非主站域名的内存缓存 + * 娴嬭瘯 娓呴櫎闈炰富绔欏煙鍚嶇殑鍐呭瓨缂撳瓨 */ @Test public void testClearMemoryCacheForHostWithoutFixedIP() { @@ -447,21 +447,21 @@ public class ResolveHostResultRepoTest { repo.setHostListWhichIpFixed(hostListWithFixedIP); - // 触发缓存 + // 瑙﹀彂缂撳瓨 repo.save(REGION_DEFAULT, hostWithFixedIP, RequestIpType.v4, null, null, ResolveHostServer.randomResolveHostResponse(hostWithFixedIP)); repo.save(REGION_DEFAULT, hostWithoutFixedIP, RequestIpType.v4, null, null, ResolveHostServer.randomResolveHostResponse(hostWithoutFixedIP)); - // 清除内存缓存 + // 娓呴櫎鍐呭瓨缂撳瓨 repo.clearMemoryCacheForHostWithoutFixedIP(); - MatcherAssert.assertThat("主站域名没有被清除", + MatcherAssert.assertThat("涓荤珯鍩熷悕娌℃湁琚竻闄?, repo.getIps(hostWithFixedIP, RequestIpType.v4, null) != null); - MatcherAssert.assertThat("清除缓存后没有数据", + MatcherAssert.assertThat("娓呴櫎缂撳瓨鍚庢病鏈夋暟鎹?, repo.getIps(hostWithoutFixedIP, RequestIpType.v4, null) == null); } /** - * 获取已缓存解析结果的非主站域名 + * 鑾峰彇宸茬紦瀛樿В鏋愮粨鏋滅殑闈炰富绔欏煙鍚? */ @Test public void testGetAllHostWithoutFixedIP() { @@ -472,15 +472,15 @@ public class ResolveHostResultRepoTest { repo.setHostListWhichIpFixed(hostListWithFixedIP); - // 触发缓存 + // 瑙﹀彂缂撳瓨 repo.save(REGION_DEFAULT, hostWithFixedIP, RequestIpType.v4, null, null, ResolveHostServer.randomResolveHostResponse(hostWithFixedIP)); repo.save(REGION_DEFAULT, hostWithoutFixedIP, RequestIpType.v4, null, null, ResolveHostServer.randomResolveHostResponse(hostWithoutFixedIP)); HashMap result = repo.getAllHostWithoutFixedIP(); - MatcherAssert.assertThat("仅能获取一个非主站域名", result.size() == 1); - MatcherAssert.assertThat("仅能获取非主站域名", result.get(hostWithoutFixedIP), + MatcherAssert.assertThat("浠呰兘鑾峰彇涓€涓潪涓荤珯鍩熷悕", result.size() == 1); + MatcherAssert.assertThat("浠呰兘鑾峰彇闈炰富绔欏煙鍚?, result.get(hostWithoutFixedIP), Matchers.is(RequestIpType.v4)); } @@ -496,3 +496,4 @@ public class ResolveHostResultRepoTest { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest2.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest2.java index dc8ff1d..022add1 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest2.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ResolveHostResultRepoTest2.java @@ -23,11 +23,11 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** - * 在性能测试时,我们发现 - * 1. 性能问题出在我们频繁的创建对象 HTTPDNSResult - * 2. 性能问题出在我们频繁的创建对象 缓存的key 是动态生成的 + * 鍦ㄦ€ц兘娴嬭瘯鏃讹紝鎴戜滑鍙戠幇 + * 1. 鎬ц兘闂鍑哄湪鎴戜滑棰戠箒鐨勫垱寤哄璞?HTTPDNSResult + * 2. 鎬ц兘闂鍑哄湪鎴戜滑棰戠箒鐨勫垱寤哄璞?缂撳瓨鐨刱ey 鏄姩鎬佺敓鎴愮殑 *

- * 所以我们期望,缓存如果命中,就不应该产生任何对象创建 + * 鎵€浠ユ垜浠湡鏈涳紝缂撳瓨濡傛灉鍛戒腑锛屽氨涓嶅簲璇ヤ骇鐢熶换浣曞璞″垱寤? * * @author zonglin.nzl * @date 11/8/21 @@ -51,7 +51,7 @@ public class ResolveHostResultRepoTest2 { } /** - * 命中缓存 使用相同的对象 + * 鍛戒腑缂撳瓨 浣跨敤鐩稿悓鐨勫璞? */ @Test public void cacheHitWillReturnSameObject() { @@ -63,12 +63,12 @@ public class ResolveHostResultRepoTest2 { HTTPDNSResult result = repo.getIps(host, RequestIpType.v4, null); HTTPDNSResult result1 = repo.getIps(host, RequestIpType.v4, null); - MatcherAssert.assertThat("缓存命中,应该返回相同的对象", result == result1); + MatcherAssert.assertThat("缂撳瓨鍛戒腑锛屽簲璇ヨ繑鍥炵浉鍚岀殑瀵硅薄", result == result1); } /** - * 更新时,更新对象的属性,不修改对象 + * 鏇存柊鏃讹紝鏇存柊瀵硅薄鐨勫睘鎬э紝涓嶄慨鏀瑰璞? */ @Test public void saveWillUpdateCacheContentNotInstance() { @@ -79,19 +79,19 @@ public class ResolveHostResultRepoTest2 { HTTPDNSResult result = repo.getIps(host, RequestIpType.v4, null); - MatcherAssert.assertThat("开始时,缓存是 " + ip1, result.getIps()[0], Matchers.is(Matchers.equalTo(ip1))); + MatcherAssert.assertThat("寮€濮嬫椂锛岀紦瀛樻槸 " + ip1, result.getIps()[0], Matchers.is(Matchers.equalTo(ip1))); String ip2 = RandomValue.randomIpv4(); repo.save(REGION_DEFAULT, host, RequestIpType.v4, null, null, new ResolveHostResponse(host, new String[]{ip2}, null, 60, null)); HTTPDNSResult result1 = repo.getIps(host, RequestIpType.v4, null); - MatcherAssert.assertThat("缓存更新", result1.getIps()[0], Matchers.is(Matchers.equalTo(ip2))); - MatcherAssert.assertThat("缓存更新时,更新的是缓存内容,不重新创建缓存对象", result == result1); + MatcherAssert.assertThat("缂撳瓨鏇存柊", result1.getIps()[0], Matchers.is(Matchers.equalTo(ip2))); + MatcherAssert.assertThat("缂撳瓨鏇存柊鏃讹紝鏇存柊鐨勬槸缂撳瓨鍐呭锛屼笉閲嶆柊鍒涘缓缂撳瓨瀵硅薄", result == result1); } /** - * 超过ttl 会过期 + * 瓒呰繃ttl 浼氳繃鏈? * @throws InterruptedException */ @Test @@ -102,11 +102,12 @@ public class ResolveHostResultRepoTest2 { HTTPDNSResult result = repo.getIps(host, RequestIpType.v4, null); - MatcherAssert.assertThat("在ttl时间内,不过期", result.isExpired(), Matchers.is(false)); + MatcherAssert.assertThat("鍦╰tl鏃堕棿鍐咃紝涓嶈繃鏈?, result.isExpired(), Matchers.is(false)); Thread.sleep(1100); result = repo.getIps(host, RequestIpType.v4, null); - MatcherAssert.assertThat("超过ttl时间过期", result.isExpired(), Matchers.is(true)); + MatcherAssert.assertThat("瓒呰繃ttl鏃堕棿杩囨湡", result.isExpired(), Matchers.is(true)); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcherTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcherTest.java index b616885..87bd21e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcherTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/ShiftServerWatcherTest.java @@ -112,3 +112,4 @@ public class ShiftServerWatcherTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/SniffCategoryTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/SniffCategoryTest.java index e2f4034..b91191e 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/SniffCategoryTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/resolve/SniffCategoryTest.java @@ -62,3 +62,4 @@ public class SniffCategoryTest extends BaseCategoryTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/ServerIpRepoTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/ServerIpRepoTest.java index 88efbb1..7273663 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/ServerIpRepoTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/ServerIpRepoTest.java @@ -21,24 +21,24 @@ public class ServerIpRepoTest { @Test public void saveAndGet() { - MatcherAssert.assertThat("没有数据时应该返回null", repo.getServerIps(null) == null); - MatcherAssert.assertThat("没有数据时应该返回null", repo.getPorts(null) == null); - MatcherAssert.assertThat("没有数据时应该返回null", repo.getServerIps("") == null); - MatcherAssert.assertThat("没有数据时应该返回null", repo.getPorts("") == null); + MatcherAssert.assertThat("娌℃湁鏁版嵁鏃跺簲璇ヨ繑鍥瀗ull", repo.getServerIps(null) == null); + MatcherAssert.assertThat("娌℃湁鏁版嵁鏃跺簲璇ヨ繑鍥瀗ull", repo.getPorts(null) == null); + MatcherAssert.assertThat("娌℃湁鏁版嵁鏃跺簲璇ヨ繑鍥瀗ull", repo.getServerIps("") == null); + MatcherAssert.assertThat("娌℃湁鏁版嵁鏃跺簲璇ヨ繑鍥瀗ull", repo.getPorts("") == null); String hk = Constants.REGION_HK; String[] hkIps = RandomValue.randomIpv4s(); repo.save(hk, hkIps, null, null, null); - MatcherAssert.assertThat("应该可以正确获取存入的值", repo.getServerIps(hk), Matchers.arrayContaining(hkIps)); - MatcherAssert.assertThat("port没有设置就是null", repo.getPorts(hk) == null); + MatcherAssert.assertThat("搴旇鍙互姝g‘鑾峰彇瀛樺叆鐨勫€?, repo.getServerIps(hk), Matchers.arrayContaining(hkIps)); + MatcherAssert.assertThat("port娌℃湁璁剧疆灏辨槸null", repo.getPorts(hk) == null); String sg = "sg"; String[] sgIps = RandomValue.randomIpv4s(); int[] sgPorts = RandomValue.randomPorts(); repo.save(sg, sgIps, sgPorts, null, null); - MatcherAssert.assertThat("应该可以正确获取存入的值", repo.getServerIps(sg), Matchers.arrayContaining(sgIps)); + MatcherAssert.assertThat("搴旇鍙互姝g‘鑾峰彇瀛樺叆鐨勫€?, repo.getServerIps(sg), Matchers.arrayContaining(sgIps)); UnitTestUtil.assertIntArrayEquals(sgPorts, repo.getPorts(sg)); } @@ -49,14 +49,15 @@ public class ServerIpRepoTest { int[] sgPorts = RandomValue.randomPorts(); repo.save(sg, sgIps, sgPorts, null, null); - MatcherAssert.assertThat("应该可以正确获取存入的值", repo.getServerIps(sg), Matchers.arrayContaining(sgIps)); + MatcherAssert.assertThat("搴旇鍙互姝g‘鑾峰彇瀛樺叆鐨勫€?, repo.getServerIps(sg), Matchers.arrayContaining(sgIps)); UnitTestUtil.assertIntArrayEquals(sgPorts, repo.getPorts(sg)); Thread.sleep(1000); - MatcherAssert.assertThat("默认有效期是5分钟,当前应该可以获取到数据", repo.getServerIps(sg), Matchers.arrayContaining(sgIps)); + MatcherAssert.assertThat("榛樿鏈夋晥鏈熸槸5鍒嗛挓锛屽綋鍓嶅簲璇ュ彲浠ヨ幏鍙栧埌鏁版嵁", repo.getServerIps(sg), Matchers.arrayContaining(sgIps)); UnitTestUtil.assertIntArrayEquals(sgPorts, repo.getPorts(sg)); repo.setTimeInterval(500); - MatcherAssert.assertThat("超过有效期,应该返回null", repo.getServerIps(sg) == null); - MatcherAssert.assertThat("超过有效期,应该返回null", repo.getPorts(sg) == null); + MatcherAssert.assertThat("瓒呰繃鏈夋晥鏈燂紝搴旇杩斿洖null", repo.getServerIps(sg) == null); + MatcherAssert.assertThat("瓒呰繃鏈夋晥鏈燂紝搴旇杩斿洖null", repo.getPorts(sg) == null); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerLockerTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerLockerTest.java index fc617e3..30989d3 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerLockerTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerLockerTest.java @@ -24,12 +24,12 @@ public class UpdateServerLockerTest { UpdateRegionServerLocker locker = new UpdateRegionServerLocker(); String region = Constants.REGION_MAINLAND; - MatcherAssert.assertThat("允许第一个请求", locker.begin(region)); - MatcherAssert.assertThat("第一个请求,未完成,其它请求不处理", !locker.begin(region)); + MatcherAssert.assertThat("鍏佽绗竴涓姹?, locker.begin(region)); + MatcherAssert.assertThat("绗竴涓姹?鏈畬鎴愶紝鍏跺畠璇锋眰涓嶅鐞?, !locker.begin(region)); locker.end(region); - MatcherAssert.assertThat("第一个请求结束后,允许下次请求", locker.begin(region)); + MatcherAssert.assertThat("绗竴涓姹傜粨鏉熷悗锛屽厑璁镐笅娆¤姹?, locker.begin(region)); } @Test @@ -38,26 +38,26 @@ public class UpdateServerLockerTest { String region1 = Constants.REGION_HK; UpdateRegionServerLocker locker = new UpdateRegionServerLocker(); - MatcherAssert.assertThat("允许第一个请求", locker.begin(region)); - MatcherAssert.assertThat("允许第一个请求", locker.begin(region1)); - MatcherAssert.assertThat("第一个请求,未完成,其它请求不处理", !locker.begin(region)); - MatcherAssert.assertThat("第一个请求,未完成,其它请求不处理", !locker.begin(region1)); + MatcherAssert.assertThat("鍏佽绗竴涓姹?, locker.begin(region)); + MatcherAssert.assertThat("鍏佽绗竴涓姹?, locker.begin(region1)); + MatcherAssert.assertThat("绗竴涓姹?鏈畬鎴愶紝鍏跺畠璇锋眰涓嶅鐞?, !locker.begin(region)); + MatcherAssert.assertThat("绗竴涓姹?鏈畬鎴愶紝鍏跺畠璇锋眰涓嶅鐞?, !locker.begin(region1)); locker.end(region1); - MatcherAssert.assertThat("第一个请求结束后,允许下次请求", locker.begin(region1)); - MatcherAssert.assertThat("第一个请求,未完成,其它请求不处理", !locker.begin(region)); + MatcherAssert.assertThat("绗竴涓姹傜粨鏉熷悗锛屽厑璁镐笅娆¤姹?, locker.begin(region1)); + MatcherAssert.assertThat("绗竴涓姹?鏈畬鎴愶紝鍏跺畠璇锋眰涓嶅鐞?, !locker.begin(region)); } @Test public void timeout() throws InterruptedException { UpdateRegionServerLocker locker = new UpdateRegionServerLocker(10); String region = Constants.REGION_MAINLAND; - MatcherAssert.assertThat("允许第一个请求", locker.begin(region)); - MatcherAssert.assertThat("第一个请求,未完成,其它请求不处理", !locker.begin(region)); + MatcherAssert.assertThat("鍏佽绗竴涓姹?, locker.begin(region)); + MatcherAssert.assertThat("绗竴涓姹?鏈畬鎴愶紝鍏跺畠璇锋眰涓嶅鐞?, !locker.begin(region)); Thread.sleep(11); - // 设计上,我们在超时后第一次判断时,处理超时 - MatcherAssert.assertThat("第一个请求,未完成,其它请求不处理", !locker.begin(region)); - MatcherAssert.assertThat("超时,允许下一个请求", locker.begin(region)); + // 璁捐涓婏紝鎴戜滑鍦ㄨ秴鏃跺悗绗竴娆″垽鏂椂锛屽鐞嗚秴鏃? + MatcherAssert.assertThat("绗竴涓姹?鏈畬鎴愶紝鍏跺畠璇锋眰涓嶅鐞?, !locker.begin(region)); + MatcherAssert.assertThat("瓒呮椂锛屽厑璁镐笅涓€涓姹?, locker.begin(region)); } @@ -99,8 +99,9 @@ public class UpdateServerLockerTest { } int tmp = tmpRequesting.get(); - MatcherAssert.assertThat("同时只有一个成功", tmp == 0 || tmp == 1); + MatcherAssert.assertThat("鍚屾椂鍙湁涓€涓垚鍔?, tmp == 0 || tmp == 1); } })); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerResponseTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerResponseTest.java index 22278b1..7b6d6ed 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerResponseTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerResponseTest.java @@ -53,3 +53,4 @@ public class UpdateServerResponseTest { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerTaskTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerTaskTest.java index edfe434..dedc99f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerTaskTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/serverip/UpdateServerTaskTest.java @@ -28,7 +28,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** - * 更新服务IP任务 + * 鏇存柊鏈嶅姟IP浠诲姟 * * @author zonglin.nzl * @date 2020/10/19 @@ -113,3 +113,4 @@ public class UpdateServerTaskTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/app/BusinessApp.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/app/BusinessApp.java index 89f8d48..7e108d1 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/app/BusinessApp.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/app/BusinessApp.java @@ -50,7 +50,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** - * 模拟业务app + * 妯℃嫙涓氬姟app * * @author zonglin.nzl * @date 2020/10/15 @@ -102,14 +102,14 @@ public class BusinessApp { } /** - * 应用启动 + * 搴旂敤鍚姩 */ public void start(boolean removeInitUpdateServerRecord) { InitManager.getInstance().add(accountId, new BeforeHttpDnsServiceInit() { @Override public void beforeInit(HttpDnsService httpDnsService) { - // 设置针对测试的辅助接口 + // 璁剧疆閽堝娴嬭瘯鐨勮緟鍔╂帴鍙? if (httpDnsService instanceof ApiForTest) { if (BusinessApp.this.initServers != null) { String[] ips = new String[BusinessApp.this.initServers.length]; @@ -130,7 +130,7 @@ public class BusinessApp { } } - // 设置初始IP + // 璁剧疆鍒濆IP ((ApiForTest) httpDnsService).setInitServer(initRegion, ips, ports, ipv6s, v6ports); } if (BusinessApp.this.defaultUpdateServers != null) { @@ -166,7 +166,7 @@ public class BusinessApp { } } }); - // 获取httpdns + // 鑾峰彇httpdns if (secret == null) { httpDnsService = HttpDns.getService(RuntimeEnvironment.application, accountId); } else { @@ -178,12 +178,12 @@ public class BusinessApp { TestLogger.log(this.toString() + " start with " + BusinessApp.this.initServers[i].toString()); } if (removeInitUpdateServerRecord) { - ServerStatusHelper.hasReceiveRegionChange("初始化时会更新一次服务节点", this, BusinessApp.this.initServers[0], initRegion, true); + ServerStatusHelper.hasReceiveRegionChange("鍒濆鍖栨椂浼氭洿鏂颁竴娆℃湇鍔¤妭鐐?, this, BusinessApp.this.initServers[0], initRegion, true); } } /** - * 应用退出 + * 搴旂敤閫€鍑? */ public void stop() { testExecutorService.shutdownNow(); @@ -192,7 +192,7 @@ public class BusinessApp { /** - * 获取app使用httpdns accountId + * 鑾峰彇app浣跨敤httpdns accountId * * @return */ @@ -201,7 +201,7 @@ public class BusinessApp { } /** - * 获取业务使用host + * 鑾峰彇涓氬姟浣跨敤host * * @return */ @@ -210,7 +210,7 @@ public class BusinessApp { } /** - * 等待app的线程执行完毕 + * 绛夊緟app鐨勭嚎绋嬫墽琛屽畬姣? */ public void waitForAppThread() { try { @@ -221,7 +221,7 @@ public class BusinessApp { } /** - * 解析域名 + * 瑙f瀽鍩熷悕 * * @return */ @@ -230,7 +230,7 @@ public class BusinessApp { } /** - * 解析ipv6的域名 + * 瑙f瀽ipv6鐨勫煙鍚? * * @return */ @@ -239,7 +239,7 @@ public class BusinessApp { } /** - * 解析域名 + * 瑙f瀽鍩熷悕 * * @param host * @return @@ -249,7 +249,7 @@ public class BusinessApp { } /** - * 解析ipv6的域名 + * 瑙f瀽ipv6鐨勫煙鍚? * * @param requestHost * @return @@ -259,7 +259,7 @@ public class BusinessApp { } /** - * 指定类型解析 + * 鎸囧畾绫诲瀷瑙f瀽 * * @param host * @param type @@ -270,7 +270,7 @@ public class BusinessApp { } /** - * 设置日志接口 + * 璁剧疆鏃ュ織鎺ュ彛 */ public void setLogger() { mockLogger = mock(ILogger.class); @@ -285,7 +285,7 @@ public class BusinessApp { /** - * check 收到或者没有收到日志 + * check 鏀跺埌鎴栬€呮病鏈夋敹鍒版棩蹇? * * @param received */ @@ -300,7 +300,7 @@ public class BusinessApp { } /** - * check logger收到日志 + * check logger鏀跺埌鏃ュ織 */ public void hasReceiveLogInLogger() { ArgumentCaptor logArgument = ArgumentCaptor.forClass(String.class); @@ -309,13 +309,13 @@ public class BusinessApp { } /** - * check logger收到日志 + * check logger鏀跺埌鏃ュ織 */ public void hasReceiveLogInLogger(String logKey) { ArgumentCaptor logArgument = ArgumentCaptor.forClass(String.class); verify(mockLogger, atLeastOnce()).log(logArgument.capture()); assertThat(logArgument.getAllValues().size(), greaterThan(1)); - assertThat("有特定的日志" + logKey, stringListContain(logArgument.getAllValues(), logKey)); + assertThat("鏈夌壒瀹氱殑鏃ュ織" + logKey, stringListContain(logArgument.getAllValues(), logKey)); } private boolean stringListContain(List list, String msg) { @@ -328,7 +328,7 @@ public class BusinessApp { } /** - * 切换region + * 鍒囨崲region * * @param region */ @@ -337,7 +337,7 @@ public class BusinessApp { } /** - * 设置ip probe + * 璁剧疆ip probe */ public void enableIPRanking() { ArrayList list = new ArrayList<>(); @@ -346,7 +346,7 @@ public class BusinessApp { } /** - * 设置请求超时 + * 璁剧疆璇锋眰瓒呮椂 * * @param ms */ @@ -355,7 +355,7 @@ public class BusinessApp { } /** - * 清除缓存 + * 娓呴櫎缂撳瓨 * * @param hosts */ @@ -364,7 +364,7 @@ public class BusinessApp { } /** - * 设置更新服务IP的最小间隔 + * 璁剧疆鏇存柊鏈嶅姟IP鐨勬渶灏忛棿闅? * * @param timeInterval */ @@ -375,7 +375,7 @@ public class BusinessApp { } /** - * 设置嗅探模式的最小间隔 + * 璁剧疆鍡呮帰妯″紡鐨勬渶灏忛棿闅? * * @param timeInterval */ @@ -386,10 +386,10 @@ public class BusinessApp { } /** - * check 相同的account是否返回相同的实例 + * check 鐩稿悓鐨刟ccount鏄惁杩斿洖鐩稿悓鐨勫疄渚? */ public void checkSameInstanceForSameAcount() { - assertThat("一个accountId对应一个实例", httpDnsService == HttpDns.getService(RuntimeEnvironment.application, accountId)); + assertThat("涓€涓猘ccountId瀵瑰簲涓€涓疄渚?, httpDnsService == HttpDns.getService(RuntimeEnvironment.application, accountId)); } public HTTPDNSResult requestSDNSResolveHost(HashMap extras, String cacheKey) { @@ -490,3 +490,4 @@ public class BusinessApp { currentNetType = netType; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/helper/ServerStatusHelper.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/helper/ServerStatusHelper.java index 06a1f59..6c68b3b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/helper/ServerStatusHelper.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/helper/ServerStatusHelper.java @@ -12,7 +12,7 @@ import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; /** - * 服务状态判读辅助类 + * 鏈嶅姟鐘舵€佸垽璇昏緟鍔╃被 * * @author zonglin.nzl * @date 2020/11/9 @@ -20,7 +20,7 @@ import static org.hamcrest.MatcherAssert.assertThat; public class ServerStatusHelper { /** - * 判断服务是否接收到域名解析请求 + * 鍒ゆ柇鏈嶅姟鏄惁鎺ユ敹鍒板煙鍚嶈В鏋愯姹? * * @param app */ @@ -29,7 +29,7 @@ public class ServerStatusHelper { HttpDnsServer server, int count) { app.waitForAppThread(); String requestHost = app.getRequestHost(); - assertThat(reason + ", count: " + count, + assertThat(reason + "锛?count: " + count, server.getResolveHostServer().hasRequestForArg(requestHost, count, false)); } @@ -78,7 +78,7 @@ public class ServerStatusHelper { } /** - * 判断服务器 没有收到解析请求 + * 鍒ゆ柇鏈嶅姟鍣?娌℃湁鏀跺埌瑙f瀽璇锋眰 * * @param reason * @param app @@ -93,7 +93,7 @@ public class ServerStatusHelper { } /** - * 判断服务器 没有收到解析请求 + * 鍒ゆ柇鏈嶅姟鍣?娌℃湁鏀跺埌瑙f瀽璇锋眰 * * @param reason * @param app @@ -108,7 +108,7 @@ public class ServerStatusHelper { } /** - * 获取服务器返回的数据 + * 鑾峰彇鏈嶅姟鍣ㄨ繑鍥炵殑鏁版嵁 * * @param app * @param server @@ -133,7 +133,7 @@ public class ServerStatusHelper { } /** - * 判断服务是否接收到服务IP更新请求 + * 鍒ゆ柇鏈嶅姟鏄惁鎺ユ敹鍒版湇鍔P鏇存柊璇锋眰 * * @param app * @param region @@ -167,7 +167,7 @@ public class ServerStatusHelper { } /** - * 请求解析域名,判断服务是否收到 + * 璇锋眰瑙f瀽鍩熷悕锛屽垽鏂湇鍔℃槸鍚︽敹鍒? * * @param app * @param server @@ -184,10 +184,10 @@ public class ServerStatusHelper { } /** - * 对于 {@link HttpException#ERROR_MSG_SERVICE_LEVEL_DENY} 这个错误之前理解有误 - * 之前以为含义是服务节点下线了,不可用,才会返回此错误码,所以此方法命名为降级服务。 - * 真实含义是当前用户不能使用此服务节点。 - * 但是从效果上来说是一样的,都是返回了一个错误,此错误应该触发的逻辑是 切换服务节点。 所以还是保留此命名 + * 瀵逛簬 {@link HttpException#ERROR_MSG_SERVICE_LEVEL_DENY} 杩欎釜閿欒涔嬪墠鐞嗚В鏈夎 + * 涔嬪墠浠ヤ负鍚箟鏄湇鍔¤妭鐐逛笅绾夸簡锛屼笉鍙敤锛屾墠浼氳繑鍥炴閿欒鐮侊紝鎵€浠ユ鏂规硶鍛藉悕涓洪檷绾ф湇鍔°€? + * 鐪熷疄鍚箟鏄綋鍓嶇敤鎴蜂笉鑳戒娇鐢ㄦ鏈嶅姟鑺傜偣銆? + * 浣嗘槸浠庢晥鏋滀笂鏉ヨ鏄竴鏍风殑锛岄兘鏄繑鍥炰簡涓€涓敊璇紝姝ら敊璇簲璇ヨЕ鍙戠殑閫昏緫鏄?鍒囨崲鏈嶅姟鑺傜偣銆?鎵€浠ヨ繕鏄繚鐣欐鍛藉悕 * * @param server * @param requestHost @@ -203,3 +203,4 @@ public class ServerStatusHelper { server.getResolveHostServer().preSetRequestResponse(requestHost, httpCode, httpMsg, count); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/BatchResolveHostServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/BatchResolveHostServer.java index 2e81281..d856332 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/BatchResolveHostServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/BatchResolveHostServer.java @@ -71,7 +71,7 @@ public class BatchResolveHostServer extends } /** - * 获取历史请求中,包含host的预解析请求结果 + * 鑾峰彇鍘嗗彶璇锋眰涓紝鍖呭惈host鐨勯瑙f瀽璇锋眰缁撴灉 * * @param host * @param type @@ -130,7 +130,7 @@ public class BatchResolveHostServer extends } /** - * 根据 自定义请求参数 构建批量解析结果数据,数据随机 + * 鏍规嵁 鑷畾涔夎姹傚弬鏁?鏋勫缓鎵归噺瑙f瀽缁撴灉鏁版嵁锛屾暟鎹殢鏈? * * @param resolveServerArg * @return @@ -141,7 +141,7 @@ public class BatchResolveHostServer extends } /** - * 根据 域名列表和解析类型 构建批量解析结果数据,数据随机 + * 鏍规嵁 鍩熷悕鍒楄〃鍜岃В鏋愮被鍨?鏋勫缓鎵归噺瑙f瀽缁撴灉鏁版嵁锛屾暟鎹殢鏈? * * @param hostList * @param type @@ -172,7 +172,7 @@ public class BatchResolveHostServer extends } /** - * 根据 域名列表和解析类型 构建批量解析结果数据,数据随机, ttl指定 + * 鏍规嵁 鍩熷悕鍒楄〃鍜岃В鏋愮被鍨?鏋勫缓鎵归噺瑙f瀽缁撴灉鏁版嵁锛屾暟鎹殢鏈? ttl鎸囧畾 * * @param hostList * @param type @@ -235,7 +235,7 @@ public class BatchResolveHostServer extends } /** - * 预解析请求参数 + * 棰勮В鏋愯姹傚弬鏁? */ public static class BatchResolveRequestArg { public List hosts; @@ -324,3 +324,4 @@ public class BatchResolveHostServer extends } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/DebugApiServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/DebugApiServer.java index bec62be..f6449fa 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/DebugApiServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/DebugApiServer.java @@ -7,7 +7,7 @@ import java.util.List; import okhttp3.mockwebserver.RecordedRequest; /** - * 测试用接口 + * 娴嬭瘯鐢ㄦ帴鍙? * * @author zonglin.nzl * @date 2020/11/9 @@ -37,7 +37,7 @@ public class DebugApiServer extends BaseDataServer { /** - * 服务侧 判断是否是 测试请求 + * 鏈嶅姟渚?鍒ゆ柇鏄惁鏄?娴嬭瘯璇锋眰 * @param request * @return */ @@ -46,3 +46,4 @@ public class DebugApiServer extends BaseDataServer { return pathSegments.size() == 1 && pathSegments.contains("debug"); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/HttpDnsServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/HttpDnsServer.java index b973854..fba4e3b 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/HttpDnsServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/HttpDnsServer.java @@ -14,7 +14,7 @@ import java.util.HashMap; import okhttp3.mockwebserver.MockWebServer; /** - * 模拟httpdns服务 + * 妯℃嫙httpdns鏈嶅姟 * * @author zonglin.nzl * @date 2020/10/15 @@ -38,7 +38,7 @@ public class HttpDnsServer { private String ipv6; /** - * 服务启动 + * 鏈嶅姟鍚姩 */ public void start() { start(false); @@ -82,7 +82,7 @@ public class HttpDnsServer { } /** - * 服务停止 + * 鏈嶅姟鍋滄 */ public void stop() { try { @@ -93,7 +93,7 @@ public class HttpDnsServer { } /** - * 获取服务IP地址 + * 鑾峰彇鏈嶅姟IP鍦板潃 * * @return */ @@ -105,7 +105,7 @@ public class HttpDnsServer { } /** - * 获取服务端口 + * 鑾峰彇鏈嶅姟绔彛 * * @return */ @@ -114,7 +114,7 @@ public class HttpDnsServer { } /** - * 设置请求监听 + * 璁剧疆璇锋眰鐩戝惉 * * @param requestListener */ @@ -142,3 +142,4 @@ public class HttpDnsServer { return secretServce.get(account); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/MockSpeedTestServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/MockSpeedTestServer.java index 3bf9d19..7327649 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/MockSpeedTestServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/MockSpeedTestServer.java @@ -13,7 +13,7 @@ import static com.alibaba.sdk.android.httpdns.test.server.HttpDnsServer.REQUEST_ import static org.mockito.Mockito.mock; /** - * 模拟测试速度的服务器 + * 妯℃嫙娴嬭瘯閫熷害鐨勬湇鍔″櫒 * * @author zonglin.nzl * @date 2020/11/9 @@ -56,7 +56,7 @@ public class MockSpeedTestServer implements IPRankingTask.SpeedTestSocketFactory } /** - * 监听httpdns服务的返回 + * 鐩戝惉httpdns鏈嶅姟鐨勮繑鍥? * * @param server */ @@ -65,7 +65,7 @@ public class MockSpeedTestServer implements IPRankingTask.SpeedTestSocketFactory } /** - * 停止服务 + * 鍋滄鏈嶅姟 */ public void stop() { this.sortedIps.clear(); @@ -73,7 +73,7 @@ public class MockSpeedTestServer implements IPRankingTask.SpeedTestSocketFactory } /** - * 返回根据服务器速度排序的ip + * 杩斿洖鏍规嵁鏈嶅姟鍣ㄩ€熷害鎺掑簭鐨刬p * * @param requestHost * @return @@ -82,3 +82,4 @@ public class MockSpeedTestServer implements IPRankingTask.SpeedTestSocketFactory return sortedHostIpsMap.get(requestHost); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ResolveHostServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ResolveHostServer.java index 74c19ef..3473eb1 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ResolveHostServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ResolveHostServer.java @@ -16,7 +16,7 @@ import java.util.Set; import okhttp3.mockwebserver.RecordedRequest; /** - * 域名解析服务 + * 鍩熷悕瑙f瀽鏈嶅姟 * * @author zonglin.nzl * @date 2020/11/9 @@ -40,7 +40,7 @@ public class ResolveHostServer try { return ResolveHostResponse.fromResponse(body); } catch (JSONException e) { - throw new IllegalStateException("解析域名ip数据失败", e); + throw new IllegalStateException("瑙f瀽鍩熷悕ip鏁版嵁澶辫触", e); } } @@ -61,7 +61,7 @@ public class ResolveHostServer } /** - * 构建 解析结果字符串builder + * 鏋勫缓 瑙f瀽缁撴灉瀛楃涓瞓uilder * * @param targetHost * @param resultIps @@ -117,7 +117,7 @@ public class ResolveHostServer } /** - * 将解析结果 改为 下行body字符串 + * 灏嗚В鏋愮粨鏋?鏀逛负 涓嬭body瀛楃涓? * * @param response * @return @@ -128,7 +128,7 @@ public class ResolveHostServer } /** - * 构建 解析结果,数据随机 + * 鏋勫缓 瑙f瀽缁撴灉锛屾暟鎹殢鏈? * * @param host * @return @@ -140,7 +140,7 @@ public class ResolveHostServer } /** - * 构建 解析结果,ttl指定,ip数据随机 + * 鏋勫缓 瑙f瀽缁撴灉锛宼tl鎸囧畾锛宨p鏁版嵁闅忔満 * * @param host * @param ttl @@ -153,7 +153,7 @@ public class ResolveHostServer } /** - * 解析服务的参数 + * 瑙f瀽鏈嶅姟鐨勫弬鏁? */ public static class ResolveHostArg { public String host; @@ -241,8 +241,8 @@ public class ResolveHostServer } /** - * 构造 服务侧 的参数字符串,是自定义的字符串,用于区分不同的请求和快速获取参数数据 - * 可以用于匹配请求和获取参数 + * 鏋勯€?鏈嶅姟渚?鐨勫弬鏁板瓧绗︿覆锛屾槸鑷畾涔夌殑瀛楃涓诧紝鐢ㄤ簬鍖哄垎涓嶅悓鐨勮姹傚拰蹇€熻幏鍙栧弬鏁版暟鎹? + * 鍙互鐢ㄤ簬鍖归厤璇锋眰鍜岃幏鍙栧弬鏁? * * @param host * @param type @@ -314,7 +314,7 @@ public class ResolveHostServer } /** - * 创建空解析结果,指定ttl + * 鍒涘缓绌鸿В鏋愮粨鏋滐紝鎸囧畾ttl * * @param host * @param ttl @@ -325,7 +325,7 @@ public class ResolveHostServer } /** - * 创建 解析结果数据 + * 鍒涘缓 瑙f瀽缁撴灉鏁版嵁 * * @param targetHost * @param ips @@ -339,3 +339,4 @@ public class ResolveHostServer return new ResolveHostResponse(targetHost, ips, ipv6s, ttl, extra); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/SecretService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/SecretService.java index 57d7732..3fbc40a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/SecretService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/SecretService.java @@ -18,7 +18,7 @@ public class SecretService { HashMap secrets = new HashMap<>(); /** - * 服务侧 校验 签名 + * 鏈嶅姟渚?鏍¢獙 绛惧悕 * @param secretService * @param recordedRequest * @return @@ -58,3 +58,4 @@ public class SecretService { return secret; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ServerIpsServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ServerIpsServer.java index 6c3e80d..d899059 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ServerIpsServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/ServerIpsServer.java @@ -10,7 +10,7 @@ import java.util.List; import okhttp3.mockwebserver.RecordedRequest; /** - * 服务IP更新接口服务 + * 鏈嶅姟IP鏇存柊鎺ュ彛鏈嶅姟 * * @author zonglin.nzl * @date 2020/11/9 @@ -27,7 +27,7 @@ public class ServerIpsServer extends BaseDataServer implements ServerApi, } /** - * 获取预置数据 + * 鑾峰彇棰勭疆鏁版嵁 * * @param arg * @return @@ -216,7 +216,7 @@ public abstract class BaseDataServer implements ServerApi, } /** - * 获取请求参数 + * 鑾峰彇璇锋眰鍙傛暟 * * @param recordedRequest * @return @@ -224,7 +224,7 @@ public abstract class BaseDataServer implements ServerApi, public abstract ARG getRequestArg(RecordedRequest recordedRequest); /** - * 将数据转化为响应 + * 灏嗘暟鎹浆鍖栦负鍝嶅簲 * * @param data * @return @@ -232,7 +232,7 @@ public abstract class BaseDataServer implements ServerApi, public abstract String convert(DATA data); /** - * 将body转化为数据 + * 灏哹ody杞寲涓烘暟鎹? * * @param body * @return @@ -240,7 +240,7 @@ public abstract class BaseDataServer implements ServerApi, public abstract DATA convert(String body); /** - * 生成随机数据,用于没有预置数据时 + * 鐢熸垚闅忔満鏁版嵁锛岀敤浜庢病鏈夐缃暟鎹椂 * * @param arg * @return @@ -278,3 +278,4 @@ public abstract class BaseDataServer implements ServerApi, } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestHandler.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestHandler.java index 58d9857..f1a0659 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestHandler.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestHandler.java @@ -10,7 +10,7 @@ import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; /** - * 服务的请求处理逻辑 + * 鏈嶅姟鐨勮姹傚鐞嗛€昏緫 * * @author zonglin.nzl * @date 2020/10/16 @@ -58,3 +58,4 @@ public class RequestHandler extends Dispatcher { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestListener.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestListener.java index 4c912c4..8480528 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestListener.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestListener.java @@ -1,7 +1,7 @@ package com.alibaba.sdk.android.httpdns.test.server.base; /** - * 服务接受到请求的监听 + * 鏈嶅姟鎺ュ彈鍒拌姹傜殑鐩戝惉 * * @author zonglin.nzl * @date 2020/11/9 @@ -9,3 +9,4 @@ package com.alibaba.sdk.android.httpdns.test.server.base; public interface RequestListener { void onRequest(int type, Object arg, BaseDataServer server); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestRecord.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestRecord.java index 58ef73e..ef67b5a 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestRecord.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/RequestRecord.java @@ -4,7 +4,7 @@ import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; /** - * 服务请求记录 + * 鏈嶅姟璇锋眰璁板綍 * * @author zonglin.nzl * @date 2020/10/16 @@ -26,3 +26,4 @@ public class RequestRecord { return mockResponse; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/SdkBusinessServer.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/SdkBusinessServer.java index 8c003dd..b8fd641 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/SdkBusinessServer.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/SdkBusinessServer.java @@ -4,7 +4,7 @@ import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; /** - * sdk业务服务 + * sdk涓氬姟鏈嶅姟 * * @author zonglin.nzl * @date 2020/11/9 @@ -12,7 +12,7 @@ import okhttp3.mockwebserver.RecordedRequest; interface SdkBusinessServer { /** - * 是否是当前业务服务的请求 + * 鏄惁鏄綋鍓嶄笟鍔℃湇鍔$殑璇锋眰 * * @param request * @return @@ -20,10 +20,11 @@ interface SdkBusinessServer { boolean isMyBusinessRequest(RecordedRequest request); /** - * 处理请求 + * 澶勭悊璇锋眰 * * @param request * @return */ MockResponse handle(RecordedRequest request); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/ServerApi.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/ServerApi.java index e46b6bf..0fb047d 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/ServerApi.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/server/base/ServerApi.java @@ -3,97 +3,97 @@ package com.alibaba.sdk.android.httpdns.test.server.base; import java.util.List; /** - * 业务服务对外提供的接口, - * 包括 预设请求结果;查询请求结果 - * 条件维度有:参数、个数(查前几个) - * 效果维度有:生效次数、是否移除 - * 结果维度有:超时,成功,失败 + * 涓氬姟鏈嶅姟瀵瑰鎻愪緵鐨勬帴鍙? + * 鍖呮嫭 棰勮璇锋眰缁撴灉锛涙煡璇㈣姹傜粨鏋? + * 鏉′欢缁村害鏈夛細鍙傛暟銆佷釜鏁帮紙鏌ュ墠鍑犱釜锛? + * 鏁堟灉缁村害鏈夛細鐢熸晥娆℃暟銆佹槸鍚︾Щ闄? + * 缁撴灉缁村害鏈夛細瓒呮椂锛屾垚鍔燂紝澶辫触 * @author zonglin.nzl * @date 2020/12/5 */ public interface ServerApi { /** - * 预置请求超时 + * 棰勭疆璇锋眰瓒呮椂 */ void preSetRequestTimeout(ARG arg, int count); /** - * 预置请求返回结果 + * 棰勭疆璇锋眰杩斿洖缁撴灉 * * @param arg * @param data - * @param count 使用次数 + * @param count 浣跨敤娆℃暟 */ void preSetRequestResponse(ARG arg, DATA data, int count); /** - * 预置请求返回结果 + * 棰勭疆璇锋眰杩斿洖缁撴灉 * * @param arg * @param httpCode * @param body - * @param count 使用次数 + * @param count 浣跨敤娆℃暟 */ void preSetRequestResponse(ARG arg, int httpCode, String body, int count); /** - * 判断是否请求 + * 鍒ゆ柇鏄惁璇锋眰 * * @param arg * @param count - * @param removeRecord 是否移除记录 + * @param removeRecord 鏄惁绉婚櫎璁板綍 * @return */ boolean hasRequestForArg(ARG arg, int count, boolean removeRecord); /** - * 判断是否请求 + * 鍒ゆ柇鏄惁璇锋眰 * * @param arg - * @param params query参数 + * @param params query鍙傛暟 * @param count - * @param removeRecord 是否移除记录 + * @param removeRecord 鏄惁绉婚櫎璁板綍 * @return */ boolean hasRequestForArgWithParams(ARG arg, List params, int count, boolean removeRecord); /** - * 判断是否请求超时 + * 鍒ゆ柇鏄惁璇锋眰瓒呮椂 * * @param arg * @param count - * @param removeRecord 是否移除记录 + * @param removeRecord 鏄惁绉婚櫎璁板綍 * @return */ boolean hasRequestForArgTimeout(ARG arg, int count, boolean removeRecord); /** - * 判断是否有count个返回data的请求 + * 鍒ゆ柇鏄惁鏈塩ount涓繑鍥瀌ata鐨勮姹? * * @param arg * @param data * @param count - * @param removeRecord 是否移除记录 + * @param removeRecord 鏄惁绉婚櫎璁板綍 * @return */ boolean hasRequestForArgWithResult(ARG arg, DATA data, int count, boolean removeRecord); /** - * 判断是否请求过 + * 鍒ゆ柇鏄惁璇锋眰杩? * * @param arg * @param httpCode * @param body * @param count - * @param removeRecord 是否移除记录 + * @param removeRecord 鏄惁绉婚櫎璁板綍 * @return */ boolean hasRequestForArgWithResult(ARG arg, int httpCode, String body, int count, boolean removeRecord); /** - * 获取请求的结果 + * 鑾峰彇璇锋眰鐨勭粨鏋? * @param arg * @param count * @param removeRecord @@ -103,8 +103,9 @@ public interface ServerApi { /** - * 清除服务目前的所有请求记录 + * 娓呴櫎鏈嶅姟鐩墠鐨勬墍鏈夎姹傝褰? */ void cleanRecord(); } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/CountUpAndDownLatch.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/CountUpAndDownLatch.java index d0f4bec..c6d7eb0 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/CountUpAndDownLatch.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/CountUpAndDownLatch.java @@ -6,7 +6,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** - * 线程控制锁 + * 绾跨▼鎺у埗閿? * * @author zonglin.nzl * @date 2020/9/3 @@ -73,7 +73,7 @@ public class CountUpAndDownLatch { int count = this.count.get(); if (checkThreadCount) { if (count > 0) { - MatcherAssert.assertThat("线程使用超出预期 " + count, false); + MatcherAssert.assertThat("绾跨▼浣跨敤瓒呭嚭棰勬湡 " + count, false); } } else { this.count.set(0); @@ -85,3 +85,4 @@ public class CountUpAndDownLatch { this.checkThreadCount = checkThreadCount; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/MultiThreadTestHelper.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/MultiThreadTestHelper.java index b1f2cda..18dcbe6 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/MultiThreadTestHelper.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/MultiThreadTestHelper.java @@ -5,15 +5,15 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** - * 多线程测试辅助类 + * 澶氱嚎绋嬫祴璇曡緟鍔╃被 * @author zonglin.nzl * @date 11/4/21 */ public class MultiThreadTestHelper { /** - * 开始执行一个多线程测试任务 - * 根据参数 同时启动多个线程同时执行一定时间 + * 寮€濮嬫墽琛屼竴涓绾跨▼娴嬭瘯浠诲姟 + * 鏍规嵁鍙傛暟 鍚屾椂鍚姩澶氫釜绾跨▼鍚屾椂鎵ц涓€瀹氭椂闂? * @param testTask */ public static void start(final TestTask testTask) { @@ -60,45 +60,45 @@ public class MultiThreadTestHelper { } /** - * 单线程的测试任务接口 + * 鍗曠嚎绋嬬殑娴嬭瘯浠诲姟鎺ュ彛 */ public interface ThreadTask { /** - * 执行测试开始前的准备工作 + * 鎵ц娴嬭瘯寮€濮嬪墠鐨勫噯澶囧伐浣? */ void prepare(); /** - * 执行测试逻辑 + * 鎵ц娴嬭瘯閫昏緫 */ void execute(); /** - * 执行测试结果的处理逻辑 + * 鎵ц娴嬭瘯缁撴灉鐨勫鐞嗛€昏緫 */ void done(); } /** - * 测试任务的构造接口 & 测试结束接口 + * 娴嬭瘯浠诲姟鐨勬瀯閫犳帴鍙?& 娴嬭瘯缁撴潫鎺ュ彛 */ public interface TaskFactory { /** - * 创建一个测试任务 + * 鍒涘缓涓€涓祴璇曚换鍔? * @return */ ThreadTask create(); /** - * 所有测试任务完成的回调接口 + * 鎵€鏈夋祴璇曚换鍔″畬鎴愮殑鍥炶皟鎺ュ彛 */ void allFinish(); } /** - * 一个多线程测试任务 - * 需要覆写 create 方法 - * 参数指定 一共多少线程,单个线程执行多长时间 + * 涓€涓绾跨▼娴嬭瘯浠诲姟 + * 闇€瑕佽鍐?create 鏂规硶 + * 鍙傛暟鎸囧畾 涓€鍏卞灏戠嚎绋嬶紝鍗曚釜绾跨▼鎵ц澶氶暱鏃堕棿 */ public static class TestTask implements TaskFactory { private int threadCount; @@ -121,7 +121,7 @@ public class MultiThreadTestHelper { } /** - * 每个线程执行的逻辑一样时的 简单多线程测试 + * 姣忎釜绾跨▼鎵ц鐨勯€昏緫涓€鏍锋椂鐨?绠€鍗曞绾跨▼娴嬭瘯 */ public static class SimpleTask extends TestTask { private Runnable task; @@ -152,3 +152,4 @@ public class MultiThreadTestHelper { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/RandomValue.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/RandomValue.java index 2da451d..760a185 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/RandomValue.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/RandomValue.java @@ -7,7 +7,7 @@ import java.util.ArrayList; import java.util.Random; /** - * 随机测试数据 + * 闅忔満娴嬭瘯鏁版嵁 * * @author zonglin.nzl * @date 2020/9/2 @@ -139,3 +139,4 @@ public class RandomValue { return jsonObject.toString(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/ShadowNetworkInfo.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/ShadowNetworkInfo.java index 20edd93..8fd4117 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/ShadowNetworkInfo.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/ShadowNetworkInfo.java @@ -7,7 +7,7 @@ import org.robolectric.annotation.Implements; import org.robolectric.shadow.api.Shadow; /** - * robolectric 的NetworkInfo shadow 类 + * robolectric 鐨凬etworkInfo shadow 绫? * @author zonglin.nzl * @date 2020/9/8 */ @@ -117,3 +117,4 @@ public class ShadowNetworkInfo extends org.robolectric.shadows.ShadowNetworkInfo this.detailedState = detailedState; } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/SyncExecutorService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/SyncExecutorService.java index 8cad364..3301ff1 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/SyncExecutorService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/SyncExecutorService.java @@ -10,7 +10,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** - * 同步线程池 + * 鍚屾绾跨▼姹? * @author zonglin.nzl * @date 1/13/22 */ @@ -80,3 +80,4 @@ public class SyncExecutorService implements ExecutorService { command.run(); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestExecutorService.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestExecutorService.java index 2fa9618..ad348a2 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestExecutorService.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestExecutorService.java @@ -14,8 +14,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** - * 测试使用的 线程池 - * 可以进行异步控制,等待异步逻辑处理完成 + * 娴嬭瘯浣跨敤鐨?绾跨▼姹? + * 鍙互杩涜寮傛鎺у埗锛岀瓑寰呭紓姝ラ€昏緫澶勭悊瀹屾垚 * @author zonglin.nzl * @date 2020/9/3 */ @@ -362,3 +362,4 @@ public class TestExecutorService implements ScheduledExecutorService { return this.originService.scheduleWithFixedDelay(command, initialDelay, delay, unit); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestLogger.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestLogger.java index f7d0cd9..121db31 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestLogger.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/TestLogger.java @@ -4,7 +4,7 @@ import java.text.SimpleDateFormat; import java.util.Date; /** - * 测试模块的日志接口 + * 娴嬭瘯妯″潡鐨勬棩蹇楁帴鍙? * * @author zonglin.nzl * @date 2020/12/18 @@ -16,3 +16,4 @@ public class TestLogger { System.out.println("[" + format.format(new Date()) + "][TEST]" + msg); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/UnitTestUtil.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/UnitTestUtil.java index 5f547d5..3bf35e0 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/UnitTestUtil.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/test/utils/UnitTestUtil.java @@ -142,7 +142,7 @@ public class UnitTestUtil { } /** - * 用于测试只能在子线程执行的代码 + * 鐢ㄤ簬娴嬭瘯鍙兘鍦ㄥ瓙绾跨▼鎵ц鐨勪唬鐮? * @param work * @throws Throwable */ @@ -171,3 +171,4 @@ public class UnitTestUtil { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/CommonUtilTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/CommonUtilTest.java index 28f9fb1..9782300 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/CommonUtilTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/CommonUtilTest.java @@ -23,13 +23,13 @@ public class CommonUtilTest { @Test public void sortIpsOrderWithConnectSpeed() { String[] sortedIps = CommonUtil.sortIpsWithSpeeds(new String[]{"A", "B", "C"}, new int[]{3, 2, 1}); - assertIpsEqual("速度快的,排前面", sortedIps, new String[]{"C", "B", "A"}); + assertIpsEqual("閫熷害蹇殑锛屾帓鍓嶉潰", sortedIps, new String[]{"C", "B", "A"}); sortedIps = CommonUtil.sortIpsWithSpeeds(new String[]{"A", "B", "C"}, new int[]{1, 2, 3}); - assertIpsEqual("速度快的,排前面", sortedIps, new String[]{"A", "B", "C"}); + assertIpsEqual("閫熷害蹇殑锛屾帓鍓嶉潰", sortedIps, new String[]{"A", "B", "C"}); sortedIps = CommonUtil.sortIpsWithSpeeds(new String[]{"A", "B", "C"}, new int[]{2, 3, 1}); - assertIpsEqual("速度快的,排前面", sortedIps, new String[]{"C", "A", "B"}); + assertIpsEqual("閫熷害蹇殑锛屾帓鍓嶉潰", sortedIps, new String[]{"C", "A", "B"}); } @@ -38,12 +38,12 @@ public class CommonUtilTest { String[] ips = RandomValue.randomIpv4s(); String tmp = CommonUtil.translateStringArray(ips); String[] ips1 = CommonUtil.parseStringArray(tmp); - assertIpsEqual("字符串数组转化", ips, ips1); + assertIpsEqual("瀛楃涓叉暟缁勮浆鍖?, ips, ips1); - MatcherAssert.assertThat("null场景", CommonUtil.translateStringArray(null) == null); - MatcherAssert.assertThat("null场景", CommonUtil.parseStringArray(null) == null); - MatcherAssert.assertThat("空场景", CommonUtil.translateStringArray(new String[0]).equals("")); - MatcherAssert.assertThat("空场景", CommonUtil.parseStringArray("").length == 0); + MatcherAssert.assertThat("null鍦烘櫙", CommonUtil.translateStringArray(null) == null); + MatcherAssert.assertThat("null鍦烘櫙", CommonUtil.parseStringArray(null) == null); + MatcherAssert.assertThat("绌哄満鏅?, CommonUtil.translateStringArray(new String[0]).equals("")); + MatcherAssert.assertThat("绌哄満鏅?, CommonUtil.parseStringArray("").length == 0); } @@ -54,10 +54,10 @@ public class CommonUtilTest { int[] ports1 = CommonUtil.parseIntArray(tmp); UnitTestUtil.assertIntArrayEquals(ports, ports1); - MatcherAssert.assertThat("null场景", CommonUtil.translateIntArray(null) == null); - MatcherAssert.assertThat("null场景", CommonUtil.parseIntArray(null) == null); - MatcherAssert.assertThat("空场景", CommonUtil.translateIntArray(new int[0]).equals("")); - MatcherAssert.assertThat("空场景", CommonUtil.parseIntArray("").length == 0); + MatcherAssert.assertThat("null鍦烘櫙", CommonUtil.translateIntArray(null) == null); + MatcherAssert.assertThat("null鍦烘櫙", CommonUtil.parseIntArray(null) == null); + MatcherAssert.assertThat("绌哄満鏅?, CommonUtil.translateIntArray(new int[0]).equals("")); + MatcherAssert.assertThat("绌哄満鏅?, CommonUtil.parseIntArray("").length == 0); } @Test @@ -69,3 +69,4 @@ public class CommonUtilTest { } } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/HexTest.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/HexTest.java index 48ad704..f200eb3 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/HexTest.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/utils/HexTest.java @@ -41,3 +41,4 @@ public class HexTest { } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0.java index 3a1f082..631e498 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0.java @@ -40,13 +40,13 @@ import java.util.ArrayList; import java.util.Date; /** - * HTTPDNS 2.3.0 版本需求 - * 1. 缓存使用的ttl改为可配置 - * 2. 主站域名的ip不经常变动,单独处理相关逻辑 - * 3. 没有解析结果的域名解析,算是一种无效请求,也按主站域名处理。因为没有解析结果,也可以认为是一种固定的解析结果 - * 3.1 但是这里有一种特殊情况,即同时解析v4、v6的情况,有可能v6是无效的,而v4是有效的,此时需要根据缓存把解析改为仅解析v4 - * 4. 缓存有效时,过滤掉相关的解析,比如 解析v4 v6, v4有效,就只解析v6 反之亦然 - * 5. 测试异常情况下的反应,包括 日志输出 是否重试 是否切换服务IP 是否生成一个空缓存 + * HTTPDNS 2.3.0 鐗堟湰闇€姹? + * 1. 缂撳瓨浣跨敤鐨則tl鏀逛负鍙厤缃? + * 2. 涓荤珯鍩熷悕鐨刬p涓嶇粡甯稿彉鍔紝鍗曠嫭澶勭悊鐩稿叧閫昏緫 + * 3. 娌℃湁瑙f瀽缁撴灉鐨勫煙鍚嶈В鏋愶紝绠楁槸涓€绉嶆棤鏁堣姹傦紝涔熸寜涓荤珯鍩熷悕澶勭悊銆傚洜涓烘病鏈夎В鏋愮粨鏋滐紝涔熷彲浠ヨ涓烘槸涓€绉嶅浐瀹氱殑瑙f瀽缁撴灉 + * 3.1 浣嗘槸杩欓噷鏈変竴绉嶇壒娈婃儏鍐碉紝鍗冲悓鏃惰В鏋恦4銆乿6鐨勬儏鍐碉紝鏈夊彲鑳絭6鏄棤鏁堢殑锛岃€寁4鏄湁鏁堢殑锛屾鏃堕渶瑕佹牴鎹紦瀛樻妸瑙f瀽鏀逛负浠呰В鏋恦4 + * 4. 缂撳瓨鏈夋晥鏃讹紝杩囨护鎺夌浉鍏崇殑瑙f瀽锛屾瘮濡?瑙f瀽v4 v6锛?v4鏈夋晥锛屽氨鍙В鏋恦6 鍙嶄箣浜︾劧 + * 5. 娴嬭瘯寮傚父鎯呭喌涓嬬殑鍙嶅簲锛屽寘鎷?鏃ュ織杈撳嚭 鏄惁閲嶈瘯 鏄惁鍒囨崲鏈嶅姟IP 鏄惁鐢熸垚涓€涓┖缂撳瓨 * * @author zonglin.nzl * @date 2020/10/15 @@ -67,7 +67,7 @@ public class V2_3_0 { @Before public void setUp() { - // 设置日志接口 + // 璁剧疆鏃ュ織鎺ュ彛 HttpDnsLog.enable(true); logger = new ILogger() { private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); @@ -80,11 +80,11 @@ public class V2_3_0 { } }; HttpDnsLog.setLogger(logger); - // 重置实例 + // 閲嶇疆瀹炰緥 HttpDns.resetInstance(); - // 重置配置 + // 閲嶇疆閰嶇疆 InitConfig.removeConfig(null); - // 这里我们启动3个 服务节点用于测试 + // 杩欓噷鎴戜滑鍚姩3涓?鏈嶅姟鑺傜偣鐢ㄤ簬娴嬭瘯 server.start(); server1.start(); server2.start(); @@ -107,7 +107,7 @@ public class V2_3_0 { } /** - * 测试 自定义ttl 能力 + * 娴嬭瘯 鑷畾涔塼tl 鑳藉姏 * * @throws InterruptedException */ @@ -121,7 +121,7 @@ public class V2_3_0 { Mockito.when(changer.changeCacheTtl(hostWithShorterTtl, RequestIpType.v4, 2)).thenReturn(1); Mockito.when(changer.changeCacheTtl(hostWithChangerTtl, RequestIpType.v4, 1)).thenReturn(2); - // 重置,然后重新初始化httpdns + // 閲嶇疆锛岀劧鍚庨噸鏂板垵濮嬪寲httpdns HttpDns.resetInstance(); new InitConfig.Builder().configCacheTtlChanger(changer).setEnableExpiredIp(false).buildFor( app.getAccountId()); @@ -130,82 +130,82 @@ public class V2_3_0 { ResolveHostResponse response = ResolveHostServer.randomResolveHostResponse( hostWithShorterTtl, 2); server.getResolveHostServer().preSetRequestResponse(hostWithShorterTtl, response, -1); - // 请求域名解析,并返回空结果,因为是接口是异步的,所以第一次请求一个域名返回是空 + // 璇锋眰鍩熷悕瑙f瀽锛屽苟杩斿洖绌虹粨鏋滐紝鍥犱负鏄帴鍙f槸寮傛鐨勶紝鎵€浠ョ涓€娆¤姹備竴涓煙鍚嶈繑鍥炴槸绌? String[] ips = app.requestResolveHost(hostWithShorterTtl); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips); - // 验证服务器收到了请求 + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips); + // 楠岃瘉鏈嶅姟鍣ㄦ敹鍒颁簡璇锋眰 ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "当没有缓存时,会异步请求服务器", app, + "褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, ResolveHostServer.ResolveHostArg.create(hostWithShorterTtl), server, response, 1, true); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? ips = app.requestResolveHost(hostWithShorterTtl); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", ips, response.getIps()); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, ips, response.getIps()); Thread.sleep(1000); - // 由于修改了ttl, 过期了,请求ip + // 鐢变簬淇敼浜唗tl, 杩囨湡浜嗭紝璇锋眰ip ips = app.requestResolveHost(hostWithShorterTtl); - UnitTestUtil.assertIpsEmpty("ip过期后,返回空", ips); + UnitTestUtil.assertIpsEmpty("ip杩囨湡鍚庯紝杩斿洖绌?, ips); ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "ttl过期后,再次请求会触发网络请求", app, + "ttl杩囨湡鍚庯紝鍐嶆璇锋眰浼氳Е鍙戠綉缁滆姹?, app, ResolveHostServer.ResolveHostArg.create(hostWithShorterTtl), server, response, 1, true); - // 再次请求,获取再次请求服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栧啀娆¤姹傛湇鍔″櫒杩斿洖鐨勭粨鏋? ips = app.requestResolveHost(hostWithShorterTtl); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", ips, response.getIps()); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, ips, response.getIps()); ResolveHostResponse response1 = ResolveHostServer.randomResolveHostResponse( hostWithChangerTtl, 1); server.getResolveHostServer().preSetRequestResponse(hostWithChangerTtl, response1, -1); - // 请求域名解析,并返回空结果,因为是接口是异步的,所以第一次请求一个域名返回是空 + // 璇锋眰鍩熷悕瑙f瀽锛屽苟杩斿洖绌虹粨鏋滐紝鍥犱负鏄帴鍙f槸寮傛鐨勶紝鎵€浠ョ涓€娆¤姹備竴涓煙鍚嶈繑鍥炴槸绌? String[] ips1 = app.requestResolveHost(hostWithChangerTtl); - UnitTestUtil.assertIpsEmpty("第一次请求,没有缓存,应该返回空", ips1); - // 验证服务器收到了请求 + UnitTestUtil.assertIpsEmpty("绗竴娆¤姹傦紝娌℃湁缂撳瓨锛屽簲璇ヨ繑鍥炵┖", ips1); + // 楠岃瘉鏈嶅姟鍣ㄦ敹鍒颁簡璇锋眰 ServerStatusHelper.hasReceiveAppResolveHostRequestWithResult( - "当没有缓存时,会异步请求服务器", app, + "褰撴病鏈夌紦瀛樻椂锛屼細寮傛璇锋眰鏈嶅姟鍣?, app, ResolveHostServer.ResolveHostArg.create(hostWithChangerTtl), server, response1, 1, true); - // 再次请求,获取服务器返回的结果 + // 鍐嶆璇锋眰锛岃幏鍙栨湇鍔″櫒杩斿洖鐨勭粨鏋? ips1 = app.requestResolveHost(hostWithChangerTtl); - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - // 结果和服务器返回一致 - UnitTestUtil.assertIpsEqual("解析域名返回服务器结果", ips1, response1.getIps()); + // 缁撴灉鍜屾湇鍔″櫒杩斿洖涓€鑷? + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖鏈嶅姟鍣ㄧ粨鏋?, ips1, response1.getIps()); Thread.sleep(1000); - // 由于修改了ttl, 没有过期,请求ip 返回缓存结果 + // 鐢变簬淇敼浜唗tl, 娌℃湁杩囨湡锛岃姹俰p 杩斿洖缂撳瓨缁撴灉 ips1 = app.requestResolveHost(hostWithChangerTtl); - // 服务没有收到请求 - ServerStatusHelper.hasNotReceiveAppResolveHostRequest("当有缓存时,不会请求服务器", app, + // 鏈嶅姟娌℃湁鏀跺埌璇锋眰 + ServerStatusHelper.hasNotReceiveAppResolveHostRequest("褰撴湁缂撳瓨鏃讹紝涓嶄細璇锋眰鏈嶅姟鍣?, app, server); - UnitTestUtil.assertIpsEqual("解析域名返回缓存结果", ips1, response1.getIps()); + UnitTestUtil.assertIpsEqual("瑙f瀽鍩熷悕杩斿洖缂撳瓨缁撴灉", ips1, response1.getIps()); } /** - * 主站域名的ip解析缓存 不会因为网络变化而清除 + * 涓荤珯鍩熷悕鐨刬p瑙f瀽缂撳瓨 涓嶄細鍥犱负缃戠粶鍙樺寲鑰屾竻闄? */ @Test @Config(shadows = {ShadowNetworkInfo.class}) public void testCacheWillNotBeCleanWhenNetworkChangeAsIpIsFixed() { - // 重置,然后重新初始化httpdns, 配置主站域名 + // 閲嶇疆锛岀劧鍚庨噸鏂板垵濮嬪寲httpdns, 閰嶇疆涓荤珯鍩熷悕 HttpDns.resetInstance(); ArrayList hosts = new ArrayList<>(); hosts.add(app.getRequestHost()); new InitConfig.Builder().configHostWithFixedIp(hosts).buildFor(app.getAccountId()); app.start(true); - // 用于和主站域名的效果进行对比 + // 鐢ㄤ簬鍜屼富绔欏煙鍚嶇殑鏁堟灉杩涜瀵规瘮 final String hostWithoutFixedIP = RandomValue.randomHost(); - // 移动网络 + // 绉诲姩缃戠粶 app.changeToNetwork(ConnectivityManager.TYPE_MOBILE); - // 先请求一次,产生缓存 + // 鍏堣姹備竴娆★紝浜х敓缂撳瓨 app.requestResolveHost(); app.requestResolveHost(hostWithoutFixedIP); app.waitForAppThread(); @@ -215,71 +215,71 @@ public class V2_3_0 { String[] serverResponseIpsWillChange = server.getResolveHostServer().getResponse( hostWithoutFixedIP, 1, true).get(0).getIps(); - // 修改为wifi + // 淇敼涓簑ifi app.changeToNetwork(ConnectivityManager.TYPE_WIFI); - // 再请求一次,应该使用的是缓存 - UnitTestUtil.assertIpsEqual("再次请求获取的是上次请求的缓存", app.requestResolveHost(), + // 鍐嶈姹備竴娆★紝搴旇浣跨敤鐨勬槸缂撳瓨 + UnitTestUtil.assertIpsEqual("鍐嶆璇锋眰鑾峰彇鐨勬槸涓婃璇锋眰鐨勭紦瀛?, app.requestResolveHost(), serverResponseIps); - MatcherAssert.assertThat("非主站域名再次请求获取的是不一样的IP", + MatcherAssert.assertThat("闈炰富绔欏煙鍚嶅啀娆¤姹傝幏鍙栫殑鏄笉涓€鏍风殑IP", app.requestResolveHost(hostWithoutFixedIP), Matchers.not(Matchers.arrayContainingInAnyOrder(serverResponseIpsWillChange))); } /** - * 主站域名的ip解析缓存 不会因为网络变化而预解析 + * 涓荤珯鍩熷悕鐨刬p瑙f瀽缂撳瓨 涓嶄細鍥犱负缃戠粶鍙樺寲鑰岄瑙f瀽 */ @Test @Config(shadows = {ShadowNetworkInfo.class}) public void testCacheWillNotBeRefreshWhenNetworkChangeAsIpIsFixed() { - // 重置,然后重新初始化httpdns, 配置主站域名 + // 閲嶇疆锛岀劧鍚庨噸鏂板垵濮嬪寲httpdns, 閰嶇疆涓荤珯鍩熷悕 HttpDns.resetInstance(); ArrayList hosts = new ArrayList<>(); hosts.add(app.getRequestHost()); new InitConfig.Builder().configHostWithFixedIp(hosts).buildFor(app.getAccountId()); app.start(true); - // 这里设置为网络变化预解析,强化这个配置不影响主站域名 + // 杩欓噷璁剧疆涓虹綉缁滃彉鍖栭瑙f瀽锛屽己鍖栬繖涓厤缃笉褰卞搷涓荤珯鍩熷悕 app.enableResolveAfterNetworkChange(true); - // 用于和主站域名的效果进行对比 + // 鐢ㄤ簬鍜屼富绔欏煙鍚嶇殑鏁堟灉杩涜瀵规瘮 final String hostWithoutFixedIP = RandomValue.randomHost(); - // 移动网络 + // 绉诲姩缃戠粶 app.changeToNetwork(ConnectivityManager.TYPE_MOBILE); - // 先请求一次,产生缓存 + // 鍏堣姹備竴娆★紝浜х敓缂撳瓨 app.requestResolveHost(); app.requestResolveHost(hostWithoutFixedIP); app.waitForAppThread(); - // 修改为wifi + // 淇敼涓簑ifi app.changeToNetwork(ConnectivityManager.TYPE_WIFI); - MatcherAssert.assertThat("不会触发预解析", server.getBatchResolveHostServer() + MatcherAssert.assertThat("涓嶄細瑙﹀彂棰勮В鏋?, server.getBatchResolveHostServer() .hasRequestForHost(app.getRequestHost(), RequestIpType.v4, 0, false)); - MatcherAssert.assertThat("非主站域名会触发预解析", server.getBatchResolveHostServer() + MatcherAssert.assertThat("闈炰富绔欏煙鍚嶄細瑙﹀彂棰勮В鏋?, server.getBatchResolveHostServer() .hasRequestForHost(hostWithoutFixedIP, RequestIpType.v4, 1, false)); } /** - * 主站域名的ip解析缓存 默认使用本地缓存 + * 涓荤珯鍩熷悕鐨刬p瑙f瀽缂撳瓨 榛樿浣跨敤鏈湴缂撳瓨 */ @Test public void testDiskCacheAsDefaultAsIpIsFixed() { - // 重置,然后重新初始化httpdns, 配置主站域名 + // 閲嶇疆锛岀劧鍚庨噸鏂板垵濮嬪寲httpdns, 閰嶇疆涓荤珯鍩熷悕 HttpDns.resetInstance(); ArrayList hosts = new ArrayList<>(); hosts.add(app.getRequestHost()); - // 这里配置关闭本地缓存,强化这个配置不影响主站域名 + // 杩欓噷閰嶇疆鍏抽棴鏈湴缂撳瓨锛屽己鍖栬繖涓厤缃笉褰卞搷涓荤珯鍩熷悕 new InitConfig.Builder().configHostWithFixedIp(hosts).setEnableCacheIp(false).buildFor( app.getAccountId()); app.start(true); - // 非主站域名用于对比 + // 闈炰富绔欏煙鍚嶇敤浜庡姣? final String hostWithoutFixedIP = RandomValue.randomHost(); - // 先请求一次,产生缓存 + // 鍏堣姹備竴娆★紝浜х敓缂撳瓨 app.requestResolveHost(); app.requestResolveHost(hostWithoutFixedIP); app.waitForAppThread(); @@ -287,21 +287,21 @@ public class V2_3_0 { server.getResolveHostServer().getResponse(app.getRequestHost(), 1, true).get(0).getIps(); - // 重置,重新初始化,触发读取缓存逻辑 + // 閲嶇疆锛岄噸鏂板垵濮嬪寲锛岃Е鍙戣鍙栫紦瀛橀€昏緫 HttpDns.resetInstance(); new InitConfig.Builder().configHostWithFixedIp(hosts).setEnableCacheIp(false).buildFor( app.getAccountId()); app.start(true); - // 请求一次,读取缓存 + // 璇锋眰涓€娆★紝璇诲彇缂撳瓨 String[] ips = app.requestResolveHost(); - UnitTestUtil.assertIpsEqual("主站域名默认开启本地缓存", ips, serverResponseIps); - UnitTestUtil.assertIpsEmpty("非主站域名没有开启本地缓存", + UnitTestUtil.assertIpsEqual("涓荤珯鍩熷悕榛樿寮€鍚湰鍦扮紦瀛?, ips, serverResponseIps); + UnitTestUtil.assertIpsEmpty("闈炰富绔欏煙鍚嶆病鏈夊紑鍚湰鍦扮紦瀛?, app.requestResolveHost(hostWithoutFixedIP)); } /** - * 空解析缓存 不会因为网络变化而预解析 + * 绌鸿В鏋愮紦瀛?涓嶄細鍥犱负缃戠粶鍙樺寲鑰岄瑙f瀽 */ @Test @Config(shadows = {ShadowNetworkInfo.class}) @@ -311,31 +311,31 @@ public class V2_3_0 { server.getResolveHostServer().preSetRequestResponse(hostWithEmptyIP, ResolveHostServer.createResponseWithEmptyIp(hostWithEmptyIP, 100), -1); - // 这里设置为网络变化预解析,强化这个配置不影响主站域名 + // 杩欓噷璁剧疆涓虹綉缁滃彉鍖栭瑙f瀽锛屽己鍖栬繖涓厤缃笉褰卞搷涓荤珯鍩熷悕 app.enableResolveAfterNetworkChange(true); - // 移动网络 + // 绉诲姩缃戠粶 app.changeToNetwork(ConnectivityManager.TYPE_MOBILE); - // 先请求一次,产生缓存 + // 鍏堣姹備竴娆★紝浜х敓缂撳瓨 app.requestResolveHost(hostWithEmptyIP); app.waitForAppThread(); - // 修改为wifi + // 淇敼涓簑ifi app.changeToNetwork(ConnectivityManager.TYPE_WIFI); - MatcherAssert.assertThat("不会触发预解析", server.getBatchResolveHostServer() + MatcherAssert.assertThat("涓嶄細瑙﹀彂棰勮В鏋?, server.getBatchResolveHostServer() .hasRequestForHost(hostWithEmptyIP, RequestIpType.v4, 0, false)); - // 再请求一次,直接返回的应该是缓存。 这里的目的是强化目前是有缓存的 + // 鍐嶈姹備竴娆★紝鐩存帴杩斿洖鐨勫簲璇ユ槸缂撳瓨銆?杩欓噷鐨勭洰鐨勬槸寮哄寲鐩墠鏄湁缂撳瓨鐨? app.requestResolveHost(hostWithEmptyIP); app.waitForAppThread(); - MatcherAssert.assertThat("服务只接收到第一次请求", + MatcherAssert.assertThat("鏈嶅姟鍙帴鏀跺埌绗竴娆¤姹?, server.getResolveHostServer().hasRequestForArg(hostWithEmptyIP, 1, true)); } /** - * 空解析缓存 强制使用本地缓存 + * 绌鸿В鏋愮紦瀛?寮哄埗浣跨敤鏈湴缂撳瓨 */ @Test public void testDiskCacheAsDefaultAsEmptyIP() { @@ -344,29 +344,29 @@ public class V2_3_0 { server.getResolveHostServer().preSetRequestResponse(hostWithEmptyIP, ResolveHostServer.createResponseWithEmptyIp(hostWithEmptyIP, 100), -1); - // 显式设置 不开启本地缓存,避免测试干扰 + // 鏄惧紡璁剧疆 涓嶅紑鍚湰鍦扮紦瀛橈紝閬垮厤娴嬭瘯骞叉壈 HttpDns.resetInstance(); new InitConfig.Builder().setEnableCacheIp(false).buildFor(app.getAccountId()); app.start(true); - // 先请求一次,产生缓存 + // 鍏堣姹備竴娆★紝浜х敓缂撳瓨 app.requestResolveHost(hostWithEmptyIP); app.waitForAppThread(); - // 重置,重新初始化,触发读取缓存逻辑 + // 閲嶇疆锛岄噸鏂板垵濮嬪寲锛岃Е鍙戣鍙栫紦瀛橀€昏緫 HttpDns.resetInstance(); new InitConfig.Builder().setEnableCacheIp(false).buildFor(app.getAccountId()); app.start(true); - // 请求一次,读取缓存 + // 璇锋眰涓€娆★紝璇诲彇缂撳瓨 app.requestResolveHost(hostWithEmptyIP); app.waitForAppThread(); - MatcherAssert.assertThat("服务只接收到第一次请求", + MatcherAssert.assertThat("鏈嶅姟鍙帴鏀跺埌绗竴娆¤姹?, server.getResolveHostServer().hasRequestForArg(hostWithEmptyIP, 1, true)); } /** - * 预解析时,对于v4和v6结果的ttl 独立 + * 棰勮В鏋愭椂锛屽浜巚4鍜寁6缁撴灉鐨則tl 鐙珛 */ @Test public void testTtlDiffFromType() throws InterruptedException { @@ -393,31 +393,31 @@ public class V2_3_0 { ResolveHostServer.createResponse(host, null, RandomValue.randomIpv6s(), 300, null), -1); - // 预解析 + // 棰勮В鏋? app.preResolveHost(hosts, RequestIpType.both); app.waitForAppThread(); - // 等待ttl过期 + // 绛夊緟ttl杩囨湡 Thread.sleep(1000); - // 请求v4 会触发异步请求 + // 璇锋眰v4 浼氳Е鍙戝紓姝ヨ姹? app.requestResolveHost(host); app.waitForAppThread(); - MatcherAssert.assertThat("ttl过期后,异步请求", + MatcherAssert.assertThat("ttl杩囨湡鍚庯紝寮傛璇锋眰", server.getResolveHostServer().hasRequestForArg(host, 1, true)); - // 请求v6,因为没有过期 不会触发异步请求 + // 璇锋眰v6锛屽洜涓烘病鏈夎繃鏈?涓嶄細瑙﹀彂寮傛璇锋眰 app.requestResolveHostForIpv6(host); app.waitForAppThread(); - MatcherAssert.assertThat("v6的ttl与v4不同,未过期,不会触发异步请求", + MatcherAssert.assertThat("v6鐨則tl涓巚4涓嶅悓锛屾湭杩囨湡锛屼笉浼氳Е鍙戝紓姝ヨ姹?, server.getResolveHostServer() .hasRequestForArg(ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v6), 0, false)); } /** - * 预解析会过滤掉空解析域名, - * 其实这里本质上是过滤掉了有缓存的域名解析 + * 棰勮В鏋愪細杩囨护鎺夌┖瑙f瀽鍩熷悕, + * 鍏跺疄杩欓噷鏈川涓婃槸杩囨护鎺変簡鏈夌紦瀛樼殑鍩熷悕瑙f瀽 */ @Test public void testResolveFilterEmptyIP() { @@ -427,7 +427,7 @@ public class V2_3_0 { ArrayList normalHost = new ArrayList<>(); ArrayList allHost = new ArrayList<>(); - // 创建不同情况的域名和服务数据 + // 鍒涘缓涓嶅悓鎯呭喌鐨勫煙鍚嶅拰鏈嶅姟鏁版嵁 int count = RandomValue.randomInt(5) + 5; for (int i = 0; i < count; i++) { String host = RandomValue.randomHost(); @@ -462,41 +462,41 @@ public class V2_3_0 { allHost.add(host); } - // 请求所有的域名,产生缓存 + // 璇锋眰鎵€鏈夌殑鍩熷悕锛屼骇鐢熺紦瀛? for (String host : allHost) { app.requestResolveHost(host, RequestIpType.both); app.waitForAppThread(); } - // 修改域名的顺序 + // 淇敼鍩熷悕鐨勯『搴? allHost = UnitTestUtil.changeArrayListSort(allHost); - // 重置,重新初始化,清空内存缓存,重新从本地缓存读取 + // 閲嶇疆锛岄噸鏂板垵濮嬪寲锛屾竻绌哄唴瀛樼紦瀛橈紝閲嶆柊浠庢湰鍦扮紦瀛樿鍙? HttpDns.resetInstance(); new InitConfig.Builder().setEnableCacheIp(false).buildFor(app.getAccountId()); app.start(true); - // 预解析所有的域名 + // 棰勮В鏋愭墍鏈夌殑鍩熷悕 app.preResolveHost(allHost, RequestIpType.both); app.waitForAppThread(); - // 检测预解析是否符合预期 + // 妫€娴嬮瑙f瀽鏄惁绗﹀悎棰勬湡 for (String host : v6EmptyHost) { - MatcherAssert.assertThat("v6为空的,只会发起v4解析", + MatcherAssert.assertThat("v6涓虹┖鐨勶紝鍙細鍙戣捣v4瑙f瀽", server.getBatchResolveHostServer().hasRequestForHost(host, RequestIpType.v4, 1, false)); } for (String host : v4EmptyHost) { - MatcherAssert.assertThat("v4为空的,只会发起v6解析", + MatcherAssert.assertThat("v4涓虹┖鐨勶紝鍙細鍙戣捣v6瑙f瀽", server.getBatchResolveHostServer().hasRequestForHost(host, RequestIpType.v6, 1, false)); } for (String host : normalHost) { - MatcherAssert.assertThat("v4 v6都有的,不过滤", server.getBatchResolveHostServer() + MatcherAssert.assertThat("v4 v6閮芥湁鐨勶紝涓嶈繃婊?, server.getBatchResolveHostServer() .hasRequestForHost(host, RequestIpType.both, 1, false)); } } /** - * 预解析时 过滤掉有效的缓存,仅解析过期的或者不存在的域名 + * 棰勮В鏋愭椂 杩囨护鎺夋湁鏁堢殑缂撳瓨锛屼粎瑙f瀽杩囨湡鐨勬垨鑰呬笉瀛樺湪鐨勫煙鍚? */ @Test public void testPreResolveFilterValidCache() { @@ -506,7 +506,7 @@ public class V2_3_0 { ArrayList bothHost = new ArrayList<>(); ArrayList allHost = new ArrayList<>(); - // 创建不同情况的域名和服务数据 + // 鍒涘缓涓嶅悓鎯呭喌鐨勫煙鍚嶅拰鏈嶅姟鏁版嵁 int count = RandomValue.randomInt(5) + 5; for (int i = 0; i < count; i++) { String host = RandomValue.randomHost(); @@ -541,7 +541,7 @@ public class V2_3_0 { allHost.add(host); } - // 请求所有的域名,产生缓存 + // 璇锋眰鎵€鏈夌殑鍩熷悕锛屼骇鐢熺紦瀛? for (String host : v4Host) { app.requestResolveHost(host, RequestIpType.v4); app.waitForAppThread(); @@ -555,24 +555,24 @@ public class V2_3_0 { app.waitForAppThread(); } - // 修改域名的顺序 + // 淇敼鍩熷悕鐨勯『搴? allHost = UnitTestUtil.changeArrayListSort(allHost); - // 预解析所有的域名 + // 棰勮В鏋愭墍鏈夌殑鍩熷悕 app.preResolveHost(allHost, RequestIpType.both); app.waitForAppThread(); - // 检测预解析是否符合预期 + // 妫€娴嬮瑙f瀽鏄惁绗﹀悎棰勬湡 for (String host : v4Host) { - MatcherAssert.assertThat("v4有效,只会发起v6请求", + MatcherAssert.assertThat("v4鏈夋晥锛屽彧浼氬彂璧穠6璇锋眰", server.getBatchResolveHostServer().hasRequestForHost(host, RequestIpType.v6, 1, false)); } for (String host : v6Host) { - MatcherAssert.assertThat("v6有效,只会发起v4解析", + MatcherAssert.assertThat("v6鏈夋晥锛屽彧浼氬彂璧穠4瑙f瀽", server.getBatchResolveHostServer().hasRequestForHost(host, RequestIpType.v4, 1, false)); } for (String host : bothHost) { - MatcherAssert.assertThat("v4 v6都有效,不会请求", + MatcherAssert.assertThat("v4 v6閮芥湁鏁堬紝涓嶄細璇锋眰", server.getBatchResolveHostServer().hasRequestForHost(host, RequestIpType.both, 0, false) && server.getBatchResolveHostServer() .hasRequestForHost(host, RequestIpType.v4, 0, false) @@ -582,7 +582,7 @@ public class V2_3_0 { } /** - * 域名解析时,过滤已有缓存的域名 + * 鍩熷悕瑙f瀽鏃讹紝杩囨护宸叉湁缂撳瓨鐨勫煙鍚? */ @Test public void testResolveFilterValidCache() { @@ -591,7 +591,7 @@ public class V2_3_0 { ArrayList v6Host = new ArrayList<>(); ArrayList allHost = new ArrayList<>(); - // 创建不同情况的域名和服务数据 + // 鍒涘缓涓嶅悓鎯呭喌鐨勫煙鍚嶅拰鏈嶅姟鏁版嵁 int count = RandomValue.randomInt(5) + 5; for (int i = 0; i < count; i++) { String host = RandomValue.randomHost(); @@ -614,7 +614,7 @@ public class V2_3_0 { allHost.add(host); } - // 请求所有的域名,产生缓存 + // 璇锋眰鎵€鏈夌殑鍩熷悕锛屼骇鐢熺紦瀛? for (String host : v4Host) { app.requestResolveHost(host, RequestIpType.v4); app.waitForAppThread(); @@ -624,30 +624,30 @@ public class V2_3_0 { app.waitForAppThread(); } - // 修改域名的顺序 + // 淇敼鍩熷悕鐨勯『搴? allHost = UnitTestUtil.changeArrayListSort(allHost); - // 解析所有的域名 + // 瑙f瀽鎵€鏈夌殑鍩熷悕 for (String host : allHost) { app.requestResolveHost(host, RequestIpType.both); app.waitForAppThread(); } - // 检测预解析是否符合预期 + // 妫€娴嬮瑙f瀽鏄惁绗﹀悎棰勬湡 for (String host : v4Host) { - MatcherAssert.assertThat("v4缓存有效,只会发起v6请求", server.getResolveHostServer() + MatcherAssert.assertThat("v4缂撳瓨鏈夋晥锛屽彧浼氬彂璧穠6璇锋眰", server.getResolveHostServer() .hasRequestForArg(ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v6), 1, true)); } for (String host : v6Host) { - MatcherAssert.assertThat("v6缓存有效,只会发起v4请求", server.getResolveHostServer() + MatcherAssert.assertThat("v6缂撳瓨鏈夋晥锛屽彧浼氬彂璧穠4璇锋眰", server.getResolveHostServer() .hasRequestForArg(ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v4), 1, true)); } } /** - * 同步解析过滤已有缓存的域名 + * 鍚屾瑙f瀽杩囨护宸叉湁缂撳瓨鐨勫煙鍚? */ @Test public void testSyncResolveFilterValidCache() throws Throwable { @@ -658,7 +658,7 @@ public class V2_3_0 { ArrayList v6Host = new ArrayList<>(); ArrayList allHost = new ArrayList<>(); - // 创建不同情况的域名和服务数据 + // 鍒涘缓涓嶅悓鎯呭喌鐨勫煙鍚嶅拰鏈嶅姟鏁版嵁 int count = RandomValue.randomInt(5) + 5; for (int i = 0; i < count; i++) { String host = RandomValue.randomHost(); @@ -685,7 +685,7 @@ public class V2_3_0 { allHost.add(host); } - // 请求所有的域名,产生缓存 + // 璇锋眰鎵€鏈夌殑鍩熷悕锛屼骇鐢熺紦瀛? for (String host : v4Host) { app.requestResolveHostSync(host, RequestIpType.v4); } @@ -693,23 +693,23 @@ public class V2_3_0 { app.requestResolveHostSync(host, RequestIpType.v6); } - // 修改域名的顺序 + // 淇敼鍩熷悕鐨勯『搴? allHost = UnitTestUtil.changeArrayListSort(allHost); - // 解析所有的域名 + // 瑙f瀽鎵€鏈夌殑鍩熷悕 for (String host : allHost) { app.requestResolveHostSync(host, RequestIpType.both); } - // 检测预解析是否符合预期 + // 妫€娴嬮瑙f瀽鏄惁绗﹀悎棰勬湡 for (String host : v4Host) { - MatcherAssert.assertThat("v4缓存有效,只会发起v6请求", + MatcherAssert.assertThat("v4缂撳瓨鏈夋晥锛屽彧浼氬彂璧穠6璇锋眰", server.getResolveHostServer().hasRequestForArg( ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v6), 1, true)); } for (String host : v6Host) { - MatcherAssert.assertThat("v6缓存有效,只会发起v4请求", + MatcherAssert.assertThat("v6缂撳瓨鏈夋晥锛屽彧浼氬彂璧穠4璇锋眰", server.getResolveHostServer().hasRequestForArg( ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v4), 1, true)); @@ -719,7 +719,7 @@ public class V2_3_0 { } /** - * 测试不需要 重试和切换服务IP 的错误场景 + * 娴嬭瘯涓嶉渶瑕?閲嶈瘯鍜屽垏鎹㈡湇鍔P 鐨勯敊璇満鏅? */ @Test public void testUnsignedInterfaceDisabled() { @@ -785,22 +785,22 @@ public class V2_3_0 { app.setLogger(); - // 请求解析,触发错误处理逻辑 + // 璇锋眰瑙f瀽锛岃Е鍙戦敊璇鐞嗛€昏緫 app.requestResolveHost(host); app.waitForAppThread(); - MatcherAssert.assertThat("应该没有重试", + MatcherAssert.assertThat("搴旇娌℃湁閲嶈瘯", server.getResolveHostServer().hasRequestForArg(host, 1, true)); - MatcherAssert.assertThat("也没有切换服务重试", + MatcherAssert.assertThat("涔熸病鏈夊垏鎹㈡湇鍔¢噸璇?, server1.getResolveHostServer().hasRequestForArg(host, 0, false)); String anotherHost = RandomValue.randomHost(); app.requestResolveHost(anotherHost); app.waitForAppThread(); - MatcherAssert.assertThat("没有切换服务IP", + MatcherAssert.assertThat("娌℃湁鍒囨崲鏈嶅姟IP", server.getResolveHostServer().hasRequestForArg(anotherHost, 1, true)); - // 日志 + // 鏃ュ織 app.hasReceiveLogInLogger(code); app.removeLogger(); } @@ -816,22 +816,22 @@ public class V2_3_0 { app.setLogger(); - // 请求解析,触发错误处理逻辑 + // 璇锋眰瑙f瀽锛岃Е鍙戦敊璇鐞嗛€昏緫 app.requestResolveHost(host); app.waitForAppThread(); - MatcherAssert.assertThat("因为切换服务,第一个服务节点只请求了一次", + MatcherAssert.assertThat("鍥犱负鍒囨崲鏈嶅姟锛岀涓€涓湇鍔¤妭鐐瑰彧璇锋眰浜嗕竴娆?, server.getResolveHostServer().hasRequestForArg(host, 1, true)); - MatcherAssert.assertThat("切换服务重试", + MatcherAssert.assertThat("鍒囨崲鏈嶅姟閲嶈瘯", server1.getResolveHostServer().hasRequestForArg(host, 1, true)); String anotherHost = RandomValue.randomHost(); app.requestResolveHost(anotherHost); app.waitForAppThread(); - MatcherAssert.assertThat("切换服务IP", + MatcherAssert.assertThat("鍒囨崲鏈嶅姟IP", server2.getResolveHostServer().hasRequestForArg(anotherHost, 1, true)); - // 日志 + // 鏃ュ織 app.hasReceiveLogInLogger(code); app.removeLogger(); } @@ -849,23 +849,24 @@ public class V2_3_0 { server2.getResolveHostServer().preSetRequestResponse(host, statusCode, getErrorBody(code), -1); - // 请求解析,触发错误处理逻辑 + // 璇锋眰瑙f瀽锛岃Е鍙戦敊璇鐞嗛€昏緫 app.requestResolveHost(host); app.waitForAppThread(); - // 清除服务记录 + // 娓呴櫎鏈嶅姟璁板綍 server.getResolveHostServer().cleanRecord(); server1.getResolveHostServer().cleanRecord(); server2.getResolveHostServer().cleanRecord(); - // 再次请求 + // 鍐嶆璇锋眰 String[] ips = app.requestResolveHost(host); app.waitForAppThread(); - UnitTestUtil.assertIpsEmpty("生成的应该是空记录", ips); - MatcherAssert.assertThat("没有服务接收到请求", + UnitTestUtil.assertIpsEmpty("鐢熸垚鐨勫簲璇ユ槸绌鸿褰?, ips); + MatcherAssert.assertThat("娌℃湁鏈嶅姟鎺ユ敹鍒拌姹?, server.getResolveHostServer().hasRequestForArg(host, 0, false) && server1.getResolveHostServer().hasRequestForArg(host, 0, false) && server2.getResolveHostServer().hasRequestForArg(host, 0, false)); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_NetType.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_NetType.java index 7ca1ed4..f763d3f 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_NetType.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_NetType.java @@ -36,14 +36,14 @@ import java.util.Date; import static org.hamcrest.MatcherAssert.assertThat; /** - * 支持网络切换后,有很多逻辑需要调整,包括 - * 0. 调度请求,同时更新ipv4和ipv6 服务节点 - * 1. ipv6 only 场景下,调度使用ipv6服务节点 - * 2. ipv6 only 场景下,解析使用ipv6服务节点 - * 2.1 ipv6 only 场景下,服务节点的缓存和再次使用 - * 3. ipv4 切换 ipv6后,切换使用ipv6的服务节点解析 调度 - * 4. ipv6 切换 ipv4后,切换使用ipv4的服务节点解析 调度 - * 5. 解析时,根据网络类型判断解析哪种ip + * 鏀寔缃戠粶鍒囨崲鍚庯紝鏈夊緢澶氶€昏緫闇€瑕佽皟鏁达紝鍖呮嫭 + * 0. 璋冨害璇锋眰锛屽悓鏃舵洿鏂癷pv4鍜宨pv6 鏈嶅姟鑺傜偣 + * 1. ipv6 only 鍦烘櫙涓嬶紝璋冨害浣跨敤ipv6鏈嶅姟鑺傜偣 + * 2. ipv6 only 鍦烘櫙涓嬶紝瑙f瀽浣跨敤ipv6鏈嶅姟鑺傜偣 + * 2.1 ipv6 only 鍦烘櫙涓嬶紝鏈嶅姟鑺傜偣鐨勭紦瀛樺拰鍐嶆浣跨敤 + * 3. ipv4 鍒囨崲 ipv6鍚庯紝鍒囨崲浣跨敤ipv6鐨勬湇鍔¤妭鐐硅В鏋?璋冨害 + * 4. ipv6 鍒囨崲 ipv4鍚庯紝鍒囨崲浣跨敤ipv4鐨勬湇鍔¤妭鐐硅В鏋?璋冨害 + * 5. 瑙f瀽鏃讹紝鏍规嵁缃戠粶绫诲瀷鍒ゆ柇瑙f瀽鍝ip * * @author zonglin.nzl * @date 8/29/22 @@ -69,7 +69,7 @@ public class V2_3_0_NetType { @Before public void setUp() { - // 设置日志接口 + // 璁剧疆鏃ュ織鎺ュ彛 HttpDnsLog.enable(true); logger = new ILogger() { private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); @@ -80,11 +80,11 @@ public class V2_3_0_NetType { } }; HttpDnsLog.setLogger(logger); - // 重置实例 + // 閲嶇疆瀹炰緥 HttpDns.resetInstance(); - // 重置配置 + // 閲嶇疆閰嶇疆 InitConfig.removeConfig(null); - // 这里我们启动3个 服务节点用于测试 + // 杩欓噷鎴戜滑鍚姩3涓?鏈嶅姟鑺傜偣鐢ㄤ簬娴嬭瘯 serverV4One.start(); serverV4Two.start(); serverV4Three.start(); @@ -94,7 +94,7 @@ public class V2_3_0_NetType { ShadowApplication application = Shadows.shadowOf(RuntimeEnvironment.application); application.grantPermissions(Manifest.permission.ACCESS_NETWORK_STATE); - // 内置第一个服务节点,第二、三个服务节点作为调度请求的结果 + // 鍐呯疆绗竴涓湇鍔¤妭鐐癸紝绗簩銆佷笁涓湇鍔¤妭鐐逛綔涓鸿皟搴﹁姹傜殑缁撴灉 String response = ServerIpsServer.createUpdateServerResponse( new String[]{serverV4Two.getServerIp(), serverV4Three.getServerIp()}, new String[]{serverV6Two.getServerIp(), serverV6Three.getServerIp()}, @@ -130,77 +130,77 @@ public class V2_3_0_NetType { /** - * 启动更新服务IP, ipv4 + * 鍚姩鏇存柊鏈嶅姟IP锛?ipv4 */ @Test public void testUpdateServerWhenStart() { - // v4 网络情况下启动 + // v4 缃戠粶鎯呭喌涓嬪惎鍔? app.changeNetType(NetType.v4); app.start(false); - ServerStatusHelper.hasReceiveRegionChange("v4网络下使用内置v4节点更新服务", app, serverV4One, REGION_DEFAULT, true); + ServerStatusHelper.hasReceiveRegionChange("v4缃戠粶涓嬩娇鐢ㄥ唴缃畍4鑺傜偣鏇存柊鏈嶅姟", app, serverV4One, REGION_DEFAULT, true); - // 随便发起一个请求 + // 闅忎究鍙戣捣涓€涓姹? app.requestResolveHost(); - // 确认服务节点是否更新成功 - ServerStatusHelper.hasReceiveAppResolveHostRequest("更新后,使用新服务节点解析", app, serverV4Two, 1); + // 纭鏈嶅姟鑺傜偣鏄惁鏇存柊鎴愬姛 + ServerStatusHelper.hasReceiveAppResolveHostRequest("鏇存柊鍚庯紝浣跨敤鏂版湇鍔¤妭鐐硅В鏋?, app, serverV4Two, 1); } /** - * 启动更新服务IP, ipv6 + * 鍚姩鏇存柊鏈嶅姟IP锛?ipv6 */ @Test public void testUpdateServerWhenStartUnderV6() { - // v6 网络情况下启动 + // v6 缃戠粶鎯呭喌涓嬪惎鍔? app.changeNetType(NetType.v6); app.start(false); - ServerStatusHelper.hasReceiveRegionChange("v6网络下使用内置v6节点更新服务", app, serverV6One, REGION_DEFAULT, true); + ServerStatusHelper.hasReceiveRegionChange("v6缃戠粶涓嬩娇鐢ㄥ唴缃畍6鑺傜偣鏇存柊鏈嶅姟", app, serverV6One, REGION_DEFAULT, true); - // 随便发起一个请求 + // 闅忎究鍙戣捣涓€涓姹? app.requestResolveHost(); - // 确认服务节点是否更新成功 - ServerStatusHelper.hasReceiveAppResolveHostRequest("更新后,使用新服务节点解析", app, serverV6Two, 1); + // 纭鏈嶅姟鑺傜偣鏄惁鏇存柊鎴愬姛 + ServerStatusHelper.hasReceiveAppResolveHostRequest("鏇存柊鍚庯紝浣跨敤鏂版湇鍔¤妭鐐硅В鏋?, app, serverV6Two, 1); } /** - * 启动更新服务IP, both + * 鍚姩鏇存柊鏈嶅姟IP锛?both */ @Test public void testUpdateServerWhenStartUnderV4V6() { - // 都支持 网络情况下启动 + // 閮芥敮鎸?缃戠粶鎯呭喌涓嬪惎鍔? app.changeNetType(NetType.both); app.start(false); - ServerStatusHelper.hasReceiveRegionChange("都支持的网络下使用内置v4节点更新服务", app, serverV4One, REGION_DEFAULT, true); + ServerStatusHelper.hasReceiveRegionChange("閮芥敮鎸佺殑缃戠粶涓嬩娇鐢ㄥ唴缃畍4鑺傜偣鏇存柊鏈嶅姟", app, serverV4One, REGION_DEFAULT, true); - // 随便发起一个请求 + // 闅忎究鍙戣捣涓€涓姹? app.requestResolveHost(); - // 确认服务节点是否更新成功 - ServerStatusHelper.hasReceiveAppResolveHostRequest("更新后,使用新服务节点解析", app, serverV4Two, 1); + // 纭鏈嶅姟鑺傜偣鏄惁鏇存柊鎴愬姛 + ServerStatusHelper.hasReceiveAppResolveHostRequest("鏇存柊鍚庯紝浣跨敤鏂版湇鍔¤妭鐐硅В鏋?, app, serverV4Two, 1); } /** - * 测试ipv6服务节点的缓存 + * 娴嬭瘯ipv6鏈嶅姟鑺傜偣鐨勭紦瀛? */ @Test public void testCacheIpv6ServerIps() { - // 先利用此case获取ipv6的服务节点 + // 鍏堝埄鐢ㄦcase鑾峰彇ipv6鐨勬湇鍔¤妭鐐? testUpdateServerWhenStartUnderV6(); String host = RandomValue.randomHost(); serverV6Two.getResolveHostServer().preSetRequestResponse(host, 403, "whatever", -1); - // 发起一次请求,使切换服务节点 + // 鍙戣捣涓€娆¤姹傦紝浣垮垏鎹㈡湇鍔¤妭鐐? app.requestResolveHost(host); app.waitForAppThread(); - assertThat("第一次失败后,切换服务IP重试", serverV6Three.getResolveHostServer().hasRequestForArg(host, 1, true)); + assertThat("绗竴娆″け璐ュ悗锛屽垏鎹㈡湇鍔P閲嶈瘯", serverV6Three.getResolveHostServer().hasRequestForArg(host, 1, true)); - // 重置 + // 閲嶇疆 HttpDns.resetInstance(); serverV6One.getServerIpsServer().cleanRecord(); serverV6One.getResolveHostServer().cleanRecord(); @@ -209,7 +209,7 @@ public class V2_3_0_NetType { serverV6Three.getServerIpsServer().cleanRecord(); serverV6Three.getResolveHostServer().cleanRecord(); - // 模拟第二次启动 + // 妯℃嫙绗簩娆″惎鍔? app.changeNetType(NetType.v6); app.start(false); @@ -217,21 +217,21 @@ public class V2_3_0_NetType { app.requestResolveHost(anotherHost); app.waitForAppThread(); - assertThat("启动时,从缓存中读取服务节点使用", serverV6Three.getResolveHostServer().hasRequestForArg(anotherHost, 1, true)); + assertThat("鍚姩鏃讹紝浠庣紦瀛樹腑璇诲彇鏈嶅姟鑺傜偣浣跨敤", serverV6Three.getResolveHostServer().hasRequestForArg(anotherHost, 1, true)); } /** - * 网络变化时,切换对应的服务节点 + * 缃戠粶鍙樺寲鏃讹紝鍒囨崲瀵瑰簲鐨勬湇鍔¤妭鐐? */ @Test @Config(shadows = {ShadowNetworkInfo.class}) public void testChangeServerIpWhenNetChange() { - //复用case 获取测试环境, 当前应该是 v6网络,serverV6Three 是当前服务节点,v4的服务节点应该是serverV4Two + //澶嶇敤case 鑾峰彇娴嬭瘯鐜锛?褰撳墠搴旇鏄?v6缃戠粶锛宻erverV6Three 鏄綋鍓嶆湇鍔¤妭鐐癸紝v4鐨勬湇鍔¤妭鐐瑰簲璇ユ槸serverV4Two testCacheIpv6ServerIps(); - // 网络变化到v4 wifi + // 缃戠粶鍙樺寲鍒皏4 wifi app.changeNetType(NetType.v4); app.changeToNetwork(ConnectivityManager.TYPE_WIFI); @@ -239,10 +239,10 @@ public class V2_3_0_NetType { app.requestResolveHost(host1); app.waitForAppThread(); - assertThat("网络环境变为v4后使用v4的服务节点", serverV4Two.getResolveHostServer().hasRequestForArg(host1, 1, true)); + assertThat("缃戠粶鐜鍙樹负v4鍚庝娇鐢╲4鐨勬湇鍔¤妭鐐?, serverV4Two.getResolveHostServer().hasRequestForArg(host1, 1, true)); - // 网络变化到v6 mobile + // 缃戠粶鍙樺寲鍒皏6 mobile app.changeNetType(NetType.v6); app.changeToNetwork(ConnectivityManager.TYPE_MOBILE); @@ -250,9 +250,9 @@ public class V2_3_0_NetType { app.requestResolveHost(host2); app.waitForAppThread(); - assertThat("网络环境变为v6后使用v6的服务节点", serverV6Three.getResolveHostServer().hasRequestForArg(host2, 1, true)); + assertThat("缃戠粶鐜鍙樹负v6鍚庝娇鐢╲6鐨勬湇鍔¤妭鐐?, serverV6Three.getResolveHostServer().hasRequestForArg(host2, 1, true)); - // 网络变化到都支持 wifi + // 缃戠粶鍙樺寲鍒伴兘鏀寔 wifi app.changeNetType(NetType.both); app.changeToNetwork(ConnectivityManager.TYPE_WIFI); @@ -260,14 +260,14 @@ public class V2_3_0_NetType { app.requestResolveHost(host3); app.waitForAppThread(); - assertThat("网络环境变为both后使用v4的服务节点", serverV4Two.getResolveHostServer().hasRequestForArg(host3, 1, true)); + assertThat("缃戠粶鐜鍙樹负both鍚庝娇鐢╲4鐨勬湇鍔¤妭鐐?, serverV4Two.getResolveHostServer().hasRequestForArg(host3, 1, true)); } @Test public void testAutoRequestIpTypeForIpv4() { - // 复用case 获取v4网络状态 + // 澶嶇敤case 鑾峰彇v4缃戠粶鐘舵€? testUpdateServerWhenStart(); serverV4Two.getResolveHostServer().cleanRecord(); @@ -275,12 +275,12 @@ public class V2_3_0_NetType { app.requestResolveHost(host, RequestIpType.auto); app.waitForAppThread(); - assertThat("当前网络仅支持v4时,自动解析只会解析v4类型", serverV4Two.getResolveHostServer().hasRequestForArg(host, 1, true)); + assertThat("褰撳墠缃戠粶浠呮敮鎸乿4鏃讹紝鑷姩瑙f瀽鍙細瑙f瀽v4绫诲瀷", serverV4Two.getResolveHostServer().hasRequestForArg(host, 1, true)); } @Test public void testAutoRequestIpTypeForIpv6() { - // 复用case 获取v6网络状态 + // 澶嶇敤case 鑾峰彇v6缃戠粶鐘舵€? testUpdateServerWhenStartUnderV6(); serverV6Two.getResolveHostServer().cleanRecord(); @@ -288,12 +288,12 @@ public class V2_3_0_NetType { app.requestResolveHost(host, RequestIpType.auto); app.waitForAppThread(); - assertThat("当前网络仅支持v6时,自动解析只会解析v6类型", serverV6Two.getResolveHostServer().hasRequestForArg(ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v6), 1, true)); + assertThat("褰撳墠缃戠粶浠呮敮鎸乿6鏃讹紝鑷姩瑙f瀽鍙細瑙f瀽v6绫诲瀷", serverV6Two.getResolveHostServer().hasRequestForArg(ResolveHostServer.ResolveHostArg.create(host, RequestIpType.v6), 1, true)); } @Test public void testAutoRequestIpTypeForBoth() { - // 复用case 获取v4v6网络状态 + // 澶嶇敤case 鑾峰彇v4v6缃戠粶鐘舵€? testUpdateServerWhenStartUnderV4V6(); serverV4Two.getResolveHostServer().cleanRecord(); @@ -301,6 +301,7 @@ public class V2_3_0_NetType { app.requestResolveHost(host, RequestIpType.auto); app.waitForAppThread(); - assertThat("当前网络支持v4v6时,自动解析会解析v4v6类型", serverV4Two.getResolveHostServer().hasRequestForArg(ResolveHostServer.ResolveHostArg.create(host, RequestIpType.both), 1, true)); + assertThat("褰撳墠缃戠粶鏀寔v4v6鏃讹紝鑷姩瑙f瀽浼氳В鏋恦4v6绫诲瀷", serverV4Two.getResolveHostServer().hasRequestForArg(ResolveHostServer.ResolveHostArg.create(host, RequestIpType.both), 1, true)); } } + diff --git a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_config.java b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_config.java index 2d58b27..950e8df 100644 --- a/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_config.java +++ b/EdgeHttpDNS/sdk/android/httpdns-sdk/src/testEnd2end/java/com/alibaba/sdk/android/httpdns/version/V2_3_0_config.java @@ -27,9 +27,9 @@ import java.util.Date; import static org.hamcrest.MatcherAssert.assertThat; /** - * 2.3.0 版本中关于初始IP配置的需求, 因为和一般case的条件不同,所以单独列出 - * 1. 默认服务可以不是 中国大陆 - * 2. 增加默认调度IP,即在当前服务IP调度失败,初始服务IP调度失败时,使用默认的调度IP,此能力是应用国际版初始IP不稳定的情况 + * 2.3.0 鐗堟湰涓叧浜庡垵濮婭P閰嶇疆鐨勯渶姹傦紝 鍥犱负鍜屼竴鑸琧ase鐨勬潯浠朵笉鍚岋紝鎵€浠ュ崟鐙垪鍑? + * 1. 榛樿鏈嶅姟鍙互涓嶆槸 涓浗澶ч檰 + * 2. 澧炲姞榛樿璋冨害IP锛屽嵆鍦ㄥ綋鍓嶆湇鍔P璋冨害澶辫触锛屽垵濮嬫湇鍔P璋冨害澶辫触鏃讹紝浣跨敤榛樿鐨勮皟搴P锛屾鑳藉姏鏄簲鐢ㄥ浗闄呯増鍒濆IP涓嶇ǔ瀹氱殑鎯呭喌 * * @author zonglin.nzl * @date 8/26/22 @@ -50,7 +50,7 @@ public class V2_3_0_config { @Before public void setUp() { - // 设置日志接口 + // 璁剧疆鏃ュ織鎺ュ彛 HttpDnsLog.enable(true); logger = new ILogger() { private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); @@ -63,11 +63,11 @@ public class V2_3_0_config { } }; HttpDnsLog.setLogger(logger); - // 重置实例 + // 閲嶇疆瀹炰緥 HttpDns.resetInstance(); - // 重置配置 + // 閲嶇疆閰嶇疆 InitConfig.removeConfig(null); - // 这里我们启动3个 服务节点用于测试 + // 杩欓噷鎴戜滑鍚姩3涓?鏈嶅姟鑺傜偣鐢ㄤ簬娴嬭瘯 server.start(); server1.start(); server2.start(); @@ -88,8 +88,8 @@ public class V2_3_0_config { } /** - * 默认region可以是其它region - * 通过修改region配置,验证初始化时,使用的region不同 + * 榛樿region鍙互鏄叾瀹價egion + * 閫氳繃淇敼region閰嶇疆锛岄獙璇佸垵濮嬪寲鏃讹紝浣跨敤鐨剅egion涓嶅悓 */ @Test public void testDefaultRegion() { @@ -97,23 +97,24 @@ public class V2_3_0_config { } /** - * 更新服务IP时,包括 初始化时,和后续修改region时 如果前面的服务失败,能够回退到默认的服务IP进行调度请求 + * 鏇存柊鏈嶅姟IP鏃讹紝鍖呮嫭 鍒濆鍖栨椂锛屽拰鍚庣画淇敼region鏃?濡傛灉鍓嶉潰鐨勬湇鍔″け璐ワ紝鑳藉鍥為€€鍒伴粯璁ょ殑鏈嶅姟IP杩涜璋冨害璇锋眰 */ @Test public void testUpdateServerFallbackToDefaultUpdateServer() { - // 初始服务 调度失败 + // 鍒濆鏈嶅姟 璋冨害澶辫触 server.getServerIpsServer().preSetRequestResponse(REGION_DEFAULT, 500, "whatever", -1); - // 第一个默认调度服务 也失败 + // 绗竴涓粯璁よ皟搴︽湇鍔?涔熷け璐? server1.getServerIpsServer().preSetRequestResponse(REGION_DEFAULT, 500, "whatever", -1); app.configInitServer(REGION_DEFAULT, new HttpDnsServer[] {server}, new HttpDnsServer[] {server1, server2}); - // 初始化httpdns 初始化调度请求 + // 鍒濆鍖杊ttpdns 鍒濆鍖栬皟搴﹁姹? app.start(false); app.waitForAppThread(); - assertThat("调度请求失败会回退到默认调度IP请求, region " + REGION_DEFAULT, + assertThat("璋冨害璇锋眰澶辫触浼氬洖閫€鍒伴粯璁よ皟搴P璇锋眰, region " + REGION_DEFAULT, server2.getServerIpsServer().hasRequestForArg(REGION_DEFAULT, 1, true)); } } + diff --git a/EdgeHttpDNS/sdk/dist/README.md b/EdgeHttpDNS/sdk/dist/README.md new file mode 100644 index 0000000..717b47f --- /dev/null +++ b/EdgeHttpDNS/sdk/dist/README.md @@ -0,0 +1,77 @@ +# HTTPDNS Android SDK (SNI Hidden v1.0.0) + +## 1. Init + +```java +import com.Trust.sdk.android.httpdns.HttpDns; +import com.Trust.sdk.android.httpdns.HttpDnsService; +import com.Trust.sdk.android.httpdns.InitConfig; + +String appId = "app1f1ndpo9"; + +new InitConfig.Builder() + .setContext(context) + .setPrimaryServiceHost("httpdns-a.example.com") + .setBackupServiceHost("httpdns-b.example.com") + .setServicePort(443) + .setSecretKey("your-sign-secret") // optional if sign is enabled + .setEnableHttps(true) + .buildFor(appId); + +HttpDnsService httpDnsService = HttpDns.getService(appId); +``` + +## 2. Resolve + +```java +HTTPDNSResult result = httpDnsService.getHttpDnsResultForHostSyncNonBlocking( + "api.business.com", + RequestIpType.auto, + null, + null +); +``` + +## 3. Official HTTP Adapter (IP + Empty-SNI + Host) + +```java +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterOptions; +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterRequest; +import com.Trust.sdk.android.httpdns.network.HttpDnsAdapterResponse; +import com.Trust.sdk.android.httpdns.network.HttpDnsHttpAdapter; + +HttpDnsHttpAdapter adapter = HttpDns.buildHttpClientAdapter( + httpDnsService, + new HttpDnsAdapterOptions.Builder() + .setConnectTimeoutMillis(3000) + .setReadTimeoutMillis(5000) + .setRequestIpType(RequestIpType.auto) + .setAllowInsecureCertificatesForDebugOnly(false) + .build() +); + +HttpDnsAdapterResponse response = adapter.execute( + new HttpDnsAdapterRequest("GET", "https://api.business.com/v1/ping") +); +``` + +Behavior is fixed: +- Resolve by `/resolve`. +- Connect to resolved IP over HTTPS. +- Keep `Host` header as business domain. +- No fallback to domain direct request. + +## 4. Public Errors + +- `NO_IP_AVAILABLE` +- `TLS_EMPTY_SNI_FAILED` +- `HOST_ROUTE_REJECTED` +- `RESOLVE_SIGN_INVALID` + +## 5. Removed Public Params + +Do not use legacy public parameters: +- `accountId` +- `serviceDomain` +- `endpoint` +- `aesSecretKey` diff --git a/EdgeHttpDNS/sdk/dist/alicloud-android-crashdefend-0.0.6.jar b/EdgeHttpDNS/sdk/dist/alicloud-android-crashdefend-0.0.6.jar new file mode 100644 index 0000000..c2547d6 Binary files /dev/null and b/EdgeHttpDNS/sdk/dist/alicloud-android-crashdefend-0.0.6.jar differ diff --git a/EdgeHttpDNS/sdk/dist/alicloud-android-httpdns-2.6.7.aar b/EdgeHttpDNS/sdk/dist/alicloud-android-httpdns-2.6.7.aar new file mode 100644 index 0000000..6bacaf9 Binary files /dev/null and b/EdgeHttpDNS/sdk/dist/alicloud-android-httpdns-2.6.7.aar differ diff --git a/EdgeHttpDNS/sdk/dist/alicloud-android-ipdetector-1.2.0.aar b/EdgeHttpDNS/sdk/dist/alicloud-android-ipdetector-1.2.0.aar new file mode 100644 index 0000000..843f9d7 Binary files /dev/null and b/EdgeHttpDNS/sdk/dist/alicloud-android-ipdetector-1.2.0.aar differ diff --git a/EdgeHttpDNS/sdk/dist/alicloud-android-logger-1.2.0.aar b/EdgeHttpDNS/sdk/dist/alicloud-android-logger-1.2.0.aar new file mode 100644 index 0000000..d3bb217 Binary files /dev/null and b/EdgeHttpDNS/sdk/dist/alicloud-android-logger-1.2.0.aar differ diff --git a/EdgeHttpDNS/sdk/dist/proguard-rules.pro b/EdgeHttpDNS/sdk/dist/proguard-rules.pro new file mode 100644 index 0000000..c1def44 --- /dev/null +++ b/EdgeHttpDNS/sdk/dist/proguard-rules.pro @@ -0,0 +1,68 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/ryan/Downloads/adt-bundle-mac-x86_64-20131030/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} +-optimizationpasses 3 +-dontoptimize +-dontusemixedcaseclassnames +-dontskipnonpubliclibraryclasses +-verbose +-overloadaggressively +#-allowaccessmodification +-useuniqueclassmembernames + +-dontwarn com.alibaba.sdk.android.httpdns.net.HttpDnsNetworkDetector + +-keeppackagenames com.alibaba.sdk.android.httpdns +-flattenpackagehierarchy com.alibaba.sdk.android.httpdns +-keep class com.alibaba.sdk.android.httpdns.HttpDns{*;} +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsService{*;} +-keep class com.alibaba.sdk.android.httpdns.impl.ErrorImpl{*;} +-keep interface com.alibaba.sdk.android.httpdns.SyncService{*;} +-keep class com.alibaba.sdk.android.httpdns.InitConfig{*;} +-keep class com.alibaba.sdk.android.httpdns.InitConfig$Builder{*;} +-keep class com.alibaba.sdk.android.httpdns.RequestIpType{*;} +-keep interface com.alibaba.sdk.android.httpdns.DegradationFilter{*;} +-keep interface com.alibaba.sdk.android.httpdns.NotUseHttpDnsFilter{*;} +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsCallback{*;} +-keep class com.alibaba.sdk.android.httpdns.ranking.IPRankingBean{*;} +-keep interface com.alibaba.sdk.android.httpdns.ILogger{*;} +-keep interface com.alibaba.sdk.android.httpdns.CacheTtlChanger{*;} +-keep class com.alibaba.sdk.android.httpdns.NetType{*;} +-keepclasseswithmembers class com.alibaba.sdk.android.httpdns.log.HttpDnsLog { + public static *** setLogger(***); + public static *** removeLogger(***); + public static *** enable(***); +} +-keep class com.alibaba.sdk.android.httpdns.HTTPDNSResult{*;} +-keepclasseswithmembers class com.alibaba.sdk.android.httpdns.HttpDnsSettings { + public static *** setDailyReport(***); + public static *** setNetworkChecker(***); +} + +-keep class com.alibaba.sdk.android.httpdns.net.HttpDnsNetworkDetector { + public ; + public ; +} + +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsSettings$NetworkChecker{*;} +-keep interface com.alibaba.sdk.android.httpdns.HttpDnsSettings$NetworkDetector{*;} +-keep class com.alibaba.sdk.android.httpdns.utils.CommonUtil{ + public ; + public ; +} +-keep enum com.alibaba.sdk.android.httpdns.Region {*;} +-keep class com.alibaba.sdk.android.httpdns.exception.InitException{*;} diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/CHANGELOG.md b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/CHANGELOG.md index 688b21a..74b1755 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/CHANGELOG.md +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/CHANGELOG.md @@ -1,11 +1,11 @@ ## 1.0.2 -* 升级 iOS HTTPDNS SDK 至 3.4.0 版本 +* 升级 iOS HTTPDNS SDK ?3.4.0 版本 ## 1.0.1 -* 新增 IP 优选功能 +* 新增 IP 优选功? * 现有接口功能优化 -* 升级 Android HTTPDNS SDK 至 2.6.7 版本 -* 升级 iOS HTTPDNS SDK 至 3.3.0 版本 +* 升级 Android HTTPDNS SDK ?2.6.7 版本 +* 升级 iOS HTTPDNS SDK ?3.3.0 版本 ## 1.0.0 * 重构插件,更新接入方式和各个接口 diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/README.md b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/README.md index 9b3c76e..d7f747c 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/README.md +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/README.md @@ -1,4 +1,4 @@ -# HTTPDNS Flutter SDK (SNI Hidden v1.0.0) +# HTTPDNS Flutter SDK (SNI Hidden v1.0.0) ## 1. Initialization diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/android/src/main/kotlin/com/aliyun/ams/httpdns/AliyunHttpDnsPlugin.kt b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/android/src/main/kotlin/com/aliyun/ams/httpdns/AliyunHttpDnsPlugin.kt index 13b2470..d5477bf 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/android/src/main/kotlin/com/aliyun/ams/httpdns/AliyunHttpDnsPlugin.kt +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/android/src/main/kotlin/com/aliyun/ams/httpdns/AliyunHttpDnsPlugin.kt @@ -1,20 +1,20 @@ -package com.aliyun.ams.httpdns +package com.TrustAPP.ams.httpdns import android.content.Context import android.util.Log import androidx.annotation.NonNull -import com.alibaba.sdk.android.httpdns.HttpDns -import com.alibaba.sdk.android.httpdns.HttpDnsService -import com.alibaba.sdk.android.httpdns.InitConfig -import com.alibaba.sdk.android.httpdns.RequestIpType -import com.alibaba.sdk.android.httpdns.log.HttpDnsLog +import com.Trust.sdk.android.httpdns.HttpDns +import com.Trust.sdk.android.httpdns.HttpDnsService +import com.Trust.sdk.android.httpdns.InitConfig +import com.Trust.sdk.android.httpdns.RequestIpType +import com.Trust.sdk.android.httpdns.log.HttpDnsLog import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result -class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { +class TrustAPPHttpDnsPlugin : FlutterPlugin, MethodCallHandler { private lateinit var channel: MethodChannel private var appContext: Context? = null @@ -36,7 +36,7 @@ class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { appContext = flutterPluginBinding.applicationContext - channel = MethodChannel(flutterPluginBinding.binaryMessenger, "aliyun_httpdns") + channel = MethodChannel(flutterPluginBinding.binaryMessenger, "TrustAPP_httpdns") channel.setMethodCallHandler(this) } @@ -58,14 +58,14 @@ class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { else -> "" } if (parsedAppId.isBlank()) { - Log.i("AliyunHttpDns", "initialize missing appId") + Log.i("TrustAPPHttpDns", "initialize missing appId") result.success(false) return } val primaryHostArg = (args["primaryServiceHost"] as? String)?.trim() if (primaryHostArg.isNullOrBlank()) { - Log.i("AliyunHttpDns", "initialize missing primaryServiceHost") + Log.i("TrustAPPHttpDns", "initialize missing primaryServiceHost") result.success(false) return } @@ -86,7 +86,7 @@ class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { servicePort = if (port != null && port > 0) port else null Log.i( - "AliyunHttpDns", + "TrustAPPHttpDns", "initialize appId=$appId, primaryServiceHost=$primaryServiceHost, backupServiceHost=$backupServiceHost, servicePort=$servicePort" ) result.success(true) @@ -194,7 +194,7 @@ class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { .invoke(builder, primaryServiceHost) hostConfigApplied = true } catch (t: Throwable) { - Log.w("AliyunHttpDns", "setPrimaryServiceHost failed: ${t.message}") + Log.w("TrustAPPHttpDns", "setPrimaryServiceHost failed: ${t.message}") } try { backupServiceHost?.let { @@ -250,7 +250,7 @@ class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { try { desiredIPRankingMap?.let { map -> if (map.isNotEmpty()) { - val beanClass = Class.forName("com.alibaba.sdk.android.httpdns.ranking.IPRankingBean") + val beanClass = Class.forName("com.Trust.sdk.android.httpdns.ranking.IPRankingBean") val ctor = beanClass.getConstructor(String::class.java, Int::class.javaPrimitiveType) val list = ArrayList() map.forEach { (host, port) -> @@ -264,7 +264,7 @@ class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { } if (!hostConfigApplied) { - Log.w("AliyunHttpDns", "build failed: sdk core does not support primaryServiceHost") + Log.w("TrustAPPHttpDns", "build failed: sdk core does not support primaryServiceHost") result.success(false) return } @@ -279,7 +279,7 @@ class AliyunHttpDnsPlugin : FlutterPlugin, MethodCallHandler { result.success(true) } catch (t: Throwable) { - Log.w("AliyunHttpDns", "build failed: ${t.message}") + Log.w("TrustAPPHttpDns", "build failed: ${t.message}") result.success(false) } } diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/README.md b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/README.md index 79abf46..ea5b64d 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/README.md +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/README.md @@ -1,6 +1,6 @@ -# aliyun_httpdns_example +# TrustAPP_httpdns_example -Demonstrates how to use the aliyun_httpdns plugin with various network libraries. +Demonstrates how to use the TrustAPP_httpdns plugin with various network libraries. ## Features @@ -18,7 +18,7 @@ This example demonstrates: 1. Replace the SDK init parameters in `lib/main.dart` with your own values: ```dart - await AliyunHttpdns.init( + await TrustAPPHttpdns.init( appId: 'YOUR_APP_ID', primaryServiceHost: 'httpdns-a.example.com', backupServiceHost: 'httpdns-b.example.com', diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md index 89c2725..b5b843a 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -2,4 +2,4 @@ You can customize the launch screen with your own desired assets by replacing the image files in this directory. -You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/main.dart b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/main.dart index ae47b8f..195dc19 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/main.dart +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/main.dart @@ -4,7 +4,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import 'net/httpdns_http_client_adapter.dart'; -import 'package:aliyun_httpdns/aliyun_httpdns.dart'; +import 'package:TrustAPP_httpdns/TrustAPP_httpdns.dart'; void main() { runApp(const MyApp()); @@ -63,22 +63,19 @@ class _MyHomePageState extends State { if (_httpdnsReady || _httpdnsIniting) return; _httpdnsIniting = true; try { - await AliyunHttpdns.init( + await TrustAPPHttpdns.init( appId: 'app1f1ndpo9', // 请替换为您的应用 AppId - primaryServiceHost: 'httpdns-a.example.com', // 请替换为主服务域名 - backupServiceHost: 'httpdns-b.example.com', // 可选:备服务域名 - servicePort: 443, - secretKey: 'your_sign_secret_here', // 可选:仅验签开启时需要 - ); - await AliyunHttpdns.setHttpsRequestEnabled(true); - await AliyunHttpdns.setLogEnabled(true); - await AliyunHttpdns.setPersistentCacheIPEnabled(true); - await AliyunHttpdns.setReuseExpiredIPEnabled(true); - await AliyunHttpdns.build(); + primaryServiceHost: 'httpdns-a.example.com', // 请替换为主服务域? backupServiceHost: 'httpdns-b.example.com', // 可选:备服务域? servicePort: 443, + secretKey: 'your_sign_secret_here', // 可选:仅验签开启时需? ); + await TrustAPPHttpdns.setHttpsRequestEnabled(true); + await TrustAPPHttpdns.setLogEnabled(true); + await TrustAPPHttpdns.setPersistentCacheIPEnabled(true); + await TrustAPPHttpdns.setReuseExpiredIPEnabled(true); + await TrustAPPHttpdns.build(); - // 先build再执行解析相关动作 - final preResolveHosts = 'www.aliyun.com'; - await AliyunHttpdns.setPreResolveHosts([preResolveHosts], ipType: 'both'); + // 先build再执行解析相关动? + final preResolveHosts = 'www.TrustAPP.com'; + await TrustAPPHttpdns.setPreResolveHosts([preResolveHosts], ipType: 'both'); debugPrint('[httpdns] pre-resolve scheduled for host=$preResolveHosts'); _httpdnsReady = true; } catch (e) { @@ -92,9 +89,9 @@ class _MyHomePageState extends State { void initState() { super.initState(); // 设置默认的API URL用于演示 - _urlController.text = 'https://www.aliyun.com'; + _urlController.text = 'https://www.TrustAPP.com'; - // 仅首次进入页面时初始化 HTTPDNS + // 仅首次进入页面时初始?HTTPDNS _initHttpDnsOnce(); // 先初始化HTTPDNS再初始化Dio @@ -218,7 +215,7 @@ class _MyHomePageState extends State { } } - // 使用 HTTPDNS 解析当前 URL 的 host 并显示结果 + // 使用 HTTPDNS 解析当前 URL ?host 并显示结? Future _testHttpDnsResolve() async { final text = _urlController.text.trim(); if (text.isEmpty) { @@ -244,9 +241,9 @@ class _MyHomePageState extends State { }); try { - // 确保只初始化一次 + // 确保只初始化一? await _initHttpDnsOnce(); - final res = await AliyunHttpdns.resolveHostSyncNonBlocking( + final res = await TrustAPPHttpdns.resolveHostSyncNonBlocking( uri.host, ipType: 'both', ); @@ -281,12 +278,12 @@ class _MyHomePageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - // URL输入框 + // URL输入? TextField( controller: _urlController, decoration: const InputDecoration( labelText: 'Enter URL', - hintText: 'https://www.aliyun.com', + hintText: 'https://www.TrustAPP.com', border: OutlineInputBorder(), prefixIcon: Icon(Icons.link), ), diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/net/httpdns_http_client_adapter.dart b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/net/httpdns_http_client_adapter.dart index eab63fc..0f32b29 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/net/httpdns_http_client_adapter.dart +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/example/lib/net/httpdns_http_client_adapter.dart @@ -4,12 +4,12 @@ import 'package:dio/io.dart'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'package:http/io_client.dart'; -import 'package:aliyun_httpdns/aliyun_httpdns.dart'; +import 'package:TrustAPP_httpdns/TrustAPP_httpdns.dart'; /* * - * 构建带 HTTPDNS 能力的 IOHttpClientAdapter + * 构建?HTTPDNS 能力?IOHttpClientAdapter * - * 本方案由EMAS团队设计实现,参考请注明出处。 + * 本方案由EMAS团队设计实现,参考请注明出处? */ IOHttpClientAdapter buildHttpdnsHttpClientAdapter() { @@ -43,7 +43,7 @@ void _configureHttpClient(HttpClient client) { client.maxConnectionsPerHost = 8; } -// 配置基于 HTTPDNS 的连接工厂 +// 配置基于 HTTPDNS 的连接工? void _configureConnectionFactory(HttpClient client) { client .connectionFactory = (Uri uri, String? proxyHost, int? proxyPort) async { @@ -86,10 +86,10 @@ void _configureConnectionFactory(HttpClient client) { }; } -// 通过 HTTPDNS 解析目标 IP 列表;IPv4 优先;失败则返回空列表(上层回退系统 DNS) +// 通过 HTTPDNS 解析目标 IP 列表;IPv4 优先;失败则返回空列表(上层回退系统 DNS? Future> _resolveTargets(String domain) async { try { - final res = await AliyunHttpdns.resolveHostSyncNonBlocking( + final res = await TrustAPPHttpdns.resolveHostSyncNonBlocking( domain, ipType: 'both', ); diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/lib/aliyun_httpdns.dart b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/lib/aliyun_httpdns.dart index bd4070e..e74eb8c 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/lib/aliyun_httpdns.dart +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/lib/aliyun_httpdns.dart @@ -1,11 +1,11 @@ -import 'dart:async'; +import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/services.dart'; -class AliyunHttpdns { - static const MethodChannel _channel = MethodChannel('aliyun_httpdns'); +class TrustAPPHttpdns { + static const MethodChannel _channel = MethodChannel('TrustAPP_httpdns'); /// New API only: /// appId + primary/backup service host + optional sign secret. @@ -156,20 +156,20 @@ class AliyunHttpdns { await _channel.invokeMethod('cleanAllHostCache'); } - static AliyunHttpdnsHttpAdapter createHttpAdapter({ - AliyunHttpdnsAdapterOptions options = const AliyunHttpdnsAdapterOptions(), + static TrustAPPHttpdnsHttpAdapter createHttpAdapter({ + TrustAPPHttpdnsAdapterOptions options = const TrustAPPHttpdnsAdapterOptions(), }) { - return AliyunHttpdnsHttpAdapter._(options); + return TrustAPPHttpdnsHttpAdapter._(options); } } -class AliyunHttpdnsAdapterOptions { +class TrustAPPHttpdnsAdapterOptions { final String ipType; final int connectTimeoutMs; final int readTimeoutMs; final bool allowInsecureCertificatesForDebugOnly; - const AliyunHttpdnsAdapterOptions({ + const TrustAPPHttpdnsAdapterOptions({ this.ipType = 'auto', this.connectTimeoutMs = 3000, this.readTimeoutMs = 5000, @@ -177,13 +177,13 @@ class AliyunHttpdnsAdapterOptions { }); } -class AliyunHttpdnsRequestResult { +class TrustAPPHttpdnsRequestResult { final int statusCode; final Map> headers; final Uint8List body; final String usedIp; - const AliyunHttpdnsRequestResult({ + const TrustAPPHttpdnsRequestResult({ required this.statusCode, required this.headers, required this.body, @@ -191,17 +191,17 @@ class AliyunHttpdnsRequestResult { }); } -class AliyunHttpdnsHttpAdapter { - final AliyunHttpdnsAdapterOptions _options; +class TrustAPPHttpdnsHttpAdapter { + final TrustAPPHttpdnsAdapterOptions _options; - AliyunHttpdnsHttpAdapter._(this._options); + TrustAPPHttpdnsHttpAdapter._(this._options); /// Fixed behavior: /// 1) resolve host by HTTPDNS /// 2) connect to IP:443 /// 3) keep HTTP Host as original domain /// 4) no fallback to domain connect - Future request( + Future request( Uri uri, { String method = 'GET', Map? headers, @@ -214,7 +214,7 @@ class AliyunHttpdnsHttpAdapter { throw const HttpException('TLS_EMPTY_SNI_FAILED: only https is supported'); } - final Map> resolved = await AliyunHttpdns.resolveHostSyncNonBlocking( + final Map> resolved = await TrustAPPHttpdns.resolveHostSyncNonBlocking( uri.host, ipType: _options.ipType, ); @@ -264,7 +264,7 @@ class AliyunHttpdnsHttpAdapter { resp.headers.forEach((String name, List values) { responseHeaders[name] = values; }); - return AliyunHttpdnsRequestResult( + return TrustAPPHttpdnsRequestResult( statusCode: resp.statusCode, headers: responseHeaders, body: Uint8List.fromList(payload), diff --git a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/pubspec.yaml b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/pubspec.yaml index aa781b3..b1c37b1 100644 --- a/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/pubspec.yaml +++ b/EdgeHttpDNS/sdk/flutter/aliyun_httpdns/pubspec.yaml @@ -54,7 +54,7 @@ flutter: # To add custom fonts to your plugin package, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a - # list giving the asset and other descriptors for the font. For + # "list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/AlicloudHttpDNS.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/AlicloudHttpDNS.h index 84c3efd..22fd045 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/AlicloudHttpDNS.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/AlicloudHttpDNS.h @@ -19,12 +19,12 @@ #import -#import -#import -#import -#import -#import -#import -#import -#import -#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsInternalConstant.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsInternalConstant.h index 4cc2f42..00a65d1 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsInternalConstant.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsInternalConstant.h @@ -1,9 +1,9 @@ // // HttpdnsInternalConstant.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2025/03/10. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #ifndef HTTPDNS_INTERNAL_CONSTANT_H @@ -19,42 +19,42 @@ static const int HTTPDNS_DEFAULT_REQUEST_TIMEOUT_INTERVAL = 3; static const NSUInteger HTTPDNS_DEFAULT_AUTH_TIMEOUT_INTERVAL = 10 * 60; -static NSString *const ALICLOUD_HTTPDNS_VALID_SERVER_CERTIFICATE_IP = @"203.107.1.1"; +static NSString *const Trust_HTTPDNS_VALID_SERVER_CERTIFICATE_IP = @"203.107.1.1"; -// 在iOS14和iOS16,网络信息的获取权限受到越来越紧的限制 +// 在iOS14和iOS16,网络信息的获取权限受到越来越紧的限? // 除非用户主动声明需要相关entitlement,不然只能拿到空信息 -// 考虑大多数用户并不会申请这些权限,我们放弃针对细节的网络信息做缓存粒度隔离 -// 出于兼容性考虑,网络运营商只有default一种类型 +// 考虑大多数用户并不会申请这些权限,我们放弃针对细节的网络信息做缓存粒度隔? +// 出于兼容性考虑,网络运营商只有default一种类? #define HTTPDNS_DEFAULT_NETWORK_CARRIER_NAME @"default" // 调度地址示例:http://106.11.90.200/sc/httpdns_config?account_id=153519&platform=ios&sdk_version=1.6.1 -static NSString *const ALICLOUD_HTTPDNS_SCHEDULE_CENTER_REQUEST_HOST = @"httpdns-sc.aliyuncs.com"; +static NSString *const Trust_HTTPDNS_SCHEDULE_CENTER_REQUEST_HOST = @"httpdns-sc.TrustAPPcs.com"; -static NSString *const ALICLOUD_HTTPDNS_ERROR_MESSAGE_KEY = @"ErrorMessage"; +static NSString *const Trust_HTTPDNS_ERROR_MESSAGE_KEY = @"ErrorMessage"; -static NSString *const kAlicloudHttpdnsRegionConfigV4HostKey = @"service_ip"; -static NSString *const kAlicloudHttpdnsRegionConfigV6HostKey = @"service_ipv6"; +static NSString *const kTrustHttpdnsRegionConfigV4HostKey = @"service_ip"; +static NSString *const kTrustHttpdnsRegionConfigV6HostKey = @"service_ipv6"; -static NSString *const kAlicloudHttpdnsRegionKey = @"HttpdnsRegion"; +static NSString *const kTrustHttpdnsRegionKey = @"HttpdnsRegion"; #define SECONDS_OF_ONE_YEAR 365 * 24 * 60 * 60 -static NSString *const ALICLOUD_HTTPDNS_ERROR_DOMAIN = @"HttpdnsErrorDomain"; +static NSString *const Trust_HTTPDNS_ERROR_DOMAIN = @"HttpdnsErrorDomain"; -static NSInteger const ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE = 10003; -static NSInteger const ALICLOUD_HTTPDNS_HTTP_COMMON_ERROR_CODE = 10004; +static NSInteger const Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE = 10003; +static NSInteger const Trust_HTTPDNS_HTTP_COMMON_ERROR_CODE = 10004; -static NSInteger const ALICLOUD_HTTPDNS_HTTPS_TIMEOUT_ERROR_CODE = 10005; -static NSInteger const ALICLOUD_HTTPDNS_HTTP_TIMEOUT_ERROR_CODE = 10006; -static NSInteger const ALICLOUD_HTTPDNS_HTTP_OPEN_STREAM_ERROR_CODE = 10007; -static NSInteger const ALICLOUD_HTTPDNS_HTTPS_NO_DATA_ERROR_CODE = 10008; +static NSInteger const Trust_HTTPDNS_HTTPS_TIMEOUT_ERROR_CODE = 10005; +static NSInteger const Trust_HTTPDNS_HTTP_TIMEOUT_ERROR_CODE = 10006; +static NSInteger const Trust_HTTPDNS_HTTP_OPEN_STREAM_ERROR_CODE = 10007; +static NSInteger const Trust_HTTPDNS_HTTPS_NO_DATA_ERROR_CODE = 10008; -static NSInteger const ALICLOUD_HTTP_UNSUPPORTED_STATUS_CODE = 10013; -static NSInteger const ALICLOUD_HTTP_PARSE_JSON_FAILED = 10014; +static NSInteger const Trust_HTTP_UNSUPPORTED_STATUS_CODE = 10013; +static NSInteger const Trust_HTTP_PARSE_JSON_FAILED = 10014; -// 加密错误码 -static NSInteger const ALICLOUD_HTTPDNS_ENCRYPT_INVALID_PARAMS_ERROR_CODE = 10021; -static NSInteger const ALICLOUD_HTTPDNS_ENCRYPT_RANDOM_IV_ERROR_CODE = 10022; -static NSInteger const ALICLOUD_HTTPDNS_ENCRYPT_FAILED_ERROR_CODE = 10023; +// 加密错误? +static NSInteger const Trust_HTTPDNS_ENCRYPT_INVALID_PARAMS_ERROR_CODE = 10021; +static NSInteger const Trust_HTTPDNS_ENCRYPT_RANDOM_IV_ERROR_CODE = 10022; +static NSInteger const Trust_HTTPDNS_ENCRYPT_FAILED_ERROR_CODE = 10023; #endif diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsPublicConstant.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsPublicConstant.h index e7be431..8edf925 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsPublicConstant.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsPublicConstant.h @@ -1,9 +1,9 @@ // // HttpdnsPublicConstant.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/6/16. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #ifndef PublicConstant_h @@ -11,11 +11,11 @@ static NSString *const HTTPDNS_IOS_SDK_VERSION = @"1.0.0"; -#define ALICLOUD_HTTPDNS_DEFAULT_REGION_KEY @"cn" -#define ALICLOUD_HTTPDNS_HONGKONG_REGION_KEY @"hk" -#define ALICLOUD_HTTPDNS_SINGAPORE_REGION_KEY @"sg" -#define ALICLOUD_HTTPDNS_GERMANY_REGION_KEY @"de" -#define ALICLOUD_HTTPDNS_AMERICA_REGION_KEY @"us" +#define Trust_HTTPDNS_DEFAULT_REGION_KEY @"cn" +#define Trust_HTTPDNS_HONGKONG_REGION_KEY @"hk" +#define Trust_HTTPDNS_SINGAPORE_REGION_KEY @"sg" +#define Trust_HTTPDNS_GERMANY_REGION_KEY @"de" +#define Trust_HTTPDNS_AMERICA_REGION_KEY @"us" #endif /* PublicConstant_h */ diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.h index dd4b82d..a200d5f 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.h @@ -1,9 +1,9 @@ // // HttpdnsRegionConfigLoader.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/6/16. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.m index 43e6d05..32cf311 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Config/HttpdnsRegionConfigLoader.m @@ -1,20 +1,20 @@ // // HttpdnsRegionConfigLoader.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/6/16. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import "HttpdnsRegionConfigLoader.h" #import "HttpdnsPublicConstant.h" -static NSString *const kServiceV4Key = @"ALICLOUD_HTTPDNS_SERVICE_HOST_V4_KEY"; -static NSString *const kUpdateV4FallbackHostKey = @"ALICLOUD_HTTPDNS_UPDATE_HOST_V4_KEY"; -static NSString *const kServiceV6Key = @"ALICLOUD_HTTPDNS_SERVICE_HOST_V6_KEY"; -static NSString *const kUpdateV6FallbackHostKey = @"ALICLOUD_HTTPDNS_UPDATE_HOST_V6_KEY"; +static NSString *const kServiceV4Key = @"Trust_HTTPDNS_SERVICE_HOST_V4_KEY"; +static NSString *const kUpdateV4FallbackHostKey = @"Trust_HTTPDNS_UPDATE_HOST_V4_KEY"; +static NSString *const kServiceV6Key = @"Trust_HTTPDNS_SERVICE_HOST_V6_KEY"; +static NSString *const kUpdateV6FallbackHostKey = @"Trust_HTTPDNS_UPDATE_HOST_V6_KEY"; -static NSArray *ALICLOUD_HTTPDNS_AVAILABLE_REGION_LIST = nil; +static NSArray *Trust_HTTPDNS_AVAILABLE_REGION_LIST = nil; @interface HttpdnsRegionConfigLoader () @@ -25,12 +25,12 @@ static NSArray *ALICLOUD_HTTPDNS_AVAILABLE_REGION_LIST = nil; @implementation HttpdnsRegionConfigLoader + (void)initialize { - ALICLOUD_HTTPDNS_AVAILABLE_REGION_LIST = @[ - ALICLOUD_HTTPDNS_DEFAULT_REGION_KEY, - ALICLOUD_HTTPDNS_HONGKONG_REGION_KEY, - ALICLOUD_HTTPDNS_SINGAPORE_REGION_KEY, - ALICLOUD_HTTPDNS_GERMANY_REGION_KEY, - ALICLOUD_HTTPDNS_AMERICA_REGION_KEY + Trust_HTTPDNS_AVAILABLE_REGION_LIST = @[ + Trust_HTTPDNS_DEFAULT_REGION_KEY, + Trust_HTTPDNS_HONGKONG_REGION_KEY, + Trust_HTTPDNS_SINGAPORE_REGION_KEY, + Trust_HTTPDNS_GERMANY_REGION_KEY, + Trust_HTTPDNS_AMERICA_REGION_KEY ]; } @@ -51,40 +51,40 @@ static NSArray *ALICLOUD_HTTPDNS_AVAILABLE_REGION_LIST = nil; } + (NSArray *)getAvailableRegionList { - return ALICLOUD_HTTPDNS_AVAILABLE_REGION_LIST; + return Trust_HTTPDNS_AVAILABLE_REGION_LIST; } - (void)loadRegionConfig { self.regionConfig = @{ - ALICLOUD_HTTPDNS_DEFAULT_REGION_KEY: @{ + Trust_HTTPDNS_DEFAULT_REGION_KEY: @{ kServiceV4Key: @[@"203.107.1.1", @"203.107.1.97", @"203.107.1.100", @"203.119.238.240", @"106.11.25.239", @"59.82.99.47"], - kUpdateV4FallbackHostKey: @[@"resolvers-cn.httpdns.aliyuncs.com"], + kUpdateV4FallbackHostKey: @[@"resolvers-cn.httpdns.TrustAPPcs.com"], kServiceV6Key: @[@"2401:b180:7001::31d", @"2401:b180:2000:30::1c", @"2401:b180:2000:20::10", @"2401:b180:2000:30::1c"], - kUpdateV6FallbackHostKey: @[@"resolvers-cn.httpdns.aliyuncs.com"] + kUpdateV6FallbackHostKey: @[@"resolvers-cn.httpdns.TrustAPPcs.com"] }, - ALICLOUD_HTTPDNS_HONGKONG_REGION_KEY: @{ + Trust_HTTPDNS_HONGKONG_REGION_KEY: @{ kServiceV4Key: @[@"47.56.234.194", @"47.56.119.115"], - kUpdateV4FallbackHostKey: @[@"resolvers-hk.httpdns.aliyuncs.com"], + kUpdateV4FallbackHostKey: @[@"resolvers-hk.httpdns.TrustAPPcs.com"], kServiceV6Key: @[@"240b:4000:f10::178", @"240b:4000:f10::188"], - kUpdateV6FallbackHostKey: @[@"resolvers-hk.httpdns.aliyuncs.com"] + kUpdateV6FallbackHostKey: @[@"resolvers-hk.httpdns.TrustAPPcs.com"] }, - ALICLOUD_HTTPDNS_SINGAPORE_REGION_KEY: @{ + Trust_HTTPDNS_SINGAPORE_REGION_KEY: @{ kServiceV4Key: @[@"161.117.200.122", @"47.74.222.190"], - kUpdateV4FallbackHostKey: @[@"resolvers-sg.httpdns.aliyuncs.com"], + kUpdateV4FallbackHostKey: @[@"resolvers-sg.httpdns.TrustAPPcs.com"], kServiceV6Key: @[@"240b:4000:f10::178", @"240b:4000:f10::188"], - kUpdateV6FallbackHostKey: @[@"resolvers-sg.httpdns.aliyuncs.com"] + kUpdateV6FallbackHostKey: @[@"resolvers-sg.httpdns.TrustAPPcs.com"] }, - ALICLOUD_HTTPDNS_GERMANY_REGION_KEY: @{ + Trust_HTTPDNS_GERMANY_REGION_KEY: @{ kServiceV4Key: @[@"47.89.80.182", @"47.246.146.77"], - kUpdateV4FallbackHostKey: @[@"resolvers-de.httpdns.aliyuncs.com"], + kUpdateV4FallbackHostKey: @[@"resolvers-de.httpdns.TrustAPPcs.com"], kServiceV6Key: @[@"2404:2280:3000::176", @"2404:2280:3000::188"], - kUpdateV6FallbackHostKey: @[@"resolvers-de.httpdns.aliyuncs.com"] + kUpdateV6FallbackHostKey: @[@"resolvers-de.httpdns.TrustAPPcs.com"] }, - ALICLOUD_HTTPDNS_AMERICA_REGION_KEY: @{ + Trust_HTTPDNS_AMERICA_REGION_KEY: @{ kServiceV4Key: @[@"47.246.131.175", @"47.246.131.141"], - kUpdateV4FallbackHostKey: @[@"resolvers-us.httpdns.aliyuncs.com"], + kUpdateV4FallbackHostKey: @[@"resolvers-us.httpdns.TrustAPPcs.com"], kServiceV6Key: @[@"2404:2280:4000::2bb", @"2404:2280:4000::23e"], - kUpdateV6FallbackHostKey: @[@"resolvers-us.httpdns.aliyuncs.com"] + kUpdateV6FallbackHostKey: @[@"resolvers-us.httpdns.TrustAPPcs.com"] } }; } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.h index 98a8d57..0761773 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.h @@ -1,4 +1,4 @@ -#import +#import NS_ASSUME_NONNULL_BEGIN diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.m index 8b8accd..505a249 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsEdgeService.m @@ -1,4 +1,4 @@ -#import "HttpdnsEdgeService.h" +#import "HttpdnsEdgeService.h" #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.h index 620ac43..1ca0461 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.h @@ -1,9 +1,9 @@ // // HttpdnsLocalResolver.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2025/3/16. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.m index 009878e..0a23e32 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsLocalResolver.m @@ -1,9 +1,9 @@ // // HttpdnsLocalResolver.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2025/3/16. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import "HttpdnsLocalResolver.h" @@ -34,7 +34,7 @@ struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; // 同时支持IPv4和IPv6 - hints.ai_socktype = SOCK_STREAM; // TCP (对DNS解析来说通常不重要) + hints.ai_socktype = SOCK_STREAM; // TCP (对DNS解析来说通常不重? // 3. 执行getaddrinfo解析 struct addrinfo *res = NULL; @@ -105,7 +105,7 @@ for (NSString *ipStr in ipv4Array) { HttpdnsIpObject *ipObj = [[HttpdnsIpObject alloc] init]; [ipObj setIp:ipStr]; // ipObj.ip = ipStr - // connectedRT默认为0 + // connectedRT默认? [v4IpObjects addObject:ipObj]; } } @@ -123,17 +123,17 @@ [hostObject setV4Ips:v4IpObjects]; [hostObject setV6Ips:v6IpObjects]; - // IPv4和IPv6的默认TTL为60秒 + // IPv4和IPv6的默认TTL?0? [hostObject setV4TTL:60]; [hostObject setV6TTL:60]; // 自定义ttl [HttpdnsUtil processCustomTTL:hostObject forHost:host service:service]; - // 当前时间(自1970年以来的秒数) + // 当前时间(?970年以来的秒数) int64_t now = (int64_t)[[NSDate date] timeIntervalSince1970]; - // 更新最后查询时间 + // 更新最后查询时? [hostObject setLastIPv4LookupTime:now]; [hostObject setLastIPv6LookupTime:now]; @@ -141,8 +141,8 @@ [hostObject setHasNoIpv4Record:(v4IpObjects.count == 0)]; [hostObject setHasNoIpv6Record:(v6IpObjects.count == 0)]; - // 如果需要,可以在这里设置clientIp或额外字段 - // 现在保留为默认值/空 + // 如果需要,可以在这里设置clientIp或额外字? + // 现在保留为默认?? return hostObject; } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRemoteResolver.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRemoteResolver.m index e6d460b..9ee6850 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRemoteResolver.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRemoteResolver.m @@ -59,7 +59,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; + (void)initialize { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - _streamOperateSyncQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.runloopOperateQueue.HttpdnsRequest", DISPATCH_QUEUE_SERIAL); + _streamOperateSyncQueue = dispatch_queue_create("com.Trust.sdk.httpdns.runloopOperateQueue.HttpdnsRequest", DISPATCH_QUEUE_SERIAL); }); } @@ -83,7 +83,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return nil; } - // 验证响应码 + // 验证响应? if (![self validateResponseCode:json]) { return nil; } @@ -94,7 +94,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return nil; } - // 获取所有答案 + // 获取所有答? NSArray *answers = [self getAnswersFromData:data]; if (!answers) { return nil; @@ -112,7 +112,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return hostObjects; } -// 验证响应码 +// 验证响应? - (BOOL)validateResponseCode:(NSDictionary *)json { NSString *code = [json objectForKey:@"code"]; if (![code isEqualToString:@"success"]) { @@ -122,17 +122,17 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return YES; } -// 获取并处理解密数据内容 +// 获取并处理解密数据内? - (id)extractDataContent:(NSDictionary *)json { - // 获取mode,判断是否需要解密 + // 获取mode,判断是否需要解? NSInteger mode = [[json objectForKey:@"mode"] integerValue]; id data = [json objectForKey:@"data"]; if (mode == 1) { // 只处理AES-CBC模式 - // 需要解密 + // 需要解? data = [self decryptData:data withMode:mode]; } else if (mode != 0) { - // 不支持的加密模式(如AES-GCM) + // 不支持的加密模式(如AES-GCM? HttpdnsLogDebug("Unsupported encryption mode: %ld", (long)mode); return nil; } @@ -174,7 +174,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return nil; } - // 使用工具类解密 + // 使用工具类解? NSError *decryptError = nil; NSData *decryptedData = [HttpdnsUtil decryptDataAESCBC:encryptedData withKey:keyData error:&decryptError]; @@ -183,7 +183,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return nil; } - // 将解密后的JSON数据解析为字典 + // 将解密后的JSON数据解析为字? NSError *jsonError; id decodedData = [NSJSONSerialization JSONObjectWithData:decryptedData options:0 error:&jsonError]; @@ -205,7 +205,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return answers; } -// 从答案创建主机对象 +// 从答案创建主机对? - (HttpdnsHostObject *)createHostObjectFromAnswer:(NSDictionary *)answer { // 获取域名 NSString *host = [answer objectForKey:@"dn"]; @@ -251,7 +251,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; // 设置IPv4的TTL [self setTTLForHostObject:hostObject fromData:v4Data forIPv6:NO]; - // 处理v4的extra字段,优先使用 + // 处理v4的extra字段,优先使? [self processExtraInfo:v4Data forHostObject:hostObject]; // 检查是否有no_ip_code字段,表示无IPv4记录 @@ -259,7 +259,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; hostObject.hasNoIpv4Record = YES; } } else { - // 没有IPv4地址但有v4节点,可能是无记录 + // 没有IPv4地址但有v4节点,可能是无记? hostObject.hasNoIpv4Record = YES; } } @@ -289,12 +289,12 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; hostObject.hasNoIpv6Record = YES; } } else { - // 没有IPv6地址但有v6节点,可能是无记录 + // 没有IPv6地址但有v6节点,可能是无记? hostObject.hasNoIpv6Record = YES; } } -// 设置IP数组到主机对象 +// 设置IP数组到主机对? - (void)setIpArrayToHostObject:(HttpdnsHostObject *)hostObject fromIpsArray:(NSArray *)ips forIPv6:(BOOL)isIPv6 { NSMutableArray *ipArray = [NSMutableArray array]; for (NSString *ip in ips) { @@ -352,7 +352,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return nil; } - // 准备签名和加密参数 + // 准备签名和加密参? NSDictionary *paramsToSign = [self prepareSigningParams:request forEncryption:[self shouldUseEncryption]]; // 计算签名 @@ -380,7 +380,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return isV4 ? [scheduleCenter currentActiveServiceServerV4Host] : [scheduleCenter currentActiveServiceServerV6Host]; } -// 检查是否应该使用加密 +// 检查是否应该使用加? - (BOOL)shouldUseEncryption { HttpDnsService *service = self.service ?: [HttpDnsService sharedInstance]; return [HttpdnsUtil isNotEmptyString:service.aesSecretKey]; @@ -391,13 +391,13 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; HttpDnsService *service = self.service ?: [HttpDnsService sharedInstance]; NSInteger accountId = service.accountID; - // 构建参与签名的参数字典 + // 构建参与签名的参数字? NSMutableDictionary *paramsToSign = [NSMutableDictionary dictionary]; // 构建需要加密的参数字典 NSMutableDictionary *paramsToEncrypt = [NSMutableDictionary dictionary]; - // 账号ID,参与签名但不加密 + // 账号ID,参与签名但不加? [paramsToSign setObject:[NSString stringWithFormat:@"%ld", accountId] forKey:@"id"]; // 决定加密模式 @@ -416,7 +416,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; // SDNS参数,参与签名并加密 [self addSdnsParams:request.sdnsParams toParams:paramsToEncrypt]; - // 签名过期时间,参与签名但不加密 + // 签名过期时间,参与签名但不加? long expiredTimestamp = [self calculateExpiredTimestamp]; NSString *expiredTimestampString = [NSString stringWithFormat:@"%ld", expiredTimestamp]; [paramsToSign setObject:expiredTimestampString forKey:@"exp"]; @@ -435,7 +435,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return paramsToSign; } -// 获取查询类型字符串 +// 获取查询类型字符? - (NSString *)getQueryTypeString:(HttpdnsQueryIPType)queryIpType { if ((queryIpType & HttpdnsQueryIPTypeIpv4) && (queryIpType & HttpdnsQueryIPTypeIpv6)) { return @"4,6"; @@ -455,7 +455,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; } } -// 计算过期时间戳 +// 计算过期时间? - (long)calculateExpiredTimestamp { HttpDnsService *service = self.service ?: [HttpDnsService sharedInstance]; long localTimestampOffset = (long)service.authTimeOffset; @@ -510,7 +510,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; [signParts addObject:[NSString stringWithFormat:@"%@=%@", key, [params objectForKey:key]]]; } - // 组合签名字符串 + // 组合签名字符? NSString *signContent = [signParts componentsJoinedByString:@"&"]; // 计算HMAC-SHA256签名 @@ -538,7 +538,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; // 加密模式下,添加enc参数 [finalUrl appendFormat:@"&enc=%@", [params objectForKey:@"enc"]]; } else { - // 明文模式下,添加所有参数 + // 明文模式下,添加所有参? NSMutableDictionary *paramsForPlainText = [NSMutableDictionary dictionaryWithDictionary:params]; [paramsForPlainText removeObjectForKey:@"id"]; [paramsForPlainText removeObjectForKey:@"m"]; @@ -557,7 +557,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; } } - // 添加签名(如果有) + // 添加签名(如果有? if ([HttpdnsUtil isNotEmptyString:signature]) { [finalUrl appendFormat:@"&s=%@", signature]; } @@ -568,7 +568,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; return finalUrl; } -// 添加额外的不参与签名的参数 +// 添加额外的不参与签名的参? - (void)appendAdditionalParams:(NSMutableString *)url { // sessionId NSString *sessionId = [HttpdnsUtil generateSessionID]; @@ -594,7 +594,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; if (!service) { HttpdnsLogDebug("Missing service for accountId: %ld; ensure request.accountId is set and service initialized", (long)request.accountId); if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"HttpDnsService not found for accountId"}]; + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"HttpDnsService not found for accountId"}]; } return nil; } @@ -612,7 +612,7 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; @try { HttpdnsIPStackType stackType = [[HttpdnsIpStackDetector sharedInstance] currentIpStack]; - // 由于上面默认只用ipv4请求,这里判断如果是ipv6-only环境,那就用v6的ip再试一次 + // 由于上面默认只用ipv4请求,这里判断如果是ipv6-only环境,那就用v6的ip再试一? if (stackType == kHttpdnsIpv6Only) { url = [self constructHttpdnsResolvingUrl:request forV4Net:NO]; HttpdnsLogDebug("lookupHostFromServer by ipv4 server failed, construct ipv6 backup url: %@", url); @@ -631,8 +631,8 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; - (NSArray *)sendRequest:(NSString *)urlStr queryIpType:(HttpdnsQueryIPType)queryIpType error:(NSError **)error { if (![HttpdnsUtil isNotEmptyString:urlStr]) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Empty resolve URL due to missing scheduler"}]; } return nil; @@ -654,8 +654,8 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; if (httpResponse.statusCode != 200) { if (error) { NSString *errorMessage = [NSString stringWithFormat:@"Unsupported http status code: %ld", (long)httpResponse.statusCode]; - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_UNSUPPORTED_STATUS_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_UNSUPPORTED_STATUS_CODE userInfo:@{NSLocalizedDescriptionKey: errorMessage}]; } return nil; @@ -673,8 +673,8 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; NSDictionary *json = [HttpdnsUtil getValidDictionaryFromJson:jsonValue]; if (!json) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Failed to parse JSON response"}]; } return nil; @@ -691,10 +691,10 @@ static dispatch_queue_t _streamOperateSyncQueue = 0; } if ([extra isKindOfClass:[NSString class]]) { - // 已经是字符串,直接返回 + // 已经是字符串,直接返? return extra; } else { - // 非字符串,尝试转换为JSON字符串 + // 非字符串,尝试转换为JSON字符? NSError *error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:extra options:0 error:&error]; if (!error && jsonData) { diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRequestManager.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRequestManager.m index 5d73851..592bd29 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRequestManager.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsRequestManager.m @@ -71,8 +71,8 @@ typedef struct { + (void)initialize { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - _persistentCacheConcurrentQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.persistentCacheOperationQueue", DISPATCH_QUEUE_CONCURRENT); - _asyncResolveHostQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.asyncResolveHostQueue", DISPATCH_QUEUE_CONCURRENT); + _persistentCacheConcurrentQueue = dispatch_queue_create("com.Trust.sdk.httpdns.persistentCacheOperationQueue", DISPATCH_QUEUE_CONCURRENT); + _asyncResolveHostQueue = dispatch_queue_create("com.Trust.sdk.httpdns.asyncResolveHostQueue", DISPATCH_QUEUE_CONCURRENT); }); } @@ -113,7 +113,7 @@ typedef struct { // 先清理过期时间超过阈值的缓存结果 [self->_httpdnsDB cleanRecordAlreadExpiredAt:[[NSDate date] timeIntervalSince1970] - duration]; - // 再读取持久化缓存中的历史记录,加载到内存缓存里 + // 再读取持久化缓存中的历史记录,加载到内存缓存? [self loadCacheFromDbToMemory]; }); } @@ -139,7 +139,7 @@ typedef struct { return; } - // 分批处理,每批最多5个域名 + // 分批处理,每批最?个域? NSUInteger totalCount = hosts.count; for (NSUInteger i = 0; i < totalCount; i += HTTPDNS_PRE_RESOLVE_BATCH_SIZE) { NSUInteger length = MIN(HTTPDNS_PRE_RESOLVE_BATCH_SIZE, totalCount - i); @@ -190,21 +190,21 @@ typedef struct { if (isCachedResultUsable) { if (isResolvingRequired) { // 缓存结果可用,但是需要请求,因为缓存结果已经过期 - // 这种情况异步去解析就可以了 + // 这种情况异步去解析就可以? [self determineResolvingHostNonBlocking:request]; } // 缓存是以cacheKey为准,这里返回前,要把host替换成用户请求的这个 result.hostName = host; HttpdnsLogDebug("Reuse available cache for cacheKey: %@, result: %@", cacheKey, result); - // 因为缓存结果可用,可以立即返回 + // 因为缓存结果可用,可以立即返? return result; } if (request.isBlockingRequest) { - // 缓存结果不可用,且是同步请求,需要等待结果 + // 缓存结果不可用,且是同步请求,需要等待结? return [self determineResolveHostBlocking:request]; } else { - // 缓存结果不可用,且是异步请求,不需要等待结果 + // 缓存结果不可用,且是异步请求,不需要等待结? [self determineResolvingHostNonBlocking:request]; return nil; } @@ -264,14 +264,14 @@ typedef struct { if ([hostObject isExpiredUnderQueryIpType:queryType]) { if (self.atomicExpiredIPEnabled || [hostObject isLoadFromDB]) { - // 只有开启了允许过期缓存,和开启持久化缓存情况下启动后加载到内存中的缓存,才可以直接复用过期结果 + // 只有开启了允许过期缓存,和开启持久化缓存情况下启动后加载到内存中的缓存,才可以直接复用过期结? HttpdnsLogDebug("The ips is expired, but we accept it, host: %@, queryType: %ld, expiredIpEnabled: %d, isLoadFromDB: %d", hostObject.hostName, queryType, self.atomicExpiredIPEnabled, [hostObject isLoadFromDB]); - // 复用过期结果,同时也需要发起新的解析请求 + // 复用过期结果,同时也需要发起新的解析请? return (HostObjectExamingResult){YES, YES}; } - // 只要过期了就肯定需要请求 + // 只要过期了就肯定需要请? return (HostObjectExamingResult){NO, YES}; } @@ -310,7 +310,7 @@ typedef struct { return nil; } - // 这个路径里,host只会有一个,所以直接取第一个处理就行 + // 这个路径里,host只会有一个,所以直接取第一个处理就? result = resultArray.firstObject; } else { if (!self.degradeToLocalDNSEnabled) { @@ -332,7 +332,7 @@ typedef struct { // merge之后,返回的应当是存储在缓存中的实际对象,而非请求过程中构造出来的对象 HttpdnsHostObject *lookupResult = [self mergeLookupResultToManager:result host:host cacheKey:cacheKey underQueryIpType:queryIPType]; - // 返回一个快照,避免进行中的一些缓存调整影响返回去的结果 + // 返回一个快照,避免进行中的一些缓存调整影响返回去的结? return [lookupResult copy]; } @@ -483,7 +483,7 @@ typedef struct { HttpdnsNetworkStatus currentStatus = [[HttpdnsReachability sharedInstance] currentReachabilityStatus]; NSString *currentStatusString = [[HttpdnsReachability sharedInstance] currentReachabilityString]; - // 重新检测协议栈代价小,所以只要网络切换就发起检测 + // 重新检测协议栈代价小,所以只要网络切换就发起检? // 但考虑到网络切换后不稳定,还是延迟1秒才发起 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{ [[HttpdnsIpStackDetector sharedInstance] redetectIpStack]; @@ -493,23 +493,23 @@ typedef struct { BOOL statusChanged = (_lastNetworkStatus != currentStatus); // 仅在以下情况下响应网络变化去尝试更新缓存: - // - 距离上次处理事件至少过去了较长时间,或 - // - 网络状态发生变化且至少过去了较短时间 + // - 距离上次处理事件至少过去了较长时间,? + // - 网络状态发生变化且至少过去了较短时? NSTimeInterval elapsedTime = currentTimestamp - _lastUpdateTimestamp; if (elapsedTime >= 5 || (statusChanged && elapsedTime >= 1)) { HttpdnsLogDebug("Processing network change: oldStatus: %ld, newStatus: %ld(%@), elapsedTime=%.2f seconds", _lastNetworkStatus, currentStatus, currentStatusString, elapsedTime); // 更新调度 - // 网络在切换过程中可能不稳定,所以发送请求前等待2秒 + // 网络在切换过程中可能不稳定,所以发送请求前等待2? dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{ HttpdnsScheduleCenter *scheduleCenter = self.ownerService.scheduleCenter; [scheduleCenter asyncUpdateRegionScheduleConfig]; }); // 复杂逻辑(仅注释关键点,避免冗余): - // 网络切换后只预解析“cacheKey 等于 hostName”的条目, - // 这些条目代表标准域名缓存;SDNS 等使用自定义 cacheKey 的记录不在此批次处理。 + // 网络切换后只预解析“cacheKey 等于 hostName”的条目? + // 这些条目代表标准域名缓存;SDNS 等使用自定义 cacheKey 的记录不在此批次处理? NSArray *allKeys = [_hostObjectInMemoryCache allCacheKeys]; NSMutableArray *hostArray = [NSMutableArray array]; for (NSString *key in allKeys) { @@ -524,10 +524,10 @@ typedef struct { } } - // 预解析 - // 网络在切换过程中可能不稳定,所以在清理缓存和发送请求前等待3秒 + // 预解? + // 网络在切换过程中可能不稳定,所以在清理缓存和发送请求前等待3? dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{ - // 仅清理“hostName 键”的缓存,保留 SDNS 等自定义 cacheKey 的记录 + // 仅清理“hostName 键”的缓存,保?SDNS 等自定义 cacheKey 的记? for (NSString *host in hostArray) { [self->_hostObjectInMemoryCache removeHostObjectByCacheKey:host]; } @@ -538,7 +538,7 @@ typedef struct { } }); - // 更新时间戳和状态 + // 更新时间戳和状? _lastNetworkStatus = currentStatus; _lastUpdateTimestamp = currentTimestamp; } else { @@ -552,7 +552,7 @@ typedef struct { - (dispatch_queue_t)cacheQueue { if (!_cacheQueue) { - _cacheQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.cacheDisableStatusQueue", DISPATCH_QUEUE_SERIAL); + _cacheQueue = dispatch_queue_create("com.Trust.sdk.httpdns.cacheDisableStatusQueue", DISPATCH_QUEUE_SERIAL); } return _cacheQueue; } @@ -573,7 +573,7 @@ typedef struct { HttpdnsHostObject *hostObject = [HttpdnsHostObject fromDBRecord:hostRecord]; - // 从持久层加载到内存的缓存,需要做个标记,App启动后从缓存使用结果时,根据标记做特殊处理 + // 从持久层加载到内存的缓存,需要做个标记,App启动后从缓存使用结果时,根据标记做特殊处? [hostObject setIsLoadFromDB:YES]; [self->_hostObjectInMemoryCache setHostObject:hostObject forCacheKey:cacheKey]; @@ -596,7 +596,7 @@ typedef struct { } } - // 清空数据库数据 + // 清空数据库数? dispatch_async(_persistentCacheConcurrentQueue, ^{ [self->_httpdnsDB deleteByHostNameArr:hostArray]; }); @@ -605,7 +605,7 @@ typedef struct { - (void)cleanMemoryAndPersistentCacheOfAllHosts { [_hostObjectInMemoryCache removeAllHostObjects]; - // 清空数据库数据 + // 清空数据库数? dispatch_async(_persistentCacheConcurrentQueue, ^{ [self->_httpdnsDB deleteAll]; }); @@ -622,7 +622,7 @@ typedef struct { } #pragma mark - -#pragma mark - 以下函数仅用于测试目的 +#pragma mark - 以下函数仅用于测试目? - (NSString *)showMemoryCache { NSString *cacheDes; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.h index 0397c78..baa47f0 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.h @@ -24,19 +24,19 @@ // #import "HttpdnsDegradationDelegate.h" // #import "HttpdnsLoggerProtocol.h" -#import -#import -#import -#import +#import +#import +#import +#import -#define ALICLOUD_HTTPDNS_DEPRECATED(explain) __attribute__((deprecated(explain))) +#define Trust_HTTPDNS_DEPRECATED(explain) __attribute__((deprecated(explain))) -#ifndef ALICLOUDHDNS_STACK_KEY -#define ALICLOUDHDNS_STACK_KEY +#ifndef TrustHDNS_STACK_KEY +#define TrustHDNS_STACK_KEY -#define ALICLOUDHDNS_IPV4 @"ALICLOUDHDNS_IPV4" -#define ALICLOUDHDNS_IPV6 @"ALICLOUDHDNS_IPV6" +#define TrustHDNS_IPV4 @"TrustHDNS_IPV4" +#define TrustHDNS_IPV6 @"TrustHDNS_IPV6" #endif @@ -50,7 +50,7 @@ NS_ASSUME_NONNULL_BEGIN /// @param host 域名 /// @param ipType 当前查询的IP类型 /// @param ttl 当次域名解析返回的TTL -- (int64_t)httpdnsHost:(NSString * _Nonnull)host ipType:(AlicloudHttpDNS_IPType)ipType ttl:(int64_t)ttl; +- (int64_t)httpdnsHost:(NSString * _Nonnull)host ipType:(TrustHttpDNS_IPType)ipType ttl:(int64_t)ttl; @end @@ -62,154 +62,154 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, copy, readonly, nullable) NSString *aesSecretKey; -@property (nonatomic, weak, setter=setDelegateForDegradationFilter:) id delegate ALICLOUD_HTTPDNS_DEPRECATED("不再建议通过设置此回调实现降级逻辑,而是自行在调用HTTPDNS解析域名前做判断"); +@property (nonatomic, weak, setter=setDelegateForDegradationFilter:) id delegate Trust_HTTPDNS_DEPRECATED("不再建议通过设置此回调实现降级逻辑,而是自行在调用HTTPDNS解析域名前做判断"); @property (nonatomic, weak) id ttlDelegate; + (nonnull instancetype)sharedInstance; -/// 获取指定账号对应的 HttpDnsService 实例 +/// 获取指定账号对应?HttpDnsService 实例 /// @param accountID 账号 ID /// @return 已初始化的实例,若账号尚未注册则返回 nil + (nullable instancetype)getInstanceByAccountId:(NSInteger)accountID; /*! * @brief 无需鉴权功能的初始化接口 - * @details 初始化,设置 HTTPDNS 服务 Account ID。使用本接口初始化,请求将无任何签名保护,请谨慎使用。 - * 您可以从控制台获取您的 Account ID 。 - * 此方法会初始化为单例。 - * 注意:本接口从3.2.1起废弃,后续将进行移除。 + * @details 初始化,设置 HTTPDNS 服务 Account ID。使用本接口初始化,请求将无任何签名保护,请谨慎使用? + * 您可以从控制台获取您?Account ID ? + * 此方法会初始化为单例? + * 注意:本接口?.2.1起废弃,后续将进行移除? * @param accountID 您的 HTTPDNS Account ID */ -- (nonnull instancetype)initWithAccountID:(NSInteger)accountID ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. This method will be removed in the future. Use -[HttpDnsService initWithAccountID:secretKey:] instead."); +- (nonnull instancetype)initWithAccountID:(NSInteger)accountID Trust_HTTPDNS_DEPRECATED("Deprecated. This method will be removed in the future. Use -[HttpDnsService initWithAccountID:secretKey:] instead."); /*! * @brief 启用鉴权功能的初始化接口 - * @details 初始化、开启鉴权功能,并设置 HTTPDNS 服务 Account ID,鉴权功能对应的 secretKey。 - * 您可以从控制台获取您的 Account ID 、secretKey信息。 - * 此方法会初始化为单例。 + * @details 初始化、开启鉴权功能,并设?HTTPDNS 服务 Account ID,鉴权功能对应的 secretKey? + * 您可以从控制台获取您?Account ID 、secretKey信息? + * 此方法会初始化为单例? * @param accountID 您的 HTTPDNS Account ID - * @param secretKey 鉴权对应的 secretKey + * @param secretKey 鉴权对应?secretKey */ - (nonnull instancetype)initWithAccountID:(NSInteger)accountID secretKey:(NSString * _Nonnull)secretKey; /*! - * @brief 启用鉴权功能、加密功能的初始化接口 - * @details 初始化、开启鉴权功能、开启AES加密,并设置 HTTPDNS 服务 Account ID,鉴权功能对应的 secretKey,加密功能对应的 aesSecretKey。 - * 您可以从控制台获取您的 Account ID 、secretKey、aesSecretKey 信息。 - * 此方法会初始化为单例。 + * @brief 启用鉴权功能、加密功能的初始化接? + * @details 初始化、开启鉴权功能、开启AES加密,并设置 HTTPDNS 服务 Account ID,鉴权功能对应的 secretKey,加密功能对应的 aesSecretKey? + * 您可以从控制台获取您?Account ID 、secretKey、aesSecretKey 信息? + * 此方法会初始化为单例? * @param accountID 您的 HTTPDNS Account ID - * @param secretKey 鉴权对应的 secretKey - * @param aesSecretKey 加密功能对应的 aesSecretKey + * @param secretKey 鉴权对应?secretKey + * @param aesSecretKey 加密功能对应?aesSecretKey */ - (nonnull instancetype)initWithAccountID:(NSInteger)accountID secretKey:(NSString * _Nonnull)secretKey aesSecretKey:(NSString * _Nullable)aesSecretKey; -/// 开启鉴权功能后,鉴权的签名计算默认读取设备当前时间。若担心设备时间不准确导致签名不准确,可以使用此接口校正 APP 内鉴权计算使用的时间值 -/// 注意,校正操作在 APP 的一个生命周期内生效,APP 重启后需要重新设置才能重新生效 -/// @param authCurrentTime 用于校正的时间戳,单位为秒 -- (void)setAuthCurrentTime:(NSUInteger)authCurrentTime ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setInternalAuthTimeBaseBySpecifyingCurrentTime:] instead."); +/// 开启鉴权功能后,鉴权的签名计算默认读取设备当前时间。若担心设备时间不准确导致签名不准确,可以使用此接口校正 APP 内鉴权计算使用的时间? +/// 注意,校正操作在 APP 的一个生命周期内生效,APP 重启后需要重新设置才能重新生? +/// @param authCurrentTime 用于校正的时间戳,单位为? +- (void)setAuthCurrentTime:(NSUInteger)authCurrentTime Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setInternalAuthTimeBaseBySpecifyingCurrentTime:] instead."); -/// 开启鉴权功能后,鉴权的签名计算默认读取设备当前时间。若担心设备时间不准确导致签名不准确,可以使用此接口校正 APP 内鉴权计算使用的时间值 -/// 注意,校正操作在 APP 的一个生命周期内生效,APP 重启后需要重新设置才能重新生效 -/// @param currentTime 用于校正的时间戳,单位为秒 +/// 开启鉴权功能后,鉴权的签名计算默认读取设备当前时间。若担心设备时间不准确导致签名不准确,可以使用此接口校正 APP 内鉴权计算使用的时间? +/// 注意,校正操作在 APP 的一个生命周期内生效,APP 重启后需要重新设置才能重新生? +/// @param currentTime 用于校正的时间戳,单位为? - (void)setInternalAuthTimeBaseBySpecifyingCurrentTime:(NSTimeInterval)currentTime; -/// 设置持久化缓存功能 -/// @param enable YES: 开启 NO: 关闭 -- (void)setCachedIPEnabled:(BOOL)enable ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setPersistentCacheIPEnabled:] instead."); +/// 设置持久化缓存功? +/// @param enable YES: 开?NO: 关闭 +- (void)setCachedIPEnabled:(BOOL)enable Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setPersistentCacheIPEnabled:] instead."); -/// 设置持久化缓存功能 +/// 设置持久化缓存功? /// 开启后,每次解析会将结果持久化缓存到本地,当下次应用启动时,可以从本地加载缓存解析结果,提高应用启动时获取解析结果的速度 /// 加载时,会丢弃已经过期的解析结果 -/// @param enable YES: 开启 NO: 关闭 +/// @param enable YES: 开?NO: 关闭 - (void)setPersistentCacheIPEnabled:(BOOL)enable; -/// 设置持久化缓存功能 +/// 设置持久化缓存功? /// 开启后,每次解析会将结果持久化缓存到本地,当下次应用启动时,可以从本地加载缓存解析结果,提高应用启动时获取解析结果的速度 /// 加载时,会丢弃过期时间已经超过指定值的解析结果 -/// @param enable YES: 开启 NO: 关闭 -/// @param duration 决定丢弃IP的过期时间阈值,单位为秒,过期超过这个时间范围的IP会被丢弃,取值范围为0-1年。这个值仅在开启持久化缓存功能时才有意义 +/// @param enable YES: 开?NO: 关闭 +/// @param duration 决定丢弃IP的过期时间阈值,单位为秒,过期超过这个时间范围的IP会被丢弃,取值范围为0-1年。这个值仅在开启持久化缓存功能时才有意? - (void)setPersistentCacheIPEnabled:(BOOL)enable discardRecordsHasExpiredFor:(NSTimeInterval)duration; -/// 是否允许 HTTPDNS 返回 TTL 过期域名的 ip ,建议允许(默认不允许) -/// @param enable YES: 开启 NO: 关闭 -- (void)setExpiredIPEnabled:(BOOL)enable ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setReuseExpiredIPEnabled:] instead."); +/// 是否允许 HTTPDNS 返回 TTL 过期域名?ip ,建议允许(默认不允许) +/// @param enable YES: 开?NO: 关闭 +- (void)setExpiredIPEnabled:(BOOL)enable Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setReuseExpiredIPEnabled:] instead."); -/// 是否允许 HTTPDNS 返回 TTL 过期域名的 ip ,建议允许(默认不允许) -/// @param enable YES: 开启 NO: 关闭 +/// 是否允许 HTTPDNS 返回 TTL 过期域名?ip ,建议允许(默认不允许) +/// @param enable YES: 开?NO: 关闭 - (void)setReuseExpiredIPEnabled:(BOOL)enable; /// 设置 HTTPDNS 域名解析请求类型 ( HTTP / HTTPS ) -/// 若不调用该接口,默认为 HTTP 请求。 -/// HTTP 请求基于底层 CFNetwork 实现,不受 ATS 限制; +/// 若不调用该接口,默认?HTTP 请求? +/// HTTP 请求基于底层 CFNetwork 实现,不?ATS 限制? /// @param enable YES: HTTPS请求 NO: HTTP请求 - (void)setHTTPSRequestEnabled:(BOOL)enable; -/// 声明App是否配置了ATS为AllowsArbitraryLoads,默认认为没有配置 +/// 声明App是否配置了ATS为AllowsArbitraryLoads,默认认为没有配? /// 若做了声明,则当指定走HTTP方式解析域名时,解析链路会走系统NSURLSession逻辑 /// 否则,会走定制的CFHTTP链路,避免被ATS拦截请求 - (void)setHasAllowedArbitraryLoadsInATS:(BOOL)hasAllowedArbitraryLoadsInATS; -/// 设置底层HTTPDNS网络请求超时时间,单位为秒 -/// 需要注意,这个值只决定底层解析请求的网络超时时间,而非同步解析接口、异步解析接口的最长阻塞或者等待时间 +/// 设置底层HTTPDNS网络请求超时时间,单位为? +/// 需要注意,这个值只决定底层解析请求的网络超时时间,而非同步解析接口、异步解析接口的最长阻塞或者等待时? /// 同步解析接口、异步解析接口的最长阻塞或者等待时间,需要调用接口时设置request参数中的`resolveTimeoutInSecond`决定 -/// @param timeoutInterval 超时时间,单位为秒 +/// @param timeoutInterval 超时时间,单位为? - (void)setNetworkingTimeoutInterval:(NSTimeInterval)timeoutInterval; -/// 指定region,指定后会读取该region对应配置作为初始化配置 -/// 一般情况下无需设置,SDK内部会默认路由全球范围内最近的接入点 +/// 指定region,指定后会读取该region对应配置作为初始化配? +/// 一般情况下无需设置,SDK内部会默认路由全球范围内最近的接入? /// @param region 需要指定的region,缺省为中国大陆 - (void)setRegion:(NSString *)region; -/// 域名预解析 (默认解析双栈记录) -/// 通常用于启动后立即向SDK设置您后续可能会使用到的热点域名,以便SDK提前解析,减少后续解析域名时请求的时延 -/// 如果是在运行过程中调用,SDK也会立即解析设置的域名数组中的域名,刷新这些域名的解析结果 +/// 域名预解?(默认解析双栈记录) +/// 通常用于启动后立即向SDK设置您后续可能会使用到的热点域名,以便SDK提前解析,减少后续解析域名时请求的时? +/// 如果是在运行过程中调用,SDK也会立即解析设置的域名数组中的域名,刷新这些域名的解析结? /// -/// @param hosts 预解析列表数组 +/// @param hosts 预解析列表数? - (void)setPreResolveHosts:(NSArray *)hosts; /// 域名预解析,可以指定预解析auto、ipv4、ipv6、both -/// 通常用于启动后立即向SDK设置您后续可能会使用到的热点域名,以便SDK提前解析,减少后续解析域名时请求的时延 -/// 如果是在运行过程中调用,SDK也会立即解析设置的域名数组中的域名,刷新这些域名的解析结果 +/// 通常用于启动后立即向SDK设置您后续可能会使用到的热点域名,以便SDK提前解析,减少后续解析域名时请求的时? +/// 如果是在运行过程中调用,SDK也会立即解析设置的域名数组中的域名,刷新这些域名的解析结? /// -/// @param hosts 预解析列表数组 -/// @param ipType 指定预解析记录类型 +/// @param hosts 预解析列表数? +/// @param ipType 指定预解析记录类? - (void)setPreResolveHosts:(NSArray *)hosts byIPType:(HttpdnsQueryIPType)ipType; -/// 域名预解析 +/// 域名预解? /// @param hosts 域名 /// @param ipType 4: ipv4; 6: ipv6; 64: ipv4+ipv6 -- (void)setPreResolveHosts:(NSArray *)hosts queryIPType:(AlicloudHttpDNS_IPType)ipType ALICLOUD_HTTPDNS_DEPRECATED("Deprecated, this method will be removed in the future. Use -[HttpDnsService setPreResolveHosts:byIPType:] instead."); +- (void)setPreResolveHosts:(NSArray *)hosts queryIPType:(TrustHttpDNS_IPType)ipType Trust_HTTPDNS_DEPRECATED("Deprecated, this method will be removed in the future. Use -[HttpDnsService setPreResolveHosts:byIPType:] instead."); -/// 本地日志 log 开关 +/// 本地日志 log 开? /// @param enable YES: 打开 NO: 关闭 - (void)setLogEnabled:(BOOL)enable; -/// 设置网络切换时是否自动更新所有域名解析结果 -/// 如果打开此开关,在网络切换时,会自动刷新所有域名的解析结果,但会产生一定流量消耗 -/// @param enable YES: 开启 NO: 关闭 +/// 设置网络切换时是否自动更新所有域名解析结? +/// 如果打开此开关,在网络切换时,会自动刷新所有域名的解析结果,但会产生一定流量消? +/// @param enable YES: 开?NO: 关闭 - (void)setPreResolveAfterNetworkChanged:(BOOL)enable; /// 设置当httpdns解析失败时是否降级到localDNS尝试解析 -/// 降级生效时,SDNS参数不生效,降级逻辑只解析域名,返回的结果默认使用60秒(若未指定该域名自定义TTL)作为TTL值 +/// 降级生效时,SDNS参数不生效,降级逻辑只解析域名,返回的结果默认使?0?若未指定该域名自定义TTL)作为TTL? /// 降级请求也不会再对ip进行优先排序 -/// 默认关闭,不会自动降级 -/// @param enable YES:自动降级 NO:不自动降级 +/// 默认关闭,不会自动降? +/// @param enable YES:自动降?NO:不自动降级 - (void)setDegradeToLocalDNSEnabled:(BOOL)enable; @@ -219,59 +219,59 @@ NS_ASSUME_NONNULL_BEGIN - (void)setIPRankingDatasource:(NSDictionary *)IPRankingDatasource; -/// 设置是否 开启 IPv6 结果解析。只有开启状态下,对域名的解析才会尝试解析v6记录并返回v6的结果 -/// @param enable YES: 开启 NO: 关闭 -- (void)enableIPv6:(BOOL)enable ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setIPv6Enabled:] instead."); +/// 设置是否 开?IPv6 结果解析。只有开启状态下,对域名的解析才会尝试解析v6记录并返回v6的结? +/// @param enable YES: 开?NO: 关闭 +- (void)enableIPv6:(BOOL)enable Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService setIPv6Enabled:] instead."); -/// 设置是否 开启 IPv6 结果解析。只有开启状态下,对域名的解析才会尝试解析v6记录并返回v6的结果 +/// 设置是否 开?IPv6 结果解析。只有开启状态下,对域名的解析才会尝试解析v6记录并返回v6的结? /// 已弃用。默认支持IPv6。如果不需要IPv6类型的结果,只需在请求时指定`queryIpType`为`HttpdnsQueryIPTypeIpv4` -/// @param enable YES: 开启 NO: 关闭 -- (void)setIPv6Enabled:(BOOL)enable ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. If ipv6 is unnecessary, you can set the `queryIpType` as HttpdnsQueryIPTypeIpv4 when resolving domain."); +/// @param enable YES: 开?NO: 关闭 +- (void)setIPv6Enabled:(BOOL)enable Trust_HTTPDNS_DEPRECATED("Deprecated. If ipv6 is unnecessary, you can set the `queryIpType` as HttpdnsQueryIPTypeIpv4 when resolving domain."); /// 是否允许通过 CNCopyCurrentNetworkInfo 获取wifi ssid bssid -/// @param enable YES: 开启 NO: 关闭 ,默认关闭 -- (void)enableNetworkInfo:(BOOL)enable ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. We do not utilize network information anymore"); +/// @param enable YES: 开?NO: 关闭 ,默认关? +- (void)enableNetworkInfo:(BOOL)enable Trust_HTTPDNS_DEPRECATED("Deprecated. We do not utilize network information anymore"); /// 是否允许通过 CNCopyCurrentNetworkInfo 获取wifi ssid bssid -/// @param enable YES: 开启 NO: 关闭 ,默认关闭 -- (void)setReadNetworkInfoEnabled:(BOOL)enable ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. We do not utilize network information anymore."); +/// @param enable YES: 开?NO: 关闭 ,默认关? +- (void)setReadNetworkInfoEnabled:(BOOL)enable Trust_HTTPDNS_DEPRECATED("Deprecated. We do not utilize network information anymore."); /// 是否开启IP探测功能 -/// @param enable YES: 开启 NO: 关闭 默认打开 -- (void)enableCustomIPRank:(BOOL)enable ALICLOUD_HTTPDNS_DEPRECATED("Deprecated, will be removed in the future."); +/// @param enable YES: 开?NO: 关闭 默认打开 +- (void)enableCustomIPRank:(BOOL)enable Trust_HTTPDNS_DEPRECATED("Deprecated, will be removed in the future."); -/// 设置软件自定义解析全局默认参数,设置后,调用软件自定义解析时,每个请求默认都会带上这里配置的参数 +/// 设置软件自定义解析全局默认参数,设置后,调用软件自定义解析时,每个请求默认都会带上这里配置的参? /// @param params 全局默认参数 - (void)setSdnsGlobalParams:(NSDictionary *)params; -/// 设置日志输出回调,以实现自定义日志输出方式 +/// 设置日志输出回调,以实现自定义日志输出方? /// @param logHandler 日志输出回调实现实例 - (void)setLogHandler:(id)logHandler; -/// 获取用于用户追踪的 sessionId -/// sessionId为随机生成,长度为 12 位,App 生命周期内保持不变 -/// 为了排查可能的解析问题,需要您将 sessionId 和解析出的 IP 一起记录在日志中 -/// 请参考: 解析异常排查之 “会话追踪方案” https://help.aliyun.com/document_detail/100530.html +/// 获取用于用户追踪?sessionId +/// sessionId为随机生成,长度?12 位,App 生命周期内保持不? +/// 为了排查可能的解析问题,需要您?sessionId 和解析出?IP 一起记录在日志? +/// 请参? 解析异常排查?“会话追踪方案?https://help.TrustAPP.com/document_detail/100530.html - (NSString *)getSessionId; -/// 同步解析域名,会阻塞当前线程,直到从缓存中获取到有效解析结果,或者从服务器拿到最新解析结果 -/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先返回这个结果,然后启动后台线程去更新解析结果 -/// 为了防止在主线程中误用本接口导致APP卡顿,本接口会做检测,若发现调用线程是主线程,则自动降级到resolveHostSyncNonBlocking接口的实现逻辑。 +/// 同步解析域名,会阻塞当前线程,直到从缓存中获取到有效解析结果,或者从服务器拿到最新解析结? +/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先返回这个结果,然后启动后台线程去更新解析结? +/// 为了防止在主线程中误用本接口导致APP卡顿,本接口会做检测,若发现调用线程是主线程,则自动降级到resolveHostSyncNonBlocking接口的实现逻辑? /// @param host 需要解析的域名 /// @param queryIpType 可设置为自动选择,ipv4,ipv6. 设置为自动选择时,会自动根据当前所处网络环境选择解析ipv4或ipv6 /// @return 解析结果 - (nullable HttpdnsResult *)resolveHostSync:(NSString *)host byIpType:(HttpdnsQueryIPType)queryIpType; -/// 同步解析域名,会阻塞当前线程,直到从缓存中获取到有效解析结果,或者从服务器拿到最新解析结果 -/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先返回这个结果,然后启动后台线程去更新解析结果 -/// 为了防止在主线程中误用本接口导致APP卡顿,本接口会做检测,若发现调用线程是主线程,则自动降级到resolveHostSyncNonBlocking接口的实现逻辑。 +/// 同步解析域名,会阻塞当前线程,直到从缓存中获取到有效解析结果,或者从服务器拿到最新解析结? +/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先返回这个结果,然后启动后台线程去更新解析结? +/// 为了防止在主线程中误用本接口导致APP卡顿,本接口会做检测,若发现调用线程是主线程,则自动降级到resolveHostSyncNonBlocking接口的实现逻辑? /// @param host 需要解析的域名 /// @param queryIpType 可设置为自动选择,ipv4,ipv6. 设置为自动选择时,会自动根据当前所处网络环境选择解析ipv4或ipv6 /// @param sdnsParams 如果域名配置了sdns自定义解析,通过此参数携带自定义参数 @@ -279,22 +279,22 @@ NS_ASSUME_NONNULL_BEGIN /// @return 解析结果 - (nullable HttpdnsResult *)resolveHostSync:(NSString *)host byIpType:(HttpdnsQueryIPType)queryIpType withSdnsParams:(NSDictionary *)sdnsParams sdnsCacheKey:(NSString *)cacheKey; -/// 同步解析域名,会阻塞当前线程,直到从缓存中获取到有效解析结果,或者从服务器拿到最新解析结果 -/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先返回这个结果,然后启动后台线程去更新解析结果 -/// 为了防止在主线程中误用本接口导致APP卡顿,本接口会做检测,若发现调用线程是主线程,则自动降级到resolveHostSyncNonBlocking接口的实现逻辑。 +/// 同步解析域名,会阻塞当前线程,直到从缓存中获取到有效解析结果,或者从服务器拿到最新解析结? +/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先返回这个结果,然后启动后台线程去更新解析结? +/// 为了防止在主线程中误用本接口导致APP卡顿,本接口会做检测,若发现调用线程是主线程,则自动降级到resolveHostSyncNonBlocking接口的实现逻辑? /// @param request 请求参数对象 /// @return 解析结果 - (nullable HttpdnsResult *)resolveHostSync:(HttpdnsRequest *)request; /// 异步解析域名,不会阻塞当前线程,会在从缓存中获取到有效结果,或从服务器拿到最新解析结果后,通过回调返回结果 -/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先在回调中返回这个结果,然后启动后台线程去更新解析结果 +/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先在回调中返回这个结果,然后启动后台线程去更新解析结? /// @param host 需要解析的域名 /// @param queryIpType 可设置为自动选择,ipv4,ipv6. 设置为自动选择时,会自动根据当前所处网络环境选择解析ipv4或ipv6 /// @handler 解析结果回调 - (void)resolveHostAsync:(NSString *)host byIpType:(HttpdnsQueryIPType)queryIpType completionHandler:(void (^)(HttpdnsResult * nullable))handler; /// 异步解析域名,不会阻塞当前线程,会在从缓存中获取到有效结果,或从服务器拿到最新解析结果后,通过回调返回结果 -/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先在回调中返回这个结果,然后启动后台线程去更新解析结果 +/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先在回调中返回这个结果,然后启动后台线程去更新解析结? /// @param host 需要解析的域名 /// @param queryIpType 可设置为自动选择,ipv4,ipv6. 设置为自动选择时,会自动根据当前所处网络环境选择解析ipv4或ipv6 /// @param sdnsParams 如果域名配置了sdns自定义解析,通过此参数携带自定义参数 @@ -303,20 +303,20 @@ NS_ASSUME_NONNULL_BEGIN - (void)resolveHostAsync:(NSString *)host byIpType:(HttpdnsQueryIPType)queryIpType withSdnsParams:(nullable NSDictionary *)sdnsParams sdnsCacheKey:(nullable NSString *)cacheKey completionHandler:(void (^)(HttpdnsResult * nullable))handler; /// 异步解析域名,不会阻塞当前线程,会在从缓存中获取到有效结果,或从服务器拿到最新解析结果后,通过回调返回结果 -/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先在回调中返回这个结果,然后启动后台线程去更新解析结果 +/// 如果允许复用过期的解析结果且存在过期结果的情况下,会先在回调中返回这个结果,然后启动后台线程去更新解析结? /// @param request 请求参数对象 /// @handler 解析结果回调 - (void)resolveHostAsync:(HttpdnsRequest *)request completionHandler:(void (^)(HttpdnsResult * nullable))handler; -/// 伪异步解析域名,不会阻塞当前线程,首次解析结果可能为空 -/// 先查询缓存,缓存中存在有效结果(未过期,或者过期但配置了可以复用过期解析结果),则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 伪异步解析域名,不会阻塞当前线程,首次解析结果可能为? +/// 先查询缓存,缓存中存在有效结?未过期,或者过期但配置了可以复用过期解析结?,则直接返回结果,如果缓存未命中,则发起异步解析请求 /// @param host 需要解析的域名 /// @param queryIpType 可设置为自动选择,ipv4,ipv6. 设置为自动选择时,会自动根据当前所处网络环境选择解析ipv4或ipv6 /// @return 解析结果 - (nullable HttpdnsResult *)resolveHostSyncNonBlocking:(NSString *)host byIpType:(HttpdnsQueryIPType)queryIpType; -/// 伪异步解析域名,不会阻塞当前线程,首次解析结果可能为空 -/// 先查询缓存,缓存中存在有效结果(未过期,或者过期但配置了可以复用过期解析结果),则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 伪异步解析域名,不会阻塞当前线程,首次解析结果可能为? +/// 先查询缓存,缓存中存在有效结?未过期,或者过期但配置了可以复用过期解析结?,则直接返回结果,如果缓存未命中,则发起异步解析请求 /// @param host 需要解析的域名 /// @param queryIpType 可设置为自动选择,ipv4,ipv6. 设置为自动选择时,会自动根据当前所处网络环境选择解析ipv4或ipv6 /// @param sdnsParams 如果域名配置了sdns自定义解析,通过此参数携带自定义参数 @@ -324,8 +324,8 @@ NS_ASSUME_NONNULL_BEGIN /// @return 解析结果 - (nullable HttpdnsResult *)resolveHostSyncNonBlocking:(NSString *)host byIpType:(HttpdnsQueryIPType)queryIpType withSdnsParams:(nullable NSDictionary *)sdnsParams sdnsCacheKey:(nullable NSString *)cacheKey; -/// 伪异步解析域名,不会阻塞当前线程,首次解析结果可能为空 -/// 先查询缓存,缓存中存在有效结果(未过期,或者过期但配置了可以复用过期解析结果),则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 伪异步解析域名,不会阻塞当前线程,首次解析结果可能为? +/// 先查询缓存,缓存中存在有效结?未过期,或者过期但配置了可以复用过期解析结?,则直接返回结果,如果缓存未命中,则发起异步解析请求 /// @param request 请求参数对象 /// @return 解析结果 - (nullable HttpdnsResult *)resolveHostSyncNonBlocking:(HttpdnsRequest *)request; @@ -333,34 +333,34 @@ NS_ASSUME_NONNULL_BEGIN /// 获取域名对应的IP,单IP /// @param host 域名 -- (NSString *)getIpByHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSString *)getIpByHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); /// 异步接口,首次结果可能为空,获取域名对应的IP数组,多IP -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSArray *)getIpsByHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSArray *)getIpsByHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// 异步接口,首次结果可能为空,获取域名对应的ipv6, 单IP (需要开启ipv6 开关 enableIPv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 异步接口,首次结果可能为空,获取域名对应的ipv6, 单IP (需要开启ipv6 开?enableIPv6? +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSString *)getIPv6ByHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSString *)getIPv6ByHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// 异步接口,首次结果可能为空,获取域名对应的ipv6数组, 多IP (需要开启ipv6 开关 enableIPv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 异步接口,首次结果可能为空,获取域名对应的ipv6数组, 多IP (需要开启ipv6 开?enableIPv6? +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSArray *)getIPv6sByHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSArray *)getIPv6sByHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// 同时获取ipv4 ipv6的IP (需要开启ipv6 开关 enableIPv6) +/// 同时获取ipv4 ipv6的IP (需要开启ipv6 开?enableIPv6? /// @param host 域名 /// @result 返回字典类型结构 /// { -/// ALICLOUDHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], -/// ALICLOUDHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] +/// TrustHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], +/// TrustHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] /// } -- (NSDictionary *)getIPv4_v6ByHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSDictionary *)getIPv4_v6ByHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// 根据当前设备的网络状态自动返回域名对应的 IPv4/IPv6地址组 -/// 使用此API 需要确保 enableIPv6 开关已打开 +/// 根据当前设备的网络状态自动返回域名对应的 IPv4/IPv6地址? +/// 使用此API 需要确?enableIPv6 开关已打开 /// 设备网络 返回域名IP /// IPv4 Only IPv4 /// IPv6 Only IPv6 (如果没有Pv6返回空) @@ -368,75 +368,75 @@ NS_ASSUME_NONNULL_BEGIN /// @param host 要解析的域名 /// @result 返回字典类型结构 /// { -/// ALICLOUDHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], -/// ALICLOUDHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] +/// TrustHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], +/// TrustHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] /// } --(NSDictionary *)autoGetIpsByHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +-(NSDictionary *)autoGetIpsByHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); /// 异步接口,首次结果可能为空,获取域名对应的IPv4地址,单IPv4 -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSString *)getIPv4ForHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSString *)getIPv4ForHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); /// 异步接口,首次结果可能为空,获取域名对应的IP数组,多IP -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSArray *)getIPv4ListForHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSArray *)getIPv4ListForHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); /// 获取IPv4地址列表,同步接口,必须在子线程中执行,否则会转变为异步接口 -/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限为5s, -/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大于5s,同步接口也最多阻塞当前线程5s -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起同步解析请求 +/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限?s? +/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大?s,同步接口也最多阻塞当前线?s +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起同步解析请? /// @param host 域名 -- (NSArray *)getIPv4ListForHostSync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); +- (NSArray *)getIPv4ListForHostSync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); -/// 异步接口,首次结果可能为空,获取域名对应的ipv6, 单IP (需要开启ipv6 开关 enableIPv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 异步接口,首次结果可能为空,获取域名对应的ipv6, 单IP (需要开启ipv6 开?enableIPv6? +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSString *)getIPv6ForHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSString *)getIPv6ForHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// 异步接口,首次结果可能为空,获取域名对应的ipv6数组, 多IP (需要开启ipv6 开关 enableIPv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 异步接口,首次结果可能为空,获取域名对应的ipv6数组, 多IP (需要开启ipv6 开?enableIPv6? +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSArray *)getIPv6ListForHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSArray *)getIPv6ListForHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); /// 获取IPv6地址列表,同步接口,必须在子线程中执行,否则会转变为异步接口 -/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限为5s, -/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大于5s,同步接口也最多阻塞当前线程5s +/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限?s? +/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大?s,同步接口也最多阻塞当前线?s /// @param host 域名 -- (NSArray *)getIPv6ListForHostSync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); +- (NSArray *)getIPv6ListForHostSync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); /// 异步接口,首次结果可能为空,获取域名对应格式化后的IP (针对ipv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 -- (NSString *)getIpByHostAsyncInURLFormat:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSString *)getIpByHostAsyncInURLFormat:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// 异步接口,首次结果可能为空,同时获取ipv4 ipv6的IP (需要开启ipv6 开关 enableIPv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 异步接口,首次结果可能为空,同时获取ipv4 ipv6的IP (需要开启ipv6 开?enableIPv6? +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 /// @result 返回字典类型结构 /// { -/// ALICLOUDHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], -/// ALICLOUDHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] +/// TrustHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], +/// TrustHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] /// } -- (NSDictionary *)getHttpDnsResultHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +- (NSDictionary *)getHttpDnsResultHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// NOTE: 同步接口,必须在子线程中执行,否则会转变为异步接口 -/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限为5s, -/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大于5s,同步接口也最多阻塞当前线程5s -/// 同时获取ipv4 + ipv6的IP (需要开启ipv6 开关 enableIPv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// NOTE: 同步接口,必须在子线程中执行,否则会转变为异步接? +/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限?s? +/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大?s,同步接口也最多阻塞当前线?s +/// 同时获取ipv4 + ipv6的IP (需要开启ipv6 开?enableIPv6? +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 /// @result 返回字典类型结构 /// { -/// ALICLOUDHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], -/// ALICLOUDHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] +/// TrustHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], +/// TrustHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] /// } -- (NSDictionary *)getHttpDnsResultHostSync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); +- (NSDictionary *)getHttpDnsResultHostSync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); -/// 异步接口,首次结果可能为空,根据当前设备的网络状态自动返回域名对应的 IPv4/IPv6地址组 -/// 使用此API 需要确保 enableIPv6 开关已打开 +/// 异步接口,首次结果可能为空,根据当前设备的网络状态自动返回域名对应的 IPv4/IPv6地址? +/// 使用此API 需要确?enableIPv6 开关已打开 /// 设备网络 返回域名IP /// IPv4 Only IPv4 /// IPv6 Only IPv6 (如果没有Pv6返回空) @@ -444,33 +444,33 @@ NS_ASSUME_NONNULL_BEGIN /// @param host 要解析的域名 /// @result 返回字典类型结构 /// { -/// ALICLOUDHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], -/// ALICLOUDHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] +/// TrustHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], +/// TrustHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] /// } --(NSDictionary *)autoGetHttpDnsResultForHostAsync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); +-(NSDictionary *)autoGetHttpDnsResultForHostAsync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:] instead."); -/// 根据当前设备的网络状态自动返回域名对应的 IPv4/IPv6地址组,同步接口,必须在子线程中执行,否则会转变为异步接口 -/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限为5s, -/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大于5s,同步接口也最多阻塞当前线程5s -/// 根据当前网络栈自动获取ipv4 ipv6的IP (需要开启ipv6 开关 enableIPv6) -/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请求 +/// 根据当前设备的网络状态自动返回域名对应的 IPv4/IPv6地址组,同步接口,必须在子线程中执行,否则会转变为异步接? +/// 同步接口有超时机制,超时时间为[HttpDnsService sharedInstance].timeoutInterval, 但是超时上限?s? +/// 即使[HttpDnsService sharedInstance].timeoutInterval设置的时间大?s,同步接口也最多阻塞当前线?s +/// 根据当前网络栈自动获取ipv4 ipv6的IP (需要开启ipv6 开?enableIPv6? +/// 先查询缓存,缓存中存在未过期的结果,则直接返回结果,如果缓存未命中,则发起异步解析请? /// @param host 域名 /// @result 返回字典类型结构 /// { -/// ALICLOUDHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], -/// ALICLOUDHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] +/// TrustHDNS_IPV4: ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'], +/// TrustHDNS_IPV6: ['xx:xx:xx:xx:xx:xx:xx:xx', 'xx:xx:xx:xx:xx:xx:xx:xx'] /// } -- (NSDictionary *)autoGetHttpDnsResultForHostSync:(NSString *)host ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); +- (NSDictionary *)autoGetHttpDnsResultForHostSync:(NSString *)host Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSync:byIpType:] instead."); -/// 软件自定义解析接口 -- (NSDictionary *)getIpsByHostAsync:(NSString *)host withParams:(NSDictionary *)params withCacheKey:(NSString *)cacheKey ALICLOUD_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:withSdnsParams:sdnsCacheKey:] instead."); +/// 软件自定义解析接? +- (NSDictionary *)getIpsByHostAsync:(NSString *)host withParams:(NSDictionary *)params withCacheKey:(NSString *)cacheKey Trust_HTTPDNS_DEPRECATED("Deprecated. Use -[HttpDnsService resolveHostSyncNonBlocking:byIpType:withSdnsParams:sdnsCacheKey:] instead."); -/// 清除指定host缓存(内存+沙盒数据库) +/// 清除指定host缓存(内?沙盒数据库) /// @param hostArray 需要清除的host域名数组。如果需要清空全部数据传nil或者空数组即可 - (void)cleanHostCache:(nullable NSArray *)hostArray; -/// 清除当前所有host缓存 (内存+沙盒数据库) +/// 清除当前所有host缓存 (内存+沙盒数据? - (void)cleanAllHostCache; /// 清理已经配置的软件自定义解析全局参数 diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.m index 7f58b34..4463e36 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/HttpdnsService.m @@ -44,12 +44,12 @@ static HttpDnsService *httpdnsSharedStubInstance; @property (nonatomic, copy) NSString *aesSecretKey; @property (nonatomic, assign) BOOL hasConfiguredAccount; - // 每次访问的签名有效期,SDK内部定死,当前不暴露设置接口,有效期定为10分钟。 + // 每次访问的签名有效期,SDK内部定死,当前不暴露设置接口,有效期定为10分钟? @property (nonatomic, assign) NSUInteger authTimeoutInterval; @property (nonatomic, copy) NSDictionary *presetSdnsParamsDict; -// scheduleCenter 已在 HttpdnsService_Internal.h 暴露,避免重复声明 +// scheduleCenter 已在 HttpdnsService_Internal.h 暴露,避免重复声? @end @@ -58,9 +58,9 @@ static HttpDnsService *httpdnsSharedStubInstance; + (void)initialize { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - asyncTaskConcurrentQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.asyncTask", DISPATCH_QUEUE_CONCURRENT); + asyncTaskConcurrentQueue = dispatch_queue_create("com.Trust.sdk.httpdns.asyncTask", DISPATCH_QUEUE_CONCURRENT); httpdnsServiceInstances = [NSMutableDictionary dictionary]; - httpdnsServiceInstancesQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.serviceRegistry", DISPATCH_QUEUE_SERIAL); + httpdnsServiceInstancesQueue = dispatch_queue_create("com.Trust.sdk.httpdns.serviceRegistry", DISPATCH_QUEUE_SERIAL); }); } @@ -168,7 +168,7 @@ static HttpDnsService *httpdnsSharedStubInstance; self.requestManager = [[HttpdnsRequestManager alloc] initWithAccountId:accountID ownerService:self]; NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - NSString *regionKey = [NSString stringWithFormat:@"%@.%ld", kAlicloudHttpdnsRegionKey, (long)accountID]; + NSString *regionKey = [NSString stringWithFormat:@"%@.%ld", kTrustHttpdnsRegionKey, (long)accountID]; NSString *cachedRegion = [userDefault objectForKey:regionKey]; HttpdnsScheduleCenter *scheduleCenter = [[HttpdnsScheduleCenter alloc] initWithAccountId:accountID]; @@ -235,7 +235,7 @@ static HttpDnsService *httpdnsSharedStubInstance; - (void)setRegion:(NSString *)region { if ([HttpdnsUtil isEmptyString:region]) { - region = ALICLOUD_HTTPDNS_DEFAULT_REGION_KEY; + region = Trust_HTTPDNS_DEFAULT_REGION_KEY; } if (![[HttpdnsRegionConfigLoader getAvailableRegionList] containsObject:region]) { @@ -244,7 +244,7 @@ static HttpDnsService *httpdnsSharedStubInstance; } NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - NSString *regionKey = [NSString stringWithFormat:@"%@.%ld", kAlicloudHttpdnsRegionKey, (long)self.accountID]; + NSString *regionKey = [NSString stringWithFormat:@"%@.%ld", kTrustHttpdnsRegionKey, (long)self.accountID]; NSString *oldRegion = [userDefault objectForKey:regionKey]; if (![region isEqualToString:oldRegion]) { [userDefault setObject:region forKey:regionKey]; @@ -262,16 +262,16 @@ static HttpDnsService *httpdnsSharedStubInstance; } -- (void)setPreResolveHosts:(NSArray *)hosts queryIPType:(AlicloudHttpDNS_IPType)ipType { +- (void)setPreResolveHosts:(NSArray *)hosts queryIPType:(TrustHttpDNS_IPType)ipType { HttpdnsQueryIPType ipQueryType; switch (ipType) { - case AlicloudHttpDNS_IPTypeV4: + case TrustHttpDNS_IPTypeV4: ipQueryType = HttpdnsQueryIPTypeIpv4; break; - case AlicloudHttpDNS_IPTypeV6: + case TrustHttpDNS_IPTypeV6: ipQueryType = HttpdnsQueryIPTypeIpv6; break; - case AlicloudHttpDNS_IPTypeV64: + case TrustHttpDNS_IPTypeV64: ipQueryType = HttpdnsQueryIPTypeIpv4 | HttpdnsQueryIPTypeIpv6; break; default: @@ -284,7 +284,7 @@ static HttpDnsService *httpdnsSharedStubInstance; - (void)setPreResolveHosts:(NSArray *)hosts byIPType:(HttpdnsQueryIPType)ipType { // 初始化过程包含了region配置更新流程,region切换会导致缓存清空,立即做预解析可能是没有意义的 - // 这是sdk接口设计的历史问题,目前没有太好办法,这里0.5秒之后再发预解析请求 + // 这是sdk接口设计的历史问题,目前没有太好办法,这?.5秒之后再发预解析请求 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), asyncTaskConcurrentQueue, ^{ [self->_requestManager preResolveHosts:hosts queryType:ipType]; }); @@ -320,20 +320,20 @@ static HttpDnsService *httpdnsSharedStubInstance; } - (void)setIPv6Enabled:(BOOL)enable { - // 默认都支持 + // 默认都支? } - (void)enableNetworkInfo:(BOOL)enable { - // 弃用此接口 + // 弃用此接? } - (void)setReadNetworkInfoEnabled:(BOOL)enable { - // 弃用此接口 + // 弃用此接? } - (void)enableCustomIPRank:(BOOL)enable { - // 不再生效,保留接口 - // 是否开启自定义IP排序,由是否设置IPRankingDatasource和IPRankingDatasource中是否能根据host找到对应的IP来决定 + // 不再生效,保留接? + // 是否开启自定义IP排序,由是否设置IPRankingDatasource和IPRankingDatasource中是否能根据host找到对应的IP来决? } - (NSString *)getSessionId { @@ -357,7 +357,7 @@ static HttpDnsService *httpdnsSharedStubInstance; - (nullable HttpdnsResult *)resolveHostSync:(HttpdnsRequest *)request { if ([NSThread isMainThread]) { - // 主线程做一个防御 + // 主线程做一个防? return [self resolveHostSyncNonBlocking:request]; } @@ -456,7 +456,7 @@ static HttpDnsService *httpdnsSharedStubInstance; if (specifiedQueryIpType == HttpdnsQueryIPTypeAuto) { HttpdnsIPStackType stackType = [[HttpdnsIpStackDetector sharedInstance] currentIpStack]; switch (stackType) { - // 双栈和ipv6only,两个类型都要请求 + // 双栈和ipv6only,两个类型都要请? // 虽然判断是ipv6only,但现实中只有实验室才会有这种情况,考虑判断网络协议栈是有误判可能的,权衡之下,还是应该请求ipv4 // 如果用户是在明确的实验室环境中做测试,他应该直接指定请求type为ipv6 case kHttpdnsIpDual: @@ -470,7 +470,7 @@ static HttpDnsService *httpdnsSharedStubInstance; } } - // 否则就按指定类型来解析 + // 否则就按指定类型来解? return specifiedQueryIpType; } @@ -681,7 +681,7 @@ static HttpDnsService *httpdnsSharedStubInstance; } //需要检查是不是在主线程,如果是主线程,保持异步逻辑 if ([NSThread isMainThread]) { - //如果是主线程,仍然使用异步的方式,即先查询缓存,如果没有,则发送异步请求 + //如果是主线程,仍然使用异步的方式,即先查询缓存,如果没有,则发送异步请? HttpdnsRequest *request = [[HttpdnsRequest alloc] initWithHost:host queryIpType:HttpdnsQueryIPTypeIpv4]; [self attachAccountInfoToRequest:request]; [request becomeNonBlockingRequest]; @@ -839,7 +839,7 @@ static HttpDnsService *httpdnsSharedStubInstance; } if ([NSThread isMainThread]) { - // 如果是主线程,仍然使用异步的方式,即先查询缓存,如果没有,则发送异步请求 + // 如果是主线程,仍然使用异步的方式,即先查询缓存,如果没有,则发送异步请? HttpdnsRequest *request = [[HttpdnsRequest alloc] initWithHost:host queryIpType:HttpdnsQueryIPTypeIpv6]; [self attachAccountInfoToRequest:request]; [request becomeNonBlockingRequest]; @@ -888,9 +888,9 @@ static HttpDnsService *httpdnsSharedStubInstance; if ([HttpdnsUtil isAnIP:host]) { HttpdnsLogDebug("The host is just an IP: %@", host); if ([HttpdnsUtil isIPv4Address:host]) { - return @{ALICLOUDHDNS_IPV4: @[host?:@""]}; + return @{TrustHDNS_IPV4: @[host?:@""]}; } else if ([HttpdnsUtil isIPv6Address:host]) { - return @{ALICLOUDHDNS_IPV6: @[host?:@""]}; + return @{TrustHDNS_IPV6: @[host?:@""]}; } return nil; } @@ -909,10 +909,10 @@ static HttpDnsService *httpdnsSharedStubInstance; NSArray *ip6s = [hostObject getV6IpStrings]; NSMutableDictionary *resultMDic = [NSMutableDictionary dictionary]; if ([HttpdnsUtil isNotEmptyArray:ip4s]) { - [resultMDic setObject:ip4s forKey:ALICLOUDHDNS_IPV4]; + [resultMDic setObject:ip4s forKey:TrustHDNS_IPV4]; } if ([HttpdnsUtil isNotEmptyArray:ip6s]) { - [resultMDic setObject:ip6s forKey:ALICLOUDHDNS_IPV6]; + [resultMDic setObject:ip6s forKey:TrustHDNS_IPV6]; } NSLog(@"getIPv4_v6ByHostAsync result is %@", resultMDic); return resultMDic; @@ -935,9 +935,9 @@ static HttpDnsService *httpdnsSharedStubInstance; if ([HttpdnsUtil isAnIP:host]) { HttpdnsLogDebug("The host is just an IP: %@", host); if ([HttpdnsUtil isIPv4Address:host]) { - return @{ALICLOUDHDNS_IPV4: @[host?:@""]}; + return @{TrustHDNS_IPV4: @[host?:@""]}; } else if ([HttpdnsUtil isIPv6Address:host]) { - return @{ALICLOUDHDNS_IPV6: @[host?:@""]}; + return @{TrustHDNS_IPV6: @[host?:@""]}; } return nil; } @@ -957,10 +957,10 @@ static HttpDnsService *httpdnsSharedStubInstance; NSMutableDictionary *httpdnsResult = [NSMutableDictionary dictionary]; NSLog(@"getHttpDnsResultHostAsync result is %@", httpdnsResult); if ([HttpdnsUtil isNotEmptyArray:ip4s]) { - [httpdnsResult setObject:ip4s forKey:ALICLOUDHDNS_IPV4]; + [httpdnsResult setObject:ip4s forKey:TrustHDNS_IPV4]; } if ([HttpdnsUtil isNotEmptyArray:ip6s]) { - [httpdnsResult setObject:ip6s forKey:ALICLOUDHDNS_IPV6]; + [httpdnsResult setObject:ip6s forKey:TrustHDNS_IPV6]; } return httpdnsResult; } @@ -981,9 +981,9 @@ static HttpDnsService *httpdnsSharedStubInstance; if ([HttpdnsUtil isAnIP:host]) { HttpdnsLogDebug("The host is just an IP: %@", host); if ([HttpdnsUtil isIPv4Address:host]) { - return @{ALICLOUDHDNS_IPV4: @[host?:@""]}; + return @{TrustHDNS_IPV4: @[host?:@""]}; } else if ([HttpdnsUtil isIPv6Address:host]) { - return @{ALICLOUDHDNS_IPV6: @[host?:@""]}; + return @{TrustHDNS_IPV6: @[host?:@""]}; } return nil; } @@ -1005,10 +1005,10 @@ static HttpDnsService *httpdnsSharedStubInstance; NSMutableDictionary *resultMDic = [NSMutableDictionary dictionary]; NSLog(@"getIPv4_v6ByHostAsync result is %@", resultMDic); if ([HttpdnsUtil isNotEmptyArray:ip4s]) { - [resultMDic setObject:ip4s forKey:ALICLOUDHDNS_IPV4]; + [resultMDic setObject:ip4s forKey:TrustHDNS_IPV4]; } if ([HttpdnsUtil isNotEmptyArray:ip6s]) { - [resultMDic setObject:ip6s forKey:ALICLOUDHDNS_IPV6]; + [resultMDic setObject:ip6s forKey:TrustHDNS_IPV6]; } return resultMDic; } @@ -1026,10 +1026,10 @@ static HttpDnsService *httpdnsSharedStubInstance; NSArray *ip6s = [hostObject getV6IpStrings]; resultMDic = [NSMutableDictionary dictionary]; if ([HttpdnsUtil isNotEmptyArray:ip4s]) { - [resultMDic setObject:ip4s forKey:ALICLOUDHDNS_IPV4]; + [resultMDic setObject:ip4s forKey:TrustHDNS_IPV4]; } if ([HttpdnsUtil isNotEmptyArray:ip6s]) { - [resultMDic setObject:ip6s forKey:ALICLOUDHDNS_IPV6]; + [resultMDic setObject:ip6s forKey:TrustHDNS_IPV6]; } NSLog(@"###### getHttpDnsResultHostSync result is %@", resultMDic); } @@ -1045,12 +1045,12 @@ static HttpDnsService *httpdnsSharedStubInstance; } else if (stackType == kHttpdnsIpv4Only) { NSArray* ipv4Ips = [self getIpsByHostAsync:host]; if (ipv4Ips != nil) { - [ipv4_ipv6 setObject:ipv4Ips forKey:ALICLOUDHDNS_IPV4]; + [ipv4_ipv6 setObject:ipv4Ips forKey:TrustHDNS_IPV4]; } } else if (stackType == kHttpdnsIpv6Only) { NSArray* ipv6Ips = [self getIPv6sByHostAsync:host]; if (ipv6Ips != nil) { - [ipv4_ipv6 setObject:ipv6Ips forKey:ALICLOUDHDNS_IPV6]; + [ipv4_ipv6 setObject:ipv6Ips forKey:TrustHDNS_IPV6]; } } @@ -1065,12 +1065,12 @@ static HttpDnsService *httpdnsSharedStubInstance; } else if (stackType == kHttpdnsIpv4Only) { NSArray* ipv4IpList = [self getIPv4ListForHostAsync:host]; if (ipv4IpList) { - [httpdnsResult setObject:ipv4IpList forKey:ALICLOUDHDNS_IPV4]; + [httpdnsResult setObject:ipv4IpList forKey:TrustHDNS_IPV4]; } } else if (stackType == kHttpdnsIpv6Only) { NSArray* ipv6List = [self getIPv6ListForHostAsync:host]; if (ipv6List) { - [httpdnsResult setObject:ipv6List forKey:ALICLOUDHDNS_IPV6]; + [httpdnsResult setObject:ipv6List forKey:TrustHDNS_IPV6]; } } @@ -1083,14 +1083,14 @@ static HttpDnsService *httpdnsSharedStubInstance; if (stackType == kHttpdnsIpv4Only) { NSArray* ipv4IpList = [self getIPv4ListForHostSync:host]; if (ipv4IpList) { - [httpdnsResult setObject:ipv4IpList forKey:ALICLOUDHDNS_IPV4]; + [httpdnsResult setObject:ipv4IpList forKey:TrustHDNS_IPV4]; } } else if (stackType == kHttpdnsIpDual) { httpdnsResult = [[self getHttpDnsResultHostSync:host] mutableCopy]; } else if (stackType == kHttpdnsIpv6Only) { NSArray* ipv6List = [self getIPv6ListForHostSync:host]; if (ipv6List) { - [httpdnsResult setObject:ipv6List forKey:ALICLOUDHDNS_IPV6]; + [httpdnsResult setObject:ipv6List forKey:TrustHDNS_IPV6]; } } return httpdnsResult; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/IpStack/HttpdnsIpStackDetector.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/IpStack/HttpdnsIpStackDetector.h index 2039e93..b26a907 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/IpStack/HttpdnsIpStackDetector.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/IpStack/HttpdnsIpStackDetector.h @@ -1,9 +1,9 @@ // // HttpdnsIpStackDetector.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2025/3/16. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import @@ -11,10 +11,10 @@ NS_ASSUME_NONNULL_BEGIN /** - * IP 协议栈类型 + * IP 协议栈类? */ typedef enum { - kHttpdnsIpUnknown = 0, // 未知协议栈 + kHttpdnsIpUnknown = 0, // 未知协议? kHttpdnsIpv4Only = 1, // IPv4-only kHttpdnsIpv6Only = 2, // IPv6-only kHttpdnsIpDual = 3 // 双栈 @@ -23,13 +23,13 @@ typedef enum { @interface HttpdnsIpStackDetector : NSObject /** - * 返回HttpdnsIpStackDetector的共享实例 + * 返回HttpdnsIpStackDetector的共享实? * @return HttpdnsIpStackDetector实例 */ + (instancetype)sharedInstance; /** - * 返回当前缓存的IP协议栈类型,不执行检测 + * 返回当前缓存的IP协议栈类型,不执行检? * @return HttpdnsIPStackType */ - (HttpdnsIPStackType)currentIpStack; @@ -41,7 +41,7 @@ typedef enum { - (BOOL)isIpv6OnlyNetwork; /** - * 强制重新检测IP协议栈类型 + * 强制重新检测IP协议栈类? */ - (void)redetectIpStack; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLog_Internal.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLog_Internal.h index e276a7a..63ccb20 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLog_Internal.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLog_Internal.h @@ -1,16 +1,16 @@ // // HttpdnsLog_Internal.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by junmo on 2018/12/19. -// Copyright © 2018年 alibaba-inc.com. All rights reserved. +// Copyright © 2018?trustapp.com. All rights reserved. // #import "HttpdnsLog.h" #import "HttpdnsLoggerProtocol.h" #import -// logHandler输出日志,不受日志开关影响 +// logHandler输出日志,不受日志开关影? #define HttpdnsLogDebug(frmt, ...) \ if ([HttpdnsLog validLogHandler]) { \ @try { \ diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLoggerProtocol.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLoggerProtocol.h index 683e971..f37b77b 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLoggerProtocol.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Log/HttpdnsLoggerProtocol.h @@ -1,9 +1,9 @@ // // HttpdnsLoggerProtocol.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by junmo on 2018/12/19. -// Copyright © 2018年 alibaba-inc.com. All rights reserved. +// Copyright © 2018?trustapp.com. All rights reserved. // #ifndef HttpdnsLoggerProtocol_h diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.h index 8fc73df..a85901f 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.h @@ -52,7 +52,7 @@ @property (nonatomic, setter=setV6TTL:, getter=getV6TTL) int64_t v6ttl; @property (nonatomic, assign) int64_t lastIPv6LookupTime; -// 用来标记该域名为配置v4记录或v6记录的情况,避免如双栈网络下因为某个协议查不到record需要重复请求 +// 用来标记该域名为配置v4记录或v6记录的情况,避免如双栈网络下因为某个协议查不到record需要重复请? // 这个信息不用持久化,一次APP启动周期内使用是合适的 @property (nonatomic, assign) BOOL hasNoIpv4Record; @property (nonatomic, assign) BOOL hasNoIpv6Record; @@ -71,8 +71,8 @@ + (instancetype)fromDBRecord:(HttpdnsHostRecord *)IPRecord; /** - * 将当前对象转换为数据库记录对象 - * @return 数据库记录对象 + * 将当前对象转换为数据库记录对? + * @return 数据库记录对? */ - (HttpdnsHostRecord *)toDBRecord; @@ -83,7 +83,7 @@ /** * 更新指定IP的connectedRT值并重新排序IP列表 * @param ip 需要更新的IP地址 - * @param connectedRT 检测到的RT值,-1表示不可达 + * @param connectedRT 检测到的RT值,-1表示不可? */ - (void)updateConnectedRT:(NSInteger)connectedRT forIP:(NSString *)ip; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.m index 522e02a..27dd90d 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostObject.m @@ -29,7 +29,7 @@ - (instancetype)init { if (self = [super init]) { - // 初始化connectedRT为最大整数值 + // 初始化connectedRT为最大整数? self.connectedRT = NSIntegerMax; } return self; @@ -129,13 +129,13 @@ - (BOOL)isIpEmptyUnderQueryIpType:(HttpdnsQueryIPType)queryType { if (queryType & HttpdnsQueryIPTypeIpv4) { - // 注意,_hasNoIpv4Record为true时,说明域名没有配置ipv4ip,不是需要去请求的情况 + // 注意,_hasNoIpv4Record为true时,说明域名没有配置ipv4ip,不是需要去请求的情? if ([HttpdnsUtil isEmptyArray:[self getV4Ips]] && !_hasNoIpv4Record) { return YES; } } else if (queryType & HttpdnsQueryIPTypeIpv6 && !_hasNoIpv6Record) { - // 注意,_hasNoIpv6Record为true时,说明域名没有配置ipv6ip,不是需要去请求的情况 + // 注意,_hasNoIpv6Record为true时,说明域名没有配置ipv6ip,不是需要去请求的情? if ([HttpdnsUtil isEmptyArray:[self getV6Ips]] && !_hasNoIpv6Record) { return YES; } @@ -202,14 +202,14 @@ } - (HttpdnsHostRecord *)toDBRecord { - // 将IP对象数组转换为IP字符串数组 + // 将IP对象数组转换为IP字符串数? NSArray *v4IpStrings = [self getV4IpStrings]; NSArray *v6IpStrings = [self getV6IpStrings]; // 创建当前时间作为modifyAt NSDate *currentDate = [NSDate date]; - // 使用hostName作为cacheKey,保持与fromDBRecord方法的一致性 + // 使用hostName作为cacheKey,保持与fromDBRecord方法的一致? return [[HttpdnsHostRecord alloc] initWithId:0 // 数据库会自动分配ID cacheKey:self.cacheKey hostName:self.hostName @@ -271,17 +271,17 @@ return; } - // 根据connectedRT值对IP列表进行排序,-1值放在最后 + // 根据connectedRT值对IP列表进行排序?1值放在最? [mutableIpObjects sortUsingComparator:^NSComparisonResult(HttpdnsIpObject *obj1, HttpdnsIpObject *obj2) { - // 如果obj1的connectedRT为-1,将其排在后面 + // 如果obj1的connectedRT?1,将其排在后? if (obj1.connectedRT == -1) { return NSOrderedDescending; } - // 如果obj2的connectedRT为-1,将其排在后面 + // 如果obj2的connectedRT?1,将其排在后? if (obj2.connectedRT == -1) { return NSOrderedAscending; } - // 否则按照connectedRT值从小到大排序 + // 否则按照connectedRT值从小到大排? return obj1.connectedRT > obj2.connectedRT ? NSOrderedDescending : (obj1.connectedRT < obj2.connectedRT ? NSOrderedAscending : NSOrderedSame); }]; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.h index fdbd700..17a42f0 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.h @@ -1,9 +1,9 @@ // // HttpdnsHostRecord.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/5/3. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.m index a459358..cd86b06 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsHostRecord.m @@ -1,9 +1,9 @@ // // HttpdnsHostRecord.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/5/3. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import "HttpdnsHostRecord.h" diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.h index 46dbfce..e4a6e32 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.h @@ -1,23 +1,23 @@ // // HttpdnsRequest.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/5/19. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import NS_ASSUME_NONNULL_BEGIN -#ifndef ALICLOUDHTTPDNSQUERYIPTYPE -#define ALICLOUDHTTPDNSQUERYIPTYPE +#ifndef TrustHTTPDNSQUERYIPTYPE +#define TrustHTTPDNSQUERYIPTYPE typedef enum { - AlicloudHttpDNS_IPTypeV4 = 0, //ipv4 - AlicloudHttpDNS_IPTypeV6 = 1, //ipv6 - AlicloudHttpDNS_IPTypeV64 = 2, //ipv4 + ipv6 -} AlicloudHttpDNS_IPType; + TrustHttpDNS_IPTypeV4 = 0, //ipv4 + TrustHttpDNS_IPTypeV6 = 1, //ipv6 + TrustHttpDNS_IPTypeV64 = 2, //ipv4 + ipv6 +} TrustHttpDNS_IPType; typedef NS_OPTIONS(NSUInteger, HttpdnsQueryIPType) { HttpdnsQueryIPTypeAuto NS_SWIFT_NAME(auto) = 0, @@ -33,15 +33,15 @@ typedef NS_OPTIONS(NSUInteger, HttpdnsQueryIPType) { /// 需要解析的域名 @property (nonatomic, copy) NSString *host; -/// 解析超时时间,对于同步接口,即为最大等待时间,对于异步接口,即为最大等待回调时间 -/// 默认值2秒,取值必须在0.5秒 - 5秒之间 +/// 解析超时时间,对于同步接口,即为最大等待时间,对于异步接口,即为最大等待回调时? +/// 默认?秒,取值必须在0.5?- 5秒之? @property (nonatomic, assign) double resolveTimeoutInSecond; /// 查询IP类型 /// 默认为HttpdnsQueryIPTypeAuto,此类型下,SDK至少会请求解析ipv4地址,若判断到当前网络环境支持ipv6,则还会请求解析ipv6地址 /// HttpdnsQueryIPTypeIpv4,只请求解析ipv4 /// HttpdnsQueryIPTypeIpv6,只请求解析ipv6 -/// HttpdnsQueryIPTypeBoth,不管当前网络环境是什么,会尝试同时请求解析ipv4地址和ipv6地址,这种用法,通常需要拿到结果之后自行判断网络环境决定使用哪个结果 +/// HttpdnsQueryIPTypeBoth,不管当前网络环境是什么,会尝试同时请求解析ipv4地址和ipv6地址,这种用法,通常需要拿到结果之后自行判断网络环境决定使用哪个结? @property (nonatomic, assign) HttpdnsQueryIPType queryIpType; /// SDNS参数,针对软件自定义解析场景使用 diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.m index 1cb776f..0749da4 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest.m @@ -1,9 +1,9 @@ // // HttpdnsRequest.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/5/19. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import "HttpdnsRequest.h" @@ -65,7 +65,7 @@ static double const RESOLVE_HOST_MAX_TIMEOUT_IN_SEC = 5; } else if (_resolveTimeoutInSecond > RESOLVE_HOST_MAX_TIMEOUT_IN_SEC) { _resolveTimeoutInSecond = RESOLVE_HOST_MAX_TIMEOUT_IN_SEC; } else { - // 在范围内的正常值 + // 在范围内的正常? } } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest_Internal.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest_Internal.h index 01ffc8c..3019f17 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest_Internal.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsRequest_Internal.h @@ -1,9 +1,9 @@ // // HttpdnsRequest_Internal.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/6/19. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #ifndef HttpdnsRequest_Internal_h diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.h index b8c8685..4eae03b 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.h @@ -1,9 +1,9 @@ // // HttpdnsResult.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/5/15. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.m index 08f8d62..ec5ec18 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Model/HttpdnsResult.m @@ -1,9 +1,9 @@ // // HttpdnsResult.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/5/15. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import "HttpdnsResult.h" diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.h index c9b9a15..b037a20 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @interface HttpdnsNWHTTPClient : NSObject -/// 全局共享实例,复用底层连接池;线程安全 +/// 全局共享实例,复用底层连接池;线程安? + (instancetype)sharedInstance; - (nullable HttpdnsNWHTTPClientResponse *)performRequestWithURLString:(NSString *)urlString diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.m index c686b46..4ae99c3 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient.m @@ -30,7 +30,7 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; @property (nonatomic, strong) dispatch_queue_t poolQueue; #if DEBUG -// 测试专用统计计数器 +// 测试专用统计计数? @property (atomic, assign) NSUInteger connectionCreationCount; @property (atomic, assign) NSUInteger connectionReuseCount; #endif @@ -81,7 +81,7 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; - (instancetype)init { self = [super init]; if (self) { - _poolQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.network.pool", DISPATCH_QUEUE_SERIAL); + _poolQueue = dispatch_queue_create("com.Trust.sdk.httpdns.network.pool", DISPATCH_QUEUE_SERIAL); _connectionPool = [NSMutableDictionary dictionary]; } return self; @@ -95,8 +95,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSURL *url = [NSURL URLWithString:urlString]; if (!url) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Invalid resolve URL"}]; } return nil; @@ -107,8 +107,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSString *host = url.host; if (![HttpdnsUtil isNotEmptyString:host]) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Missing host in resolve URL"}]; } return nil; @@ -121,8 +121,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSData *requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding]; if (!requestData) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Failed to encode HTTP request"}]; } return nil; @@ -136,8 +136,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; error:&connectionError]; if (!connection) { if (error) { - *error = connectionError ?: [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = connectionError ?: [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Unable to obtain network connection"}]; } return nil; @@ -154,8 +154,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; if (!rawResponse) { [self returnConnection:connection forKey:poolKey shouldClose:YES]; if (error) { - *error = exchangeError ?: [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = exchangeError ?: [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Network request failed"}]; } return nil; @@ -168,8 +168,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; if (![self parseHTTPResponseData:rawResponse statusCode:&statusCode headers:&headers body:&bodyData error:&parseError]) { [self returnConnection:connection forKey:poolKey shouldClose:YES]; if (error) { - *error = parseError ?: [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = parseError ?: [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Failed to parse HTTP response"}]; } return nil; @@ -239,8 +239,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; useTLS:useTLS]; if (!newConnection) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Failed to create network connection"}]; } return nil; @@ -409,8 +409,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSString *headerString = [[NSString alloc] initWithData:headerData encoding:NSUTF8StringEncoding]; if (![HttpdnsUtil isNotEmptyString:headerString]) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Failed to decode HTTP headers"}]; } return HttpdnsHTTPHeaderParseResultError; @@ -419,8 +419,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSArray *lines = [headerString componentsSeparatedByString:@"\r\n"]; if (lines.count == 0) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Missing HTTP status line"}]; } return HttpdnsHTTPHeaderParseResultError; @@ -437,8 +437,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; if (filteredParts.count < 2) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid HTTP status line"}]; } return HttpdnsHTTPHeaderParseResultError; @@ -447,8 +447,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSInteger localStatus = [filteredParts[1] integerValue]; if (localStatus <= 0) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid HTTP status code"}]; } return HttpdnsHTTPHeaderParseResultError; @@ -510,8 +510,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSString *sizeString = [[NSString alloc] initWithData:sizeData encoding:NSUTF8StringEncoding]; if (![HttpdnsUtil isNotEmptyString:sizeString]) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid chunk size"}]; } return HttpdnsHTTPChunkParseResultError; @@ -524,8 +524,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; unsigned long long chunkSize = strtoull(cStr, &endPtr, 16); if (endPtr == NULL || endPtr == cStr) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid chunk size"}]; } return HttpdnsHTTPChunkParseResultError; @@ -533,8 +533,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; if (chunkSize > NSUIntegerMax - cursor) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Chunk size overflow"}]; } return HttpdnsHTTPChunkParseResultError; @@ -570,8 +570,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; } if (bytes[cursor] != '\r' || bytes[cursor + 1] != '\n') { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid chunk terminator"}]; } return HttpdnsHTTPChunkParseResultError; @@ -589,8 +589,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; error:(NSError **)error { if (!data || data.length == 0) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Empty HTTP response"}]; } return NO; @@ -608,8 +608,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; if (headerResult != HttpdnsHTTPHeaderParseResultSuccess) { if (error) { if (headerResult == HttpdnsHTTPHeaderParseResultIncomplete) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Missing HTTP header terminator"}]; } else { *error = headerError; @@ -670,8 +670,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; } if (lineEnd + 1 >= length) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid chunked encoding"}]; } return nil; @@ -681,8 +681,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; NSString *sizeString = [[NSString alloc] initWithData:sizeData encoding:NSUTF8StringEncoding]; if (![HttpdnsUtil isNotEmptyString:sizeString]) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid chunk size"}]; } return nil; @@ -695,8 +695,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; // 检查是否是无效的十六进制字符串 if (endPtr == cStr) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid chunk size format"}]; } return nil; @@ -710,8 +710,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; } if (cursor + chunkSize > length) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Chunk size exceeds buffer"}]; } return nil; @@ -720,8 +720,8 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; cursor += chunkSize; if (cursor + 1 >= length || bytes[cursor] != '\r' || bytes[cursor + 1] != '\n') { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Invalid chunk terminator"}]; } return nil; @@ -734,7 +734,7 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain { // 测试专用:通过环境变量跳过 TLS 验证 - // 仅在设置 HTTPDNS_SKIP_TLS_VERIFY 环境变量时生效(用于本地 mock server 测试) + // 仅在设置 HTTPDNS_SKIP_TLS_VERIFY 环境变量时生效(用于本地 mock server 测试? if (getenv("HTTPDNS_SKIP_TLS_VERIFY") != NULL) { return YES; } @@ -777,15 +777,15 @@ static const NSTimeInterval kHttpdnsNWHTTPClientDefaultTimeout = 10.0; if (!userInfo[NSLocalizedDescriptionKey]) { userInfo[NSLocalizedDescriptionKey] = @"Network operation failed"; } - return [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + return [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:userInfo]; } @end #if DEBUG -// 测试专用:连接池检查 API 实现 +// 测试专用:连接池检?API 实现 @implementation HttpdnsNWHTTPClient (TestInspection) - (NSUInteger)connectionPoolCountForKey:(NSString *)key { diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient_Internal.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient_Internal.h index f370011..f572dfc 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient_Internal.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWHTTPClient_Internal.h @@ -30,7 +30,7 @@ typedef NS_ENUM(NSInteger, HttpdnsHTTPChunkParseResult) { headers:(NSDictionary *__autoreleasing _Nullable * _Nullable)headers error:(NSError * _Nullable * _Nullable)error; -// Chunked 编码检查 +// Chunked 编码检? - (HttpdnsHTTPChunkParseResult)checkChunkedBodyCompletionInData:(NSData *)data headerEndIndex:(NSUInteger)headerEndIndex error:(NSError * _Nullable * _Nullable)error; @@ -48,7 +48,7 @@ typedef NS_ENUM(NSInteger, HttpdnsHTTPChunkParseResult) { // HTTP 请求构建 - (NSString *)buildHTTPRequestStringWithURL:(NSURL *)url userAgent:(NSString *)userAgent; -// 连接池 key 生成 +// 连接?key 生成 - (NSString *)connectionPoolKeyForHost:(NSString *)host port:(NSString *)port useTLS:(BOOL)useTLS; // 错误转换 @@ -57,10 +57,10 @@ typedef NS_ENUM(NSInteger, HttpdnsHTTPChunkParseResult) { @end #if DEBUG -// 测试专用:连接池检查 API +// 测试专用:连接池检?API @interface HttpdnsNWHTTPClient (TestInspection) -// 获取指定 pool key 的连接数量 +// 获取指定 pool key 的连接数? - (NSUInteger)connectionPoolCountForKey:(NSString *)key; // 获取所有连接池 keys @@ -75,7 +75,7 @@ typedef NS_ENUM(NSInteger, HttpdnsHTTPChunkParseResult) { // 连接复用计数(用于验证连接复用) @property (atomic, assign) NSUInteger connectionReuseCount; -// 重置统计计数器(每个测试开始前调用) +// 重置统计计数器(每个测试开始前调用? - (void)resetPoolStatistics; @end diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.h index c880411..4ea1c89 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.h @@ -32,8 +32,8 @@ NS_ASSUME_NONNULL_BEGIN @interface HttpdnsNWReusableConnection (DebugInspection) // 状态检查(这些属性已在主接口暴露,这里仅为文档明确) -// @property lastUsedDate - 可读写 -// @property inUse - 可读写 +// @property lastUsedDate - 可读? +// @property inUse - 可读? // @property invalidated - 只读 // 测试辅助方法 diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.m index a7d8a7c..9ccf091 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Network/HttpdnsNWReusableConnection.m @@ -13,7 +13,7 @@ @class HttpdnsNWHTTPClient; -// 只在此实现文件内可见的交换对象,承载一次请求/响应数据与状态 +// 只在此实现文件内可见的交换对象,承载一次请?响应数据与状? @interface HttpdnsNWHTTPExchange : NSObject @property (nonatomic, strong, readonly) NSMutableData *buffer; @@ -99,7 +99,7 @@ _host = [host copy]; _port = [port copy]; _useTLS = useTLS; - _queue = dispatch_queue_create("com.alibaba.sdk.httpdns.network.connection.reuse", DISPATCH_QUEUE_SERIAL); + _queue = dispatch_queue_create("com.Trust.sdk.httpdns.network.connection.reuse", DISPATCH_QUEUE_SERIAL); _stateSemaphore = dispatch_semaphore_create(0); _state = nw_connection_state_invalid; _lastUsedDate = [NSDate date]; @@ -135,14 +135,14 @@ if (secTrust && strongSelf) { SecTrustRef trustRef = sec_trust_copy_ref(secTrust); if (trustRef) { - NSString *validIP = ALICLOUD_HTTPDNS_VALID_SERVER_CERTIFICATE_IP; + NSString *validIP = Trust_HTTPDNS_VALID_SERVER_CERTIFICATE_IP; isValid = [strongSelf.client evaluateServerTrust:trustRef forDomain:validIP]; if (!isValid && [HttpdnsUtil isNotEmptyString:strongSelf.host]) { isValid = [strongSelf.client evaluateServerTrust:trustRef forDomain:strongSelf.host]; } if (!isValid && !strongSelf.stateError) { - strongSelf.stateError = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + strongSelf.stateError = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"TLS trust validation failed"}]; } CFRelease(trustRef); @@ -220,8 +220,8 @@ - (BOOL)openWithTimeout:(NSTimeInterval)timeout error:(NSError **)error { if (self.invalidated) { if (error) { - *error = _stateError ?: [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = _stateError ?: [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Connection invalid"}]; } return NO; @@ -237,8 +237,8 @@ if (waitResult != 0) { self.invalidated = YES; if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Connection setup timed out"}]; } nw_connection_cancel(_connectionHandle); @@ -250,8 +250,8 @@ } if (error) { - *error = _stateError ?: [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = _stateError ?: [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Connection failed to become ready"}]; } return NO; @@ -277,8 +277,8 @@ error:(NSError **)error { if (!requestData || requestData.length == 0) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Empty HTTP request"}]; } return nil; @@ -286,8 +286,8 @@ if (![self isViable] || self.currentExchange) { if (error) { - *error = _stateError ?: [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + *error = _stateError ?: [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Connection not ready"}]; } return nil; @@ -299,16 +299,16 @@ dispatch_sync(_queue, ^{ __strong typeof(weakSelf) strongSelf = weakSelf; if (!strongSelf) { - exchange.error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + exchange.error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Connection released unexpectedly"}]; exchange.finished = YES; dispatch_semaphore_signal(exchange.semaphore); return; } if (strongSelf.invalidated || strongSelf.currentExchange) { - exchange.error = strongSelf.stateError ?: [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + exchange.error = strongSelf.stateError ?: [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Connection is busy"}]; exchange.finished = YES; dispatch_semaphore_signal(exchange.semaphore); @@ -320,8 +320,8 @@ if (exchange.finished) { return; } - exchange.error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + exchange.error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Request timed out"}]; exchange.finished = YES; dispatch_semaphore_signal(exchange.semaphore); @@ -366,8 +366,8 @@ if (waitResult != 0) { if (!exchange.error) { - exchange.error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + exchange.error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Request wait timed out"}]; } [self invalidate]; @@ -428,8 +428,8 @@ if (is_complete) { exchange.remoteClosed = YES; if (!exchange.finished) { - exchange.error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_COMMON_ERROR_CODE + exchange.error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_COMMON_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Connection closed before response completed"}]; exchange.finished = YES; dispatch_semaphore_signal(exchange.semaphore); @@ -452,7 +452,7 @@ } if (isComplete) { - // 远端已经发送完并关闭,需要提前标记,避免提前返回时漏记连接状态 + // 远端已经发送完并关闭,需要提前标记,避免提前返回时漏记连接状? exchange.remoteClosed = YES; } @@ -527,7 +527,7 @@ @end #if DEBUG -// 测试专用:连接状态操作实现 +// 测试专用:连接状态操作实? @implementation HttpdnsNWReusableConnection (DebugInspection) - (void)debugSetLastUsedDate:(nullable NSDate *)date { diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsDB.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsDB.h index 7e1bbcc..a6d0d68 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsDB.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsDB.h @@ -1,9 +1,9 @@ // // HttpdnsDB.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2025/3/15. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import @@ -19,53 +19,53 @@ NS_ASSUME_NONNULL_BEGIN /** * 初始化数据库 * @param accountId 账户ID - * @return 数据库实例 + * @return 数据库实? */ - (instancetype)initWithAccountId:(NSInteger)accountId; /** - * 创建或更新记录 + * 创建或更新记? * @param record 主机记录 * @return 是否成功 */ - (BOOL)createOrUpdate:(HttpdnsHostRecord *)record; /** - * 根据缓存键查询记录 - * @param cacheKey 缓存键 + * 根据缓存键查询记? + * @param cacheKey 缓存? * @return 查询到的记录,如果不存在则返回nil */ - (nullable HttpdnsHostRecord *)selectByCacheKey:(NSString *)cacheKey; /** - * 根据缓存键删除记录 - * @param cacheKey 缓存键 + * 根据缓存键删除记? + * @param cacheKey 缓存? * @return 是否成功 */ - (BOOL)deleteByCacheKey:(NSString *)cacheKey; /** - * 根据主机名数组批量删除记录 - * @param hostNameArr 主机名数组 - * @return 成功删除的记录数量 + * 根据主机名数组批量删除记? + * @param hostNameArr 主机名数? + * @return 成功删除的记录数? */ - (NSInteger)deleteByHostNameArr:(NSArray *)hostNameArr; /** - * 获取所有缓存记录 - * @return 所有缓存记录数组 + * 获取所有缓存记? + * @return 所有缓存记录数? */ - (NSArray *)getAllRecords; /** - * 清理指定时间点已过期的记录 - * @param specifiedTime 指定的时间点(epoch时间) - * @return 清理的记录数量 + * 清理指定时间点已过期的记? + * @param specifiedTime 指定的时间点(epoch时间? + * @return 清理的记录数? */ - (NSInteger)cleanRecordAlreadExpiredAt:(NSTimeInterval)specifiedTime; /** - * 删除所有记录 + * 删除所有记? * @return 是否成功 */ - (BOOL)deleteAll; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.h index 33d4d9b..7e17d7e 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.h @@ -23,7 +23,7 @@ + (NSString *)httpdnsDataDirectory; + (NSString *)scheduleCenterResultDirectory; -/// 多账号隔离:返回指定账号的调度结果目录 +/// 多账号隔离:返回指定账号的调度结果目? + (NSString *)scheduleCenterResultDirectoryForAccount:(NSInteger)accountId; + (BOOL)saveJSON:(id)JSON toPath:(NSString *)path; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.m index 5fec7fc..f82ccf9 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Persistent/HttpdnsPersistenceUtils.m @@ -21,8 +21,8 @@ #import "HttpdnsService.h" #import "HttpdnsUtil.h" -static NSString *const ALICLOUD_HTTPDNS_ROOT_DIR_NAME = @"HTTPDNS"; -static NSString *const ALICLOUD_HTTPDNS_HOST_CACHE_DIR_NAME = @"HostCache"; +static NSString *const Trust_HTTPDNS_ROOT_DIR_NAME = @"HTTPDNS"; +static NSString *const Trust_HTTPDNS_HOST_CACHE_DIR_NAME = @"HostCache"; static dispatch_queue_t _fileCacheQueue = 0; @@ -33,7 +33,7 @@ static dispatch_queue_t _fileCacheQueue = 0; + (void)initialize { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - _fileCacheQueue = dispatch_queue_create("com.alibaba.sdk.httpdns.fileCacheQueue", DISPATCH_QUEUE_SERIAL); + _fileCacheQueue = dispatch_queue_create("com.Trust.sdk.httpdns.fileCacheQueue", DISPATCH_QUEUE_SERIAL); }); } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleCenter.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleCenter.h index 247156a..1ad082b 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleCenter.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleCenter.h @@ -21,8 +21,8 @@ @interface HttpdnsScheduleCenter : NSObject -/// 针对多账号场景的调度中心构造方法 -/// 注意:若无需多账号隔离,可继续使用 sharedInstance +/// 针对多账号场景的调度中心构造方? +/// 注意:若无需多账号隔离,可继续使?sharedInstance - (instancetype)initWithAccountId:(NSInteger)accountId; - (void)initRegion:(NSString *)region; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.h index f6a5f91..ad364b9 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.h @@ -1,9 +1,9 @@ // // HttpdnsScheduleExecutor.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/4/11. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.m index 528cb70..4620201 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Scheduler/HttpdnsScheduleExecutor.m @@ -1,9 +1,9 @@ // // HttpdnsScheduleExecutor.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/4/11. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import "HttpdnsScheduleExecutor.h" @@ -94,8 +94,8 @@ if (response.statusCode != 200) { NSDictionary *dict = @{@"ResponseCode": [NSString stringWithFormat:@"%ld", (long)response.statusCode]}; if (pError) { - *pError = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_HTTPS_NO_DATA_ERROR_CODE + *pError = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_HTTPS_NO_DATA_ERROR_CODE userInfo:dict]; } return nil; @@ -118,8 +118,8 @@ } if (pError) { - *pError = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTP_PARSE_JSON_FAILED + *pError = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTP_PARSE_JSON_FAILED userInfo:@{NSLocalizedDescriptionKey: @"Failed to parse JSON response"}]; } if (pError != NULL) { diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.h index f77d7b3..e650bcc 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.h @@ -1,9 +1,9 @@ // // HttpDnsLocker.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by 王贇 on 2023/8/16. -// Copyright © 2023 alibaba-inc.com. All rights reserved. +// Copyright © 2023 trustapp.com. All rights reserved. // #ifndef HttpDnsLocker_h diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.m index db1f9b6..627d8fe 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpDnsLocker.m @@ -1,9 +1,9 @@ // // HttpDnsLocker.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by 王贇 on 2023/8/16. -// Copyright © 2023 alibaba-inc.com. All rights reserved. +// Copyright © 2023 trustapp.com. All rights reserved. // #import "HttpDnsLocker.h" diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.h index b66c5d1..55fcce3 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.h @@ -1,9 +1,9 @@ // // HttpdnsHostObjectInMemoryCache.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/9/28. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -11,10 +11,10 @@ NS_ASSUME_NONNULL_BEGIN -// 这个字典在HTTPDNS中只用于存储HttpdnsHostObject对象,这个对象是整个框架的核心对象,用于缓存和处理域名解析结果 -// 通常从缓存中获得这个对象之后,会根据不同场景改变一些字段的值,而且很可能发生在不同线程中 +// 这个字典在HTTPDNS中只用于存储HttpdnsHostObject对象,这个对象是整个框架的核心对象,用于缓存和处理域名解析结? +// 通常从缓存中获得这个对象之后,会根据不同场景改变一些字段的值,而且很可能发生在不同线程? // 而不同线程从缓存中直接读取共享对象的话,很有可能发生线程竞争的情况,多线程访问某个对象的同一个字段,在swift环境有较高概率发生crash -// 因此,除了确保字典操作的线程安全,拿出对象的时候,也直接copy一个复制对象返回(HttpdnsHostObject对象实现了NSCopying协议) +// 因此,除了确保字典操作的线程安全,拿出对象的时候,也直接copy一个复制对象返?HttpdnsHostObject对象实现了NSCopying协议) @interface HttpdnsHostObjectInMemoryCache : NSObject - (void)setHostObject:(HttpdnsHostObject *)object forCacheKey:(NSString *)key; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.m index cb0fca2..49857cb 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsHostObjectInMemoryCache.m @@ -1,9 +1,9 @@ // // HttpdnsHostObjectInMemoryCache.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/9/28. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import "HttpdnsHostObjectInMemoryCache.h" diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsIPQualityDetector.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsIPQualityDetector.h index 68f074d..6b33f7a 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsIPQualityDetector.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsIPQualityDetector.h @@ -1,9 +1,9 @@ // // HttpdnsIPQualityDetector.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2025/3/13. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import @@ -11,10 +11,10 @@ NS_ASSUME_NONNULL_BEGIN /** - * IP质量检测回调 - * @param cacheKey 缓存键 + * IP质量检测回? + * @param cacheKey 缓存? * @param ip IP地址 - * @param costTime 连接耗时(毫秒),-1表示连接失败 + * @param costTime 连接耗时(毫秒)?1表示连接失败 */ typedef void(^HttpdnsIPQualityCallback)(NSString *cacheKey, NSString *ip, NSInteger costTime); @@ -32,10 +32,10 @@ typedef void(^HttpdnsIPQualityCallback)(NSString *cacheKey, NSString *ip, NSInte /** * 调度一个IP连接质量检测任务,不会阻塞当前线程 - * @param cacheKey 缓存键,通常是域名 + * @param cacheKey 缓存键,通常是域? * @param ip 要检测的IP地址 - * @param port 连接端口,如果为nil则默认使用80 - * @param callback 检测完成后的回调 + * @param port 连接端口,如果为nil则默认使?0 + * @param callback 检测完成后的回? */ - (void)scheduleIPQualityDetection:(NSString *)cacheKey ip:(NSString *)ip @@ -45,12 +45,12 @@ typedef void(^HttpdnsIPQualityCallback)(NSString *cacheKey, NSString *ip, NSInte #pragma mark - Methods exposed for testing /** - * 执行IP连接质量检测 - * @param cacheKey 缓存键,通常是域名 + * 执行IP连接质量检? + * @param cacheKey 缓存键,通常是域? * @param ip 要检测的IP地址 - * @param port 连接端口,如果为nil则默认使用80 - * @param callback 检测完成后的回调 - * @note 此方法主要用于测试 + * @param port 连接端口,如果为nil则默认使?0 + * @param callback 检测完成后的回? + * @note 此方法主要用于测? */ - (void)executeDetection:(NSString *)cacheKey ip:(NSString *)ip @@ -58,21 +58,21 @@ typedef void(^HttpdnsIPQualityCallback)(NSString *cacheKey, NSString *ip, NSInte callback:(HttpdnsIPQualityCallback)callback; /** - * 建立TCP连接并测量连接时间 + * 建立TCP连接并测量连接时? * @param ip 要连接的IP地址 * @param port 连接端口 - * @return 连接耗时(毫秒),-1表示连接失败 - * @note 此方法主要用于测试 + * @return 连接耗时(毫秒)?1表示连接失败 + * @note 此方法主要用于测? */ - (NSInteger)tcpConnectToIP:(NSString *)ip port:(int)port; /** - * 添加待处理任务 - * @param cacheKey 缓存键,通常是域名 + * 添加待处理任? + * @param cacheKey 缓存键,通常是域? * @param ip 要检测的IP地址 * @param port 连接端口 - * @param callback 检测完成后的回调 - * @note 此方法主要用于测试 + * @param callback 检测完成后的回? + * @note 此方法主要用于测? */ - (void)addPendingTask:(NSString *)cacheKey ip:(NSString *)ip @@ -80,14 +80,14 @@ typedef void(^HttpdnsIPQualityCallback)(NSString *cacheKey, NSString *ip, NSInte callback:(HttpdnsIPQualityCallback)callback; /** - * 处理待处理任务队列 - * @note 此方法主要用于测试 + * 处理待处理任务队? + * @note 此方法主要用于测? */ - (void)processPendingTasksIfNeeded; /** * 处理所有待处理任务 - * @note 此方法主要用于测试 + * @note 此方法主要用于测? */ - (void)processPendingTasks; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsReachability.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsReachability.m index 5de3369..2d9fa9f 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsReachability.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsReachability.m @@ -463,7 +463,7 @@ static void TMReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkRea return HttpdnsReachableVia5G; } } - // 默认以使用最广泛的4G兜底 + // 默认以使用最广泛?G兜底 return HttpdnsReachableVia4G; #endif } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsUtil.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsUtil.m index a1c3c6c..a1d9a3f 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsUtil.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNS/Utils/HttpdnsUtil.m @@ -222,8 +222,8 @@ /** 生成sessionId - App打开生命周期只生成一次,不做持久化 - sessionId为12位,采用base62编码 + App打开生命周期只生成一次,不做持久? + sessionId?2位,采用base62编码 */ + (NSString *)generateSessionID { static NSString *sessionId = nil; @@ -256,11 +256,11 @@ + (NSData *)encryptDataAESCBC:(NSData *)plaintext withKey:(NSData *)key error:(NSError **)error { - // 检查输入参数 + // 检查输入参? if (plaintext == nil || [plaintext length] == 0 || key == nil || [key length] != kCCKeySizeAES128) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_ENCRYPT_INVALID_PARAMS_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_ENCRYPT_INVALID_PARAMS_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Invalid input parameters"}]; } return nil; @@ -271,18 +271,18 @@ int result = SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, iv.mutableBytes); if (result != 0) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_ENCRYPT_RANDOM_IV_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_ENCRYPT_RANDOM_IV_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Failed to generate random IV"}]; } return nil; } - // 计算加密后的数据长度 (可能需要填充) + // 计算加密后的数据长度 (可能需要填? size_t bufferSize = [plaintext length] + kCCBlockSizeAES128; size_t encryptedSize = 0; - // 创建输出缓冲区 + // 创建输出缓冲? NSMutableData *cipherData = [NSMutableData dataWithLength:bufferSize]; // 执行加密 @@ -301,17 +301,17 @@ if (cryptStatus != kCCSuccess) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_ENCRYPT_FAILED_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_ENCRYPT_FAILED_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Encryption failed with status: %d", cryptStatus]}]; } return nil; } - // 调整加密数据的长度,只保留实际加密内容 + // 调整加密数据的长度,只保留实际加密内? [cipherData setLength:encryptedSize]; - // 将IV和加密数据合并在一起 + // 将IV和加密数据合并在一? NSMutableData *resultData = [NSMutableData dataWithData:iv]; [resultData appendData:cipherData]; @@ -338,7 +338,7 @@ return nil; } - // 移除可能存在的空格 + // 移除可能存在的空? NSString *cleanedString = [hexString stringByReplacingOccurrencesOfString:@" " withString:@""]; // 确保字符串长度为偶数 @@ -391,25 +391,25 @@ + (NSData *)decryptDataAESCBC:(NSData *)ciphertext withKey:(NSData *)key error:(NSError **)error { - // 检查输入参数 + // 检查输入参? if (ciphertext == nil || [ciphertext length] <= kCCBlockSizeAES128 || key == nil || [key length] != kCCKeySizeAES128) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_ENCRYPT_INVALID_PARAMS_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_ENCRYPT_INVALID_PARAMS_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: @"Invalid input parameters for decryption"}]; } return nil; } - // 提取IV(前16字节)和实际的密文 + // 提取IV(前16字节)和实际的密? NSData *iv = [ciphertext subdataWithRange:NSMakeRange(0, kCCBlockSizeAES128)]; NSData *actualCiphertext = [ciphertext subdataWithRange:NSMakeRange(kCCBlockSizeAES128, ciphertext.length - kCCBlockSizeAES128)]; - // 计算解密后可能的缓冲区大小 + // 计算解密后可能的缓冲区大? size_t bufferSize = actualCiphertext.length + kCCBlockSizeAES128; size_t decryptedSize = 0; - // 创建输出缓冲区 + // 创建输出缓冲? NSMutableData *decryptedData = [NSMutableData dataWithLength:bufferSize]; // 执行解密 @@ -427,14 +427,14 @@ if (cryptStatus != kCCSuccess) { if (error) { - *error = [NSError errorWithDomain:ALICLOUD_HTTPDNS_ERROR_DOMAIN - code:ALICLOUD_HTTPDNS_ENCRYPT_FAILED_ERROR_CODE + *error = [NSError errorWithDomain:Trust_HTTPDNS_ERROR_DOMAIN + code:Trust_HTTPDNS_ENCRYPT_FAILED_ERROR_CODE userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Decryption failed with status: %d", cryptStatus]}]; } return nil; } - // 调整解密数据的长度,只保留实际解密内容 + // 调整解密数据的长度,只保留实际解密内? [decryptedData setLength:decryptedSize]; return decryptedData; @@ -453,14 +453,14 @@ if (dnsService.ttlDelegate && [dnsService.ttlDelegate respondsToSelector:@selector(httpdnsHost:ipType:ttl:)]) { if ([self isNotEmptyArray:[hostObject getV4Ips]]) { - int64_t customV4TTL = [dnsService.ttlDelegate httpdnsHost:host ipType:AlicloudHttpDNS_IPTypeV4 ttl:hostObject.v4ttl]; + int64_t customV4TTL = [dnsService.ttlDelegate httpdnsHost:host ipType:TrustHttpDNS_IPTypeV4 ttl:hostObject.v4ttl]; if (customV4TTL > 0) { hostObject.v4ttl = customV4TTL; } } if ([self isNotEmptyArray:[hostObject getV6Ips]]) { - int64_t customV6TTL = [dnsService.ttlDelegate httpdnsHost:host ipType:AlicloudHttpDNS_IPTypeV6 ttl:hostObject.v6ttl]; + int64_t customV6TTL = [dnsService.ttlDelegate httpdnsHost:host ipType:TrustHttpDNS_IPTypeV6 ttl:hostObject.v6ttl]; if (customV6TTL > 0) { hostObject.v6ttl = customV6TTL; } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.h index 7be6447..8c892cc 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.h @@ -1,9 +1,9 @@ // // AppDelegate.h -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // Created by junmo on 2018/8/3. -// Copyright © 2018年 alibaba-inc.com. All rights reserved. +// Copyright © 2018?trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.m index 8bbe862..ee7b066 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/AppDelegate.m @@ -1,9 +1,9 @@ // // AppDelegate.m -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // Created by junmo on 2018/8/3. -// Copyright © 2018年 alibaba-inc.com. All rights reserved. +// Copyright © 2018?trustapp.com. All rights reserved. // #import "AppDelegate.h" diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.h index 8bc2745..14bbe35 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.h @@ -1,6 +1,6 @@ // // DemoConfigLoader.h -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // @author Created by Claude Code on 2025-10-05 // diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.m index 5ee10fe..b9abafc 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoConfigLoader.m @@ -1,6 +1,6 @@ // // DemoConfigLoader.m -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // @author Created by Claude Code on 2025-10-05 // @@ -30,7 +30,7 @@ return self; } -// 复杂逻辑:配置加载顺序为 Bundle > 环境变量;并对 accountID 进行有效性校验 +// 复杂逻辑:配置加载顺序为 Bundle > 环境变量;并?accountID 进行有效性校? - (void)loadConfig { _accountID = 0; _secretKey = @""; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoHttpdnsScenario.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoHttpdnsScenario.h index c7a5b00..8e0840e 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoHttpdnsScenario.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoHttpdnsScenario.h @@ -1,6 +1,6 @@ // // DemoHttpdnsScenario.h -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // @author Created by Claude Code on 2025-10-23 // diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.h index 0072d34..c5237b6 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.h @@ -1,6 +1,6 @@ // // DemoLogViewController.h -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // @author Created by Claude Code on 2025-10-05 // diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.m index 780fc5c..be23e42 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoLogViewController.m @@ -1,6 +1,6 @@ // // DemoLogViewController.m -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // @author Created by Claude Code on 2025-10-05 // diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoResolveModel.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoResolveModel.h index be49176..751f721 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoResolveModel.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoResolveModel.h @@ -1,6 +1,6 @@ // // DemoResolveModel.h -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // @author Created by Claude Code on 2025-10-05 // diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoViewController.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoViewController.h index d3c9135..5b71d66 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoViewController.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/DemoViewController.h @@ -1,6 +1,6 @@ // // DNSDemoViewController.h -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // @author Created by Claude Code on 2025-10-05 // diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/main.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/main.m index b0f20a0..d196729 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/main.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTestDemo/main.m @@ -1,9 +1,9 @@ // // main.m -// AlicloudHttpDNSTestDemo +// TrustHttpDNSTestDemo // // Created by junmo on 2018/8/3. -// Copyright © 2018年 alibaba-inc.com. All rights reserved. +// Copyright © 2018?trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/DB/DBTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/DB/DBTest.m index 7c13597..aa6f995 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/DB/DBTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/DB/DBTest.m @@ -1,9 +1,9 @@ // // DBTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2025/3/15. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CacheKeyFunctionTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CacheKeyFunctionTest.m index 7c5e5f7..bb03930 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CacheKeyFunctionTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CacheKeyFunctionTest.m @@ -1,9 +1,9 @@ // // CacheKeyFunctionTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/6/12. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -70,7 +70,7 @@ static NSString *sdnsHost = @"sdns1.onlyforhttpdnstest.run.place"; // 清空缓存 [self.httpdns.requestManager cleanAllHostMemoryCache]; - // 从db再加载到缓存中 + // 从db再加载到缓存? [self.httpdns.requestManager syncLoadCacheFromDbToMemory]; HttpdnsResult *result = [self.httpdns resolveHostSyncNonBlocking:testHost byIpType:HttpdnsQueryIPTypeIpv4]; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CustomTTLTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CustomTTLTest.m index 42c413f..f0197ca 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CustomTTLTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/CustomTTLTest.m @@ -1,9 +1,9 @@ // // CustomTTLAndCleanCacheTest.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by xuyecan on 2024/6/17. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -38,8 +38,8 @@ static int TEST_CUSTOM_TTL_SECOND = 3; [super tearDown]; } -- (int64_t)httpdnsHost:(NSString *)host ipType:(AlicloudHttpDNS_IPType)ipType ttl:(int64_t)ttl { - // 为了在并发测试中域名快速过期,将ttl设置为3秒 +- (int64_t)httpdnsHost:(NSString *)host ipType:(TrustHttpDNS_IPType)ipType ttl:(int64_t)ttl { + // 为了在并发测试中域名快速过期,将ttl设置?? NSString *testHost = hostNameIpPrefixMap.allKeys.firstObject; if ([host isEqual:testHost]) { return TEST_CUSTOM_TTL_SECOND; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/EnableReuseExpiredIpTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/EnableReuseExpiredIpTest.m index d0f9df4..c61e26f 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/EnableReuseExpiredIpTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/EnableReuseExpiredIpTest.m @@ -1,9 +1,9 @@ // // EnableReuseExpiredIpTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/5/28. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -39,8 +39,8 @@ static int ttlForTest = 3; self.currentTimeStamp = [[NSDate date] timeIntervalSince1970]; } -- (int64_t)httpdnsHost:(NSString *)host ipType:(AlicloudHttpDNS_IPType)ipType ttl:(int64_t)ttl { - // 在测试中域名快速过期 +- (int64_t)httpdnsHost:(NSString *)host ipType:(TrustHttpDNS_IPType)ipType ttl:(int64_t)ttl { + // 在测试中域名快速过? return ttlForTest; } @@ -73,7 +73,7 @@ static int ttlForTest = 3; XCTAssertTrue([result2.host isEqualToString:host]); XCTAssertGreaterThan(result2.ttl, 0); XCTAssertLessThanOrEqual(result2.ttl, ttlForTest); - // 因为运行复用过期解析结果,因此这里获得的一定是已经过期的 + // 因为运行复用过期解析结果,因此这里获得的一定是已经过期? XCTAssertGreaterThan([[NSDate date] timeIntervalSince1970], result2.lastUpdatedTimeInterval + result2.ttl); NSString *firstIp2 = [result2 firstIpv4Address]; XCTAssertTrue([firstIp2 hasPrefix:ipPrefix]); @@ -81,13 +81,13 @@ static int ttlForTest = 3; // 等待第二次解析触发的请求完成 [NSThread sleepForTimeInterval:1]; - // 再次使用nonblocking方法解析,此时应该已经拿到有效结果 + // 再次使用nonblocking方法解析,此时应该已经拿到有效结? HttpdnsResult *result3 = [self.httpdns resolveHostSyncNonBlocking:host byIpType:HttpdnsQueryIPTypeIpv4]; XCTAssertNotNil(result3); XCTAssertTrue([result3.host isEqualToString:host]); XCTAssertGreaterThan(result3.ttl, 0); XCTAssertLessThanOrEqual(result3.ttl, ttlForTest); - // 有效结果必定未过期 + // 有效结果必定未过? XCTAssertLessThan([[NSDate date] timeIntervalSince1970], result3.lastUpdatedTimeInterval + result3.ttl); NSString *firstIp3 = [result3 firstIpv4Address]; XCTAssertTrue([firstIp3 hasPrefix:ipPrefix]); diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/HttpdnsHostObjectTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/HttpdnsHostObjectTest.m index f27d164..619b74b 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/HttpdnsHostObjectTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/HttpdnsHostObjectTest.m @@ -1,9 +1,9 @@ // // HttpdnsHostObjectTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2025/3/14. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import @@ -26,19 +26,19 @@ [super tearDown]; } -#pragma mark - 基本属性测试 +#pragma mark - 基本属性测? - (void)testHostObjectProperties { // 创建一个HttpdnsHostObject实例 HttpdnsHostObject *hostObject = [[HttpdnsHostObject alloc] init]; - // 设置基本属性 + // 设置基本属? hostObject.host = @"example.com"; hostObject.ttl = 60; hostObject.queryTimes = 1; hostObject.clientIP = @"192.168.1.1"; - // 验证属性值 + // 验证属性? XCTAssertEqualObjects(hostObject.host, @"example.com", @"host属性应该被正确设置"); XCTAssertEqual(hostObject.ttl, 60, @"ttl属性应该被正确设置"); XCTAssertEqual(hostObject.queryTimes, 1, @"queryTimes属性应该被正确设置"); @@ -51,13 +51,13 @@ // 创建一个HttpdnsIpObject实例 HttpdnsIpObject *ipObject = [[HttpdnsIpObject alloc] init]; - // 设置基本属性 + // 设置基本属? ipObject.ip = @"1.2.3.4"; ipObject.ttl = 300; ipObject.priority = 10; - ipObject.detectRT = 50; // 测试新添加的detectRT属性 + ipObject.detectRT = 50; // 测试新添加的detectRT属? - // 验证属性值 + // 验证属性? XCTAssertEqualObjects(ipObject.ip, @"1.2.3.4", @"ip属性应该被正确设置"); XCTAssertEqual(ipObject.ttl, 300, @"ttl属性应该被正确设置"); XCTAssertEqual(ipObject.priority, 10, @"priority属性应该被正确设置"); @@ -68,18 +68,18 @@ // 创建一个HttpdnsIpObject实例 HttpdnsIpObject *ipObject = [[HttpdnsIpObject alloc] init]; - // 测试默认值 + // 测试默认? XCTAssertEqual(ipObject.detectRT, -1, @"detectRT的默认值应该是-1"); - // 测试设置检测时间 + // 测试设置检测时? [ipObject setDetectRT:100]; XCTAssertEqual(ipObject.detectRT, 100, @"detectRT应该被正确设置为100"); - // 测试设置为负值 + // 测试设置为负? [ipObject setDetectRT:-5]; XCTAssertEqual(ipObject.detectRT, -1, @"设置负值时detectRT应该被设置为-1"); - // 测试设置为0 + // 测试设置? [ipObject setDetectRT:0]; XCTAssertEqual(ipObject.detectRT, 0, @"detectRT应该被正确设置为0"); } @@ -102,15 +102,15 @@ ipv6Object.ttl = 600; ipv6Object.detectRT = 80; - // 添加IP对象到主机对象 + // 添加IP对象到主机对? [hostObject addIpv4:ipv4Object]; [hostObject addIpv6:ipv6Object]; - // 验证IP对象是否被正确添加 - XCTAssertEqual(hostObject.ipv4List.count, 1, @"应该有1个IPv4对象"); - XCTAssertEqual(hostObject.ipv6List.count, 1, @"应该有1个IPv6对象"); + // 验证IP对象是否被正确添? + XCTAssertEqual(hostObject.ipv4List.count, 1, @"应该?个IPv4对象"); + XCTAssertEqual(hostObject.ipv6List.count, 1, @"应该?个IPv6对象"); - // 验证IP对象的属性 + // 验证IP对象的属? HttpdnsIpObject *retrievedIpv4 = hostObject.ipv4List.firstObject; XCTAssertEqualObjects(retrievedIpv4.ip, @"1.2.3.4", @"IPv4地址应该正确"); XCTAssertEqual(retrievedIpv4.detectRT, 50, @"IPv4的detectRT应该正确"); @@ -127,7 +127,7 @@ HttpdnsHostObject *hostObject = [[HttpdnsHostObject alloc] init]; hostObject.host = @"example.com"; - // 创建多个IP对象,具有不同的检测时间 + // 创建多个IP对象,具有不同的检测时? HttpdnsIpObject *ip1 = [[HttpdnsIpObject alloc] init]; ip1.ip = @"1.1.1.1"; ip1.detectRT = 100; @@ -142,7 +142,7 @@ HttpdnsIpObject *ip4 = [[HttpdnsIpObject alloc] init]; ip4.ip = @"4.4.4.4"; - ip4.detectRT = -1; // 未检测 + ip4.detectRT = -1; // 未检? // 添加IP对象到主机对象(顺序不重要) [hostObject addIpv4:ip1]; @@ -155,11 +155,11 @@ // 验证排序结果 // 预期顺序:ip2(50ms) -> ip1(100ms) -> ip3(200ms) -> ip4(-1ms) - XCTAssertEqual(sortedIps.count, 4, @"应该有4个IP对象"); - XCTAssertEqualObjects(sortedIps[0].ip, @"2.2.2.2", @"检测时间最短的IP应该排在第一位"); - XCTAssertEqualObjects(sortedIps[1].ip, @"1.1.1.1", @"检测时间第二短的IP应该排在第二位"); - XCTAssertEqualObjects(sortedIps[2].ip, @"3.3.3.3", @"检测时间第三短的IP应该排在第三位"); - XCTAssertEqualObjects(sortedIps[3].ip, @"4.4.4.4", @"未检测的IP应该排在最后"); + XCTAssertEqual(sortedIps.count, 4, @"应该?个IP对象"); + XCTAssertEqualObjects(sortedIps[0].ip, @"2.2.2.2", @"检测时间最短的IP应该排在第一?); + XCTAssertEqualObjects(sortedIps[1].ip, @"1.1.1.1", @"检测时间第二短的IP应该排在第二?); + XCTAssertEqualObjects(sortedIps[2].ip, @"3.3.3.3", @"检测时间第三短的IP应该排在第三?); + XCTAssertEqualObjects(sortedIps[3].ip, @"4.4.4.4", @"未检测的IP应该排在最?); } -@end \ No newline at end of file +@end diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ManuallyCleanCacheTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ManuallyCleanCacheTest.m index c2603d7..097d680 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ManuallyCleanCacheTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ManuallyCleanCacheTest.m @@ -1,9 +1,9 @@ // // ManuallyCleanCacheTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/6/17. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/MultithreadCorrectnessTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/MultithreadCorrectnessTest.m index 419470c..47d1873 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/MultithreadCorrectnessTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/MultithreadCorrectnessTest.m @@ -1,9 +1,9 @@ // // MultithreadCorrectnessTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/5/26. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -36,7 +36,7 @@ [super tearDown]; } -// 非阻塞接口不能阻塞调用线程 +// 非阻塞接口不能阻塞调用线? - (void)testNoneBlockingMethodShouldNotBlock { HttpdnsRequestManager *requestManager = self.httpdns.requestManager; HttpdnsRequestManager *mockedScheduler = OCMPartialMock(requestManager); @@ -132,7 +132,7 @@ OCMStub([mockResolver resolve:[OCMArg any] error:(NSError * __autoreleasing *)[OCMArg anyPointer]]) .ignoringNonObjectArgs() .andDo(^(NSInvocation *invocation) { - // 第一次调用,阻塞1.5秒 + // 第一次调用,阻塞1.5? [NSThread sleepForTimeInterval:1.5]; [invocation setReturnValue:&mockResolverHostObjects]; }); @@ -146,7 +146,7 @@ [self.httpdns resolveHostSync:ipv4OnlyHost byIpType:HttpdnsQueryIPTypeIpv4]; }); - // 确保第一个请求已经开始 + // 确保第一个请求已经开? [NSThread sleepForTimeInterval:0.5]; NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970]; @@ -156,7 +156,7 @@ dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 第二次请求,由于是同一个域名,所以它应该等待第一个请求的返回 // 第一个请求返回后,第二个请求不应该再次请求,而是直接从缓存中读取到结果,返回 - // 所以它的等待时间接近1秒 + // 所以它的等待时间接?? HttpdnsResult *result = [self.httpdns resolveHostSync:ipv4OnlyHost byIpType:HttpdnsQueryIPTypeIpv4]; XCTAssertNotNil(result); XCTAssertTrue([result.host isEqualToString:ipv4OnlyHost]); @@ -171,7 +171,7 @@ XCTAssert(elapsedTime >= 1, @"elapsedTime should be more than 1s, but is %f", elapsedTime); XCTAssert(elapsedTime <= 1.5, @"elapsedTime should not be more than 1.5s, but is %f", elapsedTime); - // TODO 这里暂时无法跑过,因为现在锁的机制,会导致第二个请求也要去请求 + // TODO 这里暂时无法跑过,因为现在锁的机制,会导致第二个请求也要去请? // XCTAssert(elapsedTime < 4.1, @"elapsedTime should be less than 4.1s, but is %f", elapsedTime); } @@ -191,7 +191,7 @@ // 第一次调用,返回异常 @throw [NSException exceptionWithName:@"TestException" reason:@"TestException" userInfo:nil]; } else { - // 第二次调用 + // 第二次调? [NSThread sleepForTimeInterval:0.4]; [invocation setReturnValue:&mockResolverHostObjects]; } @@ -206,7 +206,7 @@ [self.httpdns resolveHostSync:ipv4OnlyHost byIpType:HttpdnsQueryIPTypeIpv4]; }); - // 确保第一个请求已经开始 + // 确保第一个请求已经开? [NSThread sleepForTimeInterval:0.2]; NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970]; @@ -215,8 +215,8 @@ dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 第二次请求,由于是同一个域名,所以它应该等待第一个请求的返回 - // 第一个请求失败后,第二个请求从缓存拿不到结果,应该再次请求 - // 所以它等待的时间将是约5秒 + // 第一个请求失败后,第二个请求从缓存拿不到结果,应该再次请? + // 所以它等待的时间将是约5? HttpdnsResult *result = [self.httpdns resolveHostSync:ipv4OnlyHost byIpType:HttpdnsQueryIPTypeIpv4]; XCTAssertNotNil(result); XCTAssertTrue([result.host isEqualToString:ipv4OnlyHost]); @@ -232,7 +232,7 @@ XCTAssert(elapsedTime < 0.8, @"elapsedTime should be less than 0.8s, but is %f", elapsedTime); } -// 同步接口设置最大等待时间 +// 同步接口设置最大等待时? - (void)testSyncMethodSetBlockTimeout { HttpdnsRequestManager *requestManager = self.httpdns.requestManager; [self.httpdns cleanAllHostCache]; @@ -266,7 +266,7 @@ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); } -// 限制设置的等待时间在一个合理范围,目前是0.5 - 5秒 +// 限制设置的等待时间在一个合理范围,目前?.5 - 5? - (void)testLimitResolveTimeoutRange { HttpdnsRequest *request = [HttpdnsRequest new]; request.host = ipv4OnlyHost; @@ -285,7 +285,7 @@ XCTAssertEqual(request.resolveTimeoutInSecond, 3.5); } -// 设置异步回调接口的最大回调等待时间 +// 设置异步回调接口的最大回调等待时? - (void)testAsyncMethodSetBlockTimeout { HttpdnsRequestManager *requestManager = self.httpdns.requestManager; [self.httpdns cleanAllHostCache]; @@ -318,7 +318,7 @@ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); } -// 多线程状态下每个线程的等待时间 +// 多线程状态下每个线程的等待时? - (void)testMultiThreadSyncMethodMaxBlockingTime { HttpdnsRequestManager *requestManager = self.httpdns.requestManager; [self.httpdns cleanAllHostCache]; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/PresetCacheAndRetrieveTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/PresetCacheAndRetrieveTest.m index 9104cd1..424f0fe 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/PresetCacheAndRetrieveTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/PresetCacheAndRetrieveTest.m @@ -1,9 +1,9 @@ // // PresetCacheAndRetrieveTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/5/26. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -16,7 +16,7 @@ /** * 由于使用OCMock在连续的测试用例中重复Mock对象(即使每次都已经stopMocking)会有内存错乱的问题, - * 目前还解决不了,所以这个类中的测试case,需要手动单独执行 + * 目前还解决不了,所以这个类中的测试case,需要手动单独执? */ @interface PresetCacheAndRetrieveTest : TestBase @@ -122,7 +122,7 @@ XCTAssertTrue([result.ipv6s[0] isEqualToString:ipv61]); // 请求类型为auto,注意,我们认为ipv6only只存在理论上,比如实验室环境 - // 因此,ipv4的地址是一定会去解析的,auto的作用在于,如果发现网络还支持ipv6,那就多获取ipv6的结果 + // 因此,ipv4的地址是一定会去解析的,auto的作用在于,如果发现网络还支持ipv6,那就多获取ipv6的结? // 因此,这里得到的也是ipv4+ipv6 result = [self.httpdns resolveHostSyncNonBlocking:ipv4AndIpv6Host byIpType:HttpdnsQueryIPTypeAuto]; @@ -180,7 +180,7 @@ XCTAssertTrue([result.ipv6s[0] isEqualToString:ipv61]); } -// ttl、lastLookupTime,ipv4和ipv6是分开处理的 +// ttl、lastLookupTime,ipv4和ipv6是分开处理? - (void)testTTLAndLastLookUpTime { [self presetNetworkEnvAsIpv4AndIpv6]; [self.httpdns cleanAllHostCache]; @@ -195,7 +195,7 @@ hostObject1.lastIPv4LookupTime = currentTimestamp - 1; hostObject1.lastIPv6LookupTime = currentTimestamp - 2; - // 第一次设置缓存 + // 第一次设置缓? [self.httpdns.requestManager mergeLookupResultToManager:hostObject1 host:ipv4AndIpv6Host cacheKey:ipv4AndIpv6Host underQueryIpType:HttpdnsQueryIPTypeBoth]; // auto在当前环境下即请求ipv4和ipv6 @@ -210,10 +210,10 @@ hostObject2.v4ttl = 600; hostObject2.lastIPv4LookupTime = currentTimestamp - 10; - // 单独在缓存更新ipv4地址的相关信息 + // 单独在缓存更新ipv4地址的相关信? [self.httpdns.requestManager mergeLookupResultToManager:hostObject2 host:ipv4AndIpv6Host cacheKey:ipv4AndIpv6Host underQueryIpType:HttpdnsQueryIPTypeIpv4]; - // v4的信息发生变化,v6的信息保持不变 + // v4的信息发生变化,v6的信息保持不? result = [self.httpdns resolveHostSyncNonBlocking:ipv4AndIpv6Host byIpType:HttpdnsQueryIPTypeAuto]; XCTAssertEqual(result.ttl, hostObject2.v4ttl); XCTAssertEqual(result.lastUpdatedTimeInterval, hostObject2.lastIPv4LookupTime); @@ -222,7 +222,7 @@ } // 只缓存ipv4单栈的地址,按请求双栈类型存入,此时会标记该域名没有ipv6地址 -// 按预期,会判断该域名没有ipv6地址,因此不会返回ipv6地址,也不会发请求 +// 按预期,会判断该域名没有ipv6地址,因此不会返回ipv6地址,也不会发请? - (void)testMergeNoIpv6ResultAndGetBoth { [self presetNetworkEnvAsIpv4AndIpv6]; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ResolvingEffectiveHostTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ResolvingEffectiveHostTest.m index fd1b598..73d1a7f 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ResolvingEffectiveHostTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ResolvingEffectiveHostTest.m @@ -1,9 +1,9 @@ // // ResolvingEffectiveHostTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/5/28. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -42,8 +42,8 @@ [super tearDown]; } -- (int64_t)httpdnsHost:(NSString *)host ipType:(AlicloudHttpDNS_IPType)ipType ttl:(int64_t)ttl { - // 为了在并发测试中域名快速过期,将ttl设置为随机1-4秒 +- (int64_t)httpdnsHost:(NSString *)host ipType:(TrustHttpDNS_IPType)ipType ttl:(int64_t)ttl { + // 为了在并发测试中域名快速过期,将ttl设置为随?-4? return arc4random_uniform(4) + 1; } @@ -87,7 +87,7 @@ long long executeStartTimeInMs = [[NSDate date] timeIntervalSince1970] * 1000; HttpdnsResult *result = [self.httpdns resolveHostSyncNonBlocking:host byIpType:HttpdnsQueryIPTypeIpv4]; long long executeEndTimeInMs = [[NSDate date] timeIntervalSince1970] * 1000; - // 非阻塞接口任何情况下不应该阻塞超过30ms + // 非阻塞接口任何情况下不应该阻塞超?0ms if (executeEndTimeInMs - executeStartTimeInMs >= 30) { printf("XCTAssertWillFailed, host: %s, executeTime: %lldms\n", [host UTF8String], executeEndTimeInMs - executeStartTimeInMs); } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV4Test.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV4Test.m index 9780e84..53d48d2 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV4Test.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV4Test.m @@ -1,9 +1,9 @@ // // ScheduleCenterV4Test.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/6/16. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -20,7 +20,7 @@ /** * 由于使用OCMock在连续的测试用例中重复Mock对象(即使每次都已经stopMocking)会有内存错乱的问题, - * 目前还解决不了,所以这个类中的测试case,需要手动单独执行 + * 目前还解决不了,所以这个类中的测试case,需要手动单独执? */ @interface ScheduleCenterV4Test : TestBase diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV6Test.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV6Test.m index 6dab5d0..a2ed420 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV6Test.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/ScheduleCenterV6Test.m @@ -1,9 +1,9 @@ // // ScheduleCenterV6Test.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/6/17. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import #import @@ -18,7 +18,7 @@ /** * 由于使用OCMock在连续的测试用例中重复Mock对象(即使每次都已经stopMocking)会有内存错乱的问题, - * 目前还解决不了,所以这个类中的测试case,需要手动单独执行 + * 目前还解决不了,所以这个类中的测试case,需要手动单独执? */ @interface ScheduleCenterV6Test : TestBase diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/SdnsScenarioTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/SdnsScenarioTest.m index 4dd3c93..330a617 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/SdnsScenarioTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/HighLevelTest/SdnsScenarioTest.m @@ -1,9 +1,9 @@ // // SdnsScenarioTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2024/5/29. -// Copyright © 2024 alibaba-inc.com. All rights reserved. +// Copyright © 2024 trustapp.com. All rights reserved. // #import @@ -41,8 +41,8 @@ static NSString *sdnsHost = @"sdns1.onlyforhttpdnstest.run.place"; self.currentTimeStamp = [[NSDate date] timeIntervalSince1970]; } -- (int64_t)httpdnsHost:(NSString *)host ipType:(AlicloudHttpDNS_IPType)ipType ttl:(int64_t)ttl { - // 在测试中域名快速过期 +- (int64_t)httpdnsHost:(NSString *)host ipType:(TrustHttpDNS_IPType)ipType ttl:(int64_t)ttl { + // 在测试中域名快速过? return ttlForTest; } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/IPDetector/IpDetectorTest.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/IPDetector/IpDetectorTest.m index d428421..067b58e 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/IPDetector/IpDetectorTest.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/IPDetector/IpDetectorTest.m @@ -1,9 +1,9 @@ // // IpDetectorTest.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // Created by xuyecan on 2025/3/14. -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import @@ -25,14 +25,14 @@ [super tearDown]; } -#pragma mark - 单例和基本属性测试 +#pragma mark - 单例和基本属性测? - (void)testSharedInstance { // 测试单例模式 HttpdnsIPQualityDetector *detector1 = [HttpdnsIPQualityDetector sharedInstance]; HttpdnsIPQualityDetector *detector2 = [HttpdnsIPQualityDetector sharedInstance]; - XCTAssertEqual(detector1, detector2, @"单例模式应该返回相同的实例"); + XCTAssertEqual(detector1, detector2, @"单例模式应该返回相同的实?); XCTAssertNotNil(detector1, @"单例实例不应为nil"); } @@ -42,7 +42,7 @@ // 测试连接到有效IP HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; - // 使用公共DNS服务器作为测试目标 + // 使用公共DNS服务器作为测试目? NSInteger costTime = [detector tcpConnectToIP:@"8.8.8.8" port:53]; // 验证连接成功并返回正数耗时 @@ -56,8 +56,8 @@ // 使用无效IP地址 NSInteger costTime = [detector tcpConnectToIP:@"192.168.255.255" port:12345]; - // 验证连接失败并返回-1 - XCTAssertEqual(costTime, -1, @"连接到无效IP应返回-1"); + // 验证连接失败并返?1 + XCTAssertEqual(costTime, -1, @"连接到无效IP应返?1"); } - (void)testTcpConnectWithInvalidParameters { @@ -66,21 +66,21 @@ // 测试空IP NSInteger costTime = [detector tcpConnectToIP:nil port:80]; - XCTAssertEqual(costTime, -1, @"使用nil IP应返回-1"); + XCTAssertEqual(costTime, -1, @"使用nil IP应返?1"); // 测试无效格式的IP costTime = [detector tcpConnectToIP:@"not-an-ip" port:80]; - XCTAssertEqual(costTime, -1, @"使用无效格式IP应返回-1"); + XCTAssertEqual(costTime, -1, @"使用无效格式IP应返?1"); // 测试无效端口 costTime = [detector tcpConnectToIP:@"8.8.8.8" port:-1]; - XCTAssertEqual(costTime, -1, @"使用无效端口应返回-1"); + XCTAssertEqual(costTime, -1, @"使用无效端口应返?1"); } #pragma mark - 任务调度测试 - (void)testScheduleIPQualityDetection { - // 测试调度IP质量检测任务 + // 测试调度IP质量检测任? HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; id detectorMock = OCMPartialMock(detector); @@ -110,7 +110,7 @@ HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; id detectorMock = OCMPartialMock(detector); - // 设置期望:executeDetection方法不应被调用 + // 设置期望:executeDetection方法不应被调? OCMReject([detectorMock executeDetection:[OCMArg any] ip:[OCMArg any] port:[OCMArg any] @@ -146,7 +146,7 @@ HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; id detectorMock = OCMPartialMock(detector); - // 由于无法直接模拟dispatch_semaphore_wait,我们采用另一种方式测试并发限制 + // 由于无法直接模拟dispatch_semaphore_wait,我们采用另一种方式测试并发限? // 模拟scheduleIPQualityDetection内部实现,当调用时直接执行addPendingTask OCMStub([detectorMock scheduleIPQualityDetection:[OCMArg any] ip:[OCMArg any] @@ -163,7 +163,7 @@ [invocation getArgument:&port atIndex:4]; [invocation getArgument:&callback atIndex:5]; - // 直接调用addPendingTask,模拟并发限制已达到的情况 + // 直接调用addPendingTask,模拟并发限制已达到的情? [detector addPendingTask:cacheKey ip:ip port:port callback:callback]; }); @@ -193,14 +193,14 @@ } - (void)testAddPendingTask { - // 测试添加待处理任务 + // 测试添加待处理任? HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; id detectorMock = OCMPartialMock(detector); - // 模拟processPendingTasksIfNeeded方法,避免实际处理任务 + // 模拟processPendingTasksIfNeeded方法,避免实际处理任? OCMStub([detectorMock processPendingTasksIfNeeded]); - // 记录初始待处理任务数量 + // 记录初始待处理任务数? NSUInteger initialCount = [detector pendingTasksCount]; // 添加一个待处理任务 @@ -209,8 +209,8 @@ port:[NSNumber numberWithInt:80] callback:^(NSString *cacheKey, NSString *ip, NSInteger costTime) {}]; - // 验证待处理任务数量增加 - XCTAssertEqual([detector pendingTasksCount], initialCount + 1, @"添加任务后待处理任务数量应增加1"); + // 验证待处理任务数量增? + XCTAssertEqual([detector pendingTasksCount], initialCount + 1, @"添加任务后待处理任务数量应增?"); // 停止模拟 [detectorMock stopMocking]; @@ -221,7 +221,7 @@ HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; id detectorMock = OCMPartialMock(detector); - // 模拟executeDetection方法,避免实际执行检测 + // 模拟executeDetection方法,避免实际执行检? OCMStub([detectorMock executeDetection:[OCMArg any] ip:[OCMArg any] port:[OCMArg any] @@ -233,13 +233,13 @@ port:[NSNumber numberWithInt:80] callback:^(NSString *cacheKey, NSString *ip, NSInteger costTime) {}]; - // 手动触发处理待处理任务 + // 手动触发处理待处理任? [detectorMock processPendingTasksIfNeeded]; - // 给处理任务一些时间 + // 给处理任务一些时? [NSThread sleepForTimeInterval:0.1]; - // 验证待处理任务已被处理 + // 验证待处理任务已被处? XCTAssertEqual([detector pendingTasksCount], 0, @"处理后待处理任务数量应为0"); // 停止模拟 @@ -253,7 +253,7 @@ HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; id detectorMock = OCMPartialMock(detector); - // 模拟tcpConnectToIP方法返回固定值 + // 模拟tcpConnectToIP方法返回固定? OCMStub([detectorMock tcpConnectToIP:@"1.2.3.4" port:80]).andReturn(100); // 创建期望 @@ -265,9 +265,9 @@ port:[NSNumber numberWithInt:80] callback:^(NSString *cacheKey, NSString *ip, NSInteger costTime) { // 验证回调参数 - XCTAssertEqualObjects(cacheKey, @"example.com", @"回调中的cacheKey应正确"); - XCTAssertEqualObjects(ip, @"1.2.3.4", @"回调中的IP应正确"); - XCTAssertEqual(costTime, 100, @"回调中的耗时应正确"); + XCTAssertEqualObjects(cacheKey, @"example.com", @"回调中的cacheKey应正?); + XCTAssertEqualObjects(ip, @"1.2.3.4", @"回调中的IP应正?); + XCTAssertEqual(costTime, 100, @"回调中的耗时应正?); [expectation fulfill]; }]; @@ -296,8 +296,8 @@ port:[NSNumber numberWithInt:80] callback:^(NSString *cacheKey, NSString *ip, NSInteger costTime) { // 验证回调参数 - XCTAssertEqualObjects(cacheKey, @"example.com", @"回调中的cacheKey应正确"); - XCTAssertEqualObjects(ip, @"1.2.3.4", @"回调中的IP应正确"); + XCTAssertEqualObjects(cacheKey, @"example.com", @"回调中的cacheKey应正?); + XCTAssertEqualObjects(ip, @"1.2.3.4", @"回调中的IP应正?); XCTAssertEqual(costTime, -1, @"连接失败时回调中的耗时应为-1"); [expectation fulfill]; @@ -311,11 +311,11 @@ } - (void)testExecuteDetectionWithNilPort { - // 测试执行检测时端口为nil的情况 + // 测试执行检测时端口为nil的情? HttpdnsIPQualityDetector *detector = [HttpdnsIPQualityDetector sharedInstance]; id detectorMock = OCMPartialMock(detector); - // 模拟tcpConnectToIP方法,验证使用默认端口80 + // 模拟tcpConnectToIP方法,验证使用默认端?0 OCMExpect([detectorMock tcpConnectToIP:@"1.2.3.4" port:80]).andReturn(100); // 创建期望 @@ -356,9 +356,9 @@ // 模拟tcpConnectToIP方法,延迟返回以模拟网络延迟 OCMStub([detectorMock tcpConnectToIP:[OCMArg any] port:80]).andDo(^(NSInvocation *invocation) { - // 延迟执行,给GC一个机会 + // 延迟执行,给GC一个机? dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // 设置返回值 + // 设置返回? NSInteger result = 100; [invocation setReturnValue:&result]; }); @@ -373,24 +373,24 @@ port:[NSNumber numberWithInt:80] callback:^(NSString *cacheKey, NSString *ip, NSInteger costTime) { // 验证对象在回调时仍然有效 - XCTAssertEqualObjects(cacheKey, @"example.com", @"回调中的cacheKey应正确"); - XCTAssertEqualObjects(ip, @"1.2.3.4", @"回调中的IP应正确"); + XCTAssertEqualObjects(cacheKey, @"example.com", @"回调中的cacheKey应正?); + XCTAssertEqualObjects(ip, @"1.2.3.4", @"回调中的IP应正?); [expectation fulfill]; }]; - // 清除局部变量的强引用 + // 清除局部变量的强引? tempCacheKey = nil; tempIP = nil; - // 强制GC(注意:在ARC下这不一定会立即触发) + // 强制GC(注意:在ARC下这不一定会立即触发? @autoreleasepool { - // 触发自动释放池 + // 触发自动释放? } // 验证对象没有被释放(应该被executeDetection方法内部强引用) - XCTAssertNotNil(weakCacheKey, @"cacheKey不应被释放"); - XCTAssertNotNil(weakIP, @"IP不应被释放"); + XCTAssertNotNil(weakCacheKey, @"cacheKey不应被释?); + XCTAssertNotNil(weakIP, @"IP不应被释?); // 等待异步操作完成 [self waitForExpectationsWithTimeout:5.0 handler:nil]; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.h index bf6fe14..0e639f3 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.h @@ -1,11 +1,11 @@ // // HttpdnsNWHTTPClientTestBase.h -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // -// 测试基类 - 为所有 HttpdnsNWHTTPClient 测试提供共享的 setup/teardown +// 测试基类 - 为所?HttpdnsNWHTTPClient 测试提供共享?setup/teardown // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.m index 66462f1..2af4850 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestBase.m @@ -1,15 +1,15 @@ // // HttpdnsNWHTTPClientTestBase.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // // 测试基类实现 - 共享的环境配置与清理逻辑 // // 注意:所有测试需要先启动本地 mock server -// 启动命令:cd AlicloudHttpDNSTests/Network && python3 mock_server.py -// 服务端口: +// 启动命令:cd TrustHttpDNSTests/Network && python3 mock_server.py +// 服务端口? // - HTTP: 11080 // - HTTPS: 11443, 11444, 11445, 11446 // @@ -21,18 +21,18 @@ - (void)setUp { [super setUp]; - // 设置环境变量以跳过 TLS 验证(用于本地 mock server 的自签名证书) - // 这是安全的,因为: + // 设置环境变量以跳?TLS 验证(用于本?mock server 的自签名证书? + // 这是安全的,因为? // 1. 仅在测试环境生效 - // 2. 连接限制为本地 loopback (127.0.0.1) - // 3. 不影响生产代码 + // 2. 连接限制为本?loopback (127.0.0.1) + // 3. 不影响生产代? setenv("HTTPDNS_SKIP_TLS_VERIFY", "1", 1); self.client = [[HttpdnsNWHTTPClient alloc] init]; } - (void)tearDown { - // 清除环境变量,避免影响其他测试 + // 清除环境变量,避免影响其他测? unsetenv("HTTPDNS_SKIP_TLS_VERIFY"); self.client = nil; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.h index 1830efb..d6951ee 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.h @@ -1,9 +1,9 @@ // // HttpdnsNWHTTPClientTestHelper.h -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import @@ -12,20 +12,20 @@ NS_ASSUME_NONNULL_BEGIN @interface HttpdnsNWHTTPClientTestHelper : NSObject -#pragma mark - HTTP 响应数据构造 +#pragma mark - HTTP 响应数据构? -// 构造标准 HTTP 响应数据 +// 构造标?HTTP 响应数据 + (NSData *)createHTTPResponseWithStatus:(NSInteger)statusCode statusText:(NSString *)statusText headers:(nullable NSDictionary *)headers body:(nullable NSData *)body; -// 构造 chunked 编码的 HTTP 响应 +// 构?chunked 编码?HTTP 响应 + (NSData *)createChunkedHTTPResponseWithStatus:(NSInteger)statusCode headers:(nullable NSDictionary *)headers chunks:(NSArray *)chunks; -// 构造 chunked 编码的 HTTP 响应(带 trailers) +// 构?chunked 编码?HTTP 响应(带 trailers? + (NSData *)createChunkedHTTPResponseWithStatus:(NSInteger)statusCode headers:(nullable NSDictionary *)headers chunks:(NSArray *)chunks @@ -36,18 +36,18 @@ NS_ASSUME_NONNULL_BEGIN // 编码单个 chunk + (NSData *)encodeChunk:(NSData *)data; -// 编码单个 chunk(带 extension) +// 编码单个 chunk(带 extension? + (NSData *)encodeChunk:(NSData *)data extension:(nullable NSString *)extension; -// 编码终止 chunk(size=0) +// 编码终止 chunk(size=0? + (NSData *)encodeLastChunk; -// 编码终止 chunk(带 trailers) +// 编码终止 chunk(带 trailers? + (NSData *)encodeLastChunkWithTrailers:(NSDictionary *)trailers; #pragma mark - 测试数据生成 -// 生成指定大小的随机数据 +// 生成指定大小的随机数? + (NSData *)randomDataWithSize:(NSUInteger)size; // 生成 JSON 格式的响应体 diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.m index e455e32..48e6b65 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTestHelper.m @@ -1,16 +1,16 @@ // // HttpdnsNWHTTPClientTestHelper.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import "HttpdnsNWHTTPClientTestHelper.h" @implementation HttpdnsNWHTTPClientTestHelper -#pragma mark - HTTP 响应数据构造 +#pragma mark - HTTP 响应数据构? + (NSData *)createHTTPResponseWithStatus:(NSInteger)statusCode statusText:(NSString *)statusText @@ -28,12 +28,12 @@ } } - // 如果有 body 但没有 Content-Length,自动添加 + // 如果?body 但没?Content-Length,自动添? if (body && body.length > 0 && !headers[@"Content-Length"]) { [response appendFormat:@"Content-Length: %lu\r\n", (unsigned long)body.length]; } - // 空行分隔头部和 body + // 空行分隔头部?body [response appendString:@"\r\n"]; NSMutableData *responseData = [[response dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; @@ -144,7 +144,7 @@ + (NSData *)randomDataWithSize:(NSUInteger)size { NSMutableData *data = [NSMutableData dataWithLength:size]; if (SecRandomCopyBytes(kSecRandomDefault, size, data.mutableBytes) != 0) { - // 如果 SecRandom 失败,使用简单的随机数 + // 如果 SecRandom 失败,使用简单的随机? uint8_t *bytes = data.mutableBytes; for (NSUInteger i = 0; i < size; i++) { bytes[i] = arc4random_uniform(256); diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTests.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTests.m index a17cb2e..9ae1def 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTests.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClientTests.m @@ -1,9 +1,9 @@ // // HttpdnsNWHTTPClientTests.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // #import @@ -33,7 +33,7 @@ #pragma mark - A. HTTP 解析逻辑测试 -#pragma mark - A1. Header 解析 (9个) +#pragma mark - A1. Header 解析 (9? // A1.1 正常响应 - (void)testParseHTTPHeaders_ValidResponse_Success { @@ -88,7 +88,7 @@ XCTAssertEqual(result, HttpdnsHTTPHeaderParseResultSuccess); XCTAssertEqual(headers.count, testHeaders.count); - // 验证所有头部都被解析,且 key 转为小写 + // 验证所有头部都被解析,?key 转为小写 XCTAssertEqualObjects(headers[@"content-type"], @"application/json"); XCTAssertEqualObjects(headers[@"content-length"], @"123"); XCTAssertEqualObjects(headers[@"connection"], @"keep-alive"); @@ -96,7 +96,7 @@ XCTAssertEqualObjects(headers[@"cache-control"], @"no-cache"); } -// A1.3 不完整响应 +// A1.3 不完整响? - (void)testParseHTTPHeaders_IncompleteData_ReturnsIncomplete { NSString *incompleteResponse = @"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"; NSData *data = [incompleteResponse dataUsingEncoding:NSUTF8StringEncoding]; @@ -152,10 +152,10 @@ error:&error]; XCTAssertEqual(result, HttpdnsHTTPHeaderParseResultSuccess); - XCTAssertEqualObjects(headers[@"content-type"], @"application/json"); // 应该被 trim + XCTAssertEqualObjects(headers[@"content-type"], @"application/json"); // 应该?trim } -// A1.6 头部没有值 +// A1.6 头部没有? - (void)testParseHTTPHeaders_EmptyHeaderValue_HandledGracefully { NSString *responseWithEmptyValue = @"HTTP/1.1 200 OK\r\nX-Empty-Header:\r\n\r\n"; NSData *data = [responseWithEmptyValue dataUsingEncoding:NSUTF8StringEncoding]; @@ -175,7 +175,7 @@ XCTAssertEqualObjects(headers[@"x-empty-header"], @""); } -// A1.7 状态码非数字 +// A1.7 状态码非数? - (void)testParseHTTPHeaders_NonNumericStatusCode_ReturnsError { NSString *invalidStatusCode = @"HTTP/1.1 ABC OK\r\n\r\n"; NSData *data = [invalidStatusCode dataUsingEncoding:NSUTF8StringEncoding]; @@ -213,7 +213,7 @@ XCTAssertEqual(result, HttpdnsHTTPHeaderParseResultError); } -// A1.9 头部没有冒号被跳过 +// A1.9 头部没有冒号被跳? - (void)testParseHTTPHeaders_HeaderWithoutColon_Skipped { NSString *responseWithInvalidHeader = @"HTTP/1.1 200 OK\r\nInvalidHeader\r\nContent-Type: application/json\r\n\r\n"; NSData *data = [responseWithInvalidHeader dataUsingEncoding:NSUTF8StringEncoding]; @@ -233,7 +233,7 @@ XCTAssertEqualObjects(headers[@"content-type"], @"application/json"); // 有效头部正常解析 } -#pragma mark - A2. Chunked 编码检查 (8个) +#pragma mark - A2. Chunked 编码检?(8? // A2.1 单个 chunk - (void)testCheckChunkedBody_SingleChunk_DetectsComplete { @@ -269,9 +269,9 @@ XCTAssertNil(error); } -// A2.3 不完整 chunk +// A2.3 不完?chunk - (void)testCheckChunkedBody_IncompleteChunk_ReturnsIncomplete { - NSString *incompleteChunkBody = @"5\r\nhel"; // 数据不完整 + NSString *incompleteChunkBody = @"5\r\nhel"; // 数据不完? NSString *response = [NSString stringWithFormat:@"HTTP/1.1 200 OK\r\n\r\n%@", incompleteChunkBody]; NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding]; @@ -285,13 +285,13 @@ XCTAssertEqual(result, HttpdnsHTTPChunkParseResultIncomplete); } -// A2.4 带 chunk extension +// A2.4 ?chunk extension - (void)testCheckChunkedBody_WithChunkExtension_Ignored { NSString *chunkWithExtension = @"5;name=value\r\nhello\r\n0\r\n\r\n"; NSString *response = [NSString stringWithFormat:@"HTTP/1.1 200 OK\r\n\r\n%@", chunkWithExtension]; NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding]; - // headerEndIndex 指向第一个 \r\n\r\n 中的第一个 \r + // headerEndIndex 指向第一?\r\n\r\n 中的第一?\r NSUInteger headerEndIndex = [@"HTTP/1.1 200 OK" length]; NSError *error; @@ -337,9 +337,9 @@ XCTAssertNotNil(error); } -// A2.7 缺少 CRLF 终止符 +// A2.7 缺少 CRLF 终止? - (void)testCheckChunkedBody_MissingCRLFTerminator_ReturnsError { - NSString *missingTerminator = @"5\r\nhelloXX0\r\n\r\n"; // 应该是 hello\r\n + NSString *missingTerminator = @"5\r\nhelloXX0\r\n\r\n"; // 应该?hello\r\n NSString *response = [NSString stringWithFormat:@"HTTP/1.1 200 OK\r\n\r\n%@", missingTerminator]; NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding]; @@ -354,7 +354,7 @@ XCTAssertNotNil(error); } -// A2.8 带 trailers +// A2.8 ?trailers - (void)testCheckChunkedBody_WithTrailers_DetectsComplete { NSString *chunkWithTrailers = @"5\r\nhello\r\n0\r\nX-Trailer: value\r\nX-Custom: test\r\n\r\n"; NSString *response = [NSString stringWithFormat:@"HTTP/1.1 200 OK\r\n\r\n%@", chunkWithTrailers]; @@ -371,7 +371,7 @@ XCTAssertNil(error); } -#pragma mark - A3. Chunked 解码 (2个) +#pragma mark - A3. Chunked 解码 (2? // A3.1 多个 chunks 解码 - (void)testDecodeChunkedBody_MultipleChunks_DecodesCorrectly { @@ -384,7 +384,7 @@ headers:nil chunks:chunks]; - // 提取 chunked body 部分(跳过 headers) + // 提取 chunked body 部分(跳?headers? NSData *headerData = [@"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]; NSData *bodyData = [chunkedData subdataWithRange:NSMakeRange(headerData.length, chunkedData.length - headerData.length)]; @@ -409,7 +409,7 @@ XCTAssertNotNil(error); } -#pragma mark - A4. 完整响应解析 (6个) +#pragma mark - A4. 完整响应解析 (6? // A4.1 Content-Length 响应 - (void)testParseResponse_WithContentLength_ParsesCorrectly { @@ -467,7 +467,7 @@ XCTAssertEqualObjects(bodyString, @"{\"ips\":[]}"); } -// A4.3 空 body +// A4.3 ?body - (void)testParseResponse_EmptyBody_Success { NSData *responseData = [HttpdnsNWHTTPClientTestHelper createHTTPResponseWithStatus:204 statusText:@"No Content" @@ -490,12 +490,12 @@ XCTAssertEqual(body.length, 0); } -// A4.4 Content-Length 不匹配仍然成功 +// A4.4 Content-Length 不匹配仍然成? - (void)testParseResponse_ContentLengthMismatch_LogsButSucceeds { NSData *bodyData = [@"short" dataUsingEncoding:NSUTF8StringEncoding]; NSData *responseData = [HttpdnsNWHTTPClientTestHelper createHTTPResponseWithStatus:200 statusText:@"OK" - headers:@{@"Content-Length": @"100"} // 不匹配 + headers:@{@"Content-Length": @"100"} // 不匹? body:bodyData]; NSInteger statusCode; @@ -509,11 +509,11 @@ body:&body error:&error]; - XCTAssertTrue(success); // 仍然成功,只是日志警告 + XCTAssertTrue(success); // 仍然成功,只是日志警? XCTAssertEqualObjects(body, bodyData); } -// A4.5 空数据返回错误 +// A4.5 空数据返回错? - (void)testParseResponse_EmptyData_ReturnsError { NSData *emptyData = [NSData data]; @@ -532,7 +532,7 @@ XCTAssertNotNil(error); } -// A4.6 只有 headers 无 body +// A4.6 只有 headers ?body - (void)testParseResponse_OnlyHeaders_EmptyBody { NSData *responseData = [HttpdnsNWHTTPClientTestHelper createHTTPResponseWithStatus:200 statusText:@"OK" @@ -556,7 +556,7 @@ XCTAssertEqual(body.length, 0); } -#pragma mark - C. 请求构建测试 (7个) +#pragma mark - C. 请求构建测试 (7? // C.1 基本 GET 请求 - (void)testBuildHTTPRequest_BasicGET_CorrectFormat { @@ -572,7 +572,7 @@ XCTAssertTrue([request hasSuffix:@"\r\n\r\n"]); } -// C.2 带查询参数 +// C.2 带查询参? - (void)testBuildHTTPRequest_WithQueryString_Included { NSURL *url = [NSURL URLWithString:@"http://example.com/path?foo=bar&baz=qux"]; NSString *request = [self.client buildHTTPRequestStringWithURL:url userAgent:nil]; @@ -588,7 +588,7 @@ XCTAssertTrue([request containsString:@"User-Agent: CustomAgent/1.0\r\n"]); } -// C.4 HTTP 默认端口不显示 +// C.4 HTTP 默认端口不显? - (void)testBuildHTTPRequest_HTTPDefaultPort_NotInHost { NSURL *url = [NSURL URLWithString:@"http://example.com:80/"]; NSString *request = [self.client buildHTTPRequestStringWithURL:url userAgent:nil]; @@ -597,7 +597,7 @@ XCTAssertFalse([request containsString:@"Host: example.com:80\r\n"]); } -// C.5 HTTPS 默认端口不显示 +// C.5 HTTPS 默认端口不显? - (void)testBuildHTTPRequest_HTTPSDefaultPort_NotInHost { NSURL *url = [NSURL URLWithString:@"https://example.com:443/"]; NSString *request = [self.client buildHTTPRequestStringWithURL:url userAgent:nil]; @@ -606,7 +606,7 @@ XCTAssertFalse([request containsString:@"Host: example.com:443\r\n"]); } -// C.6 非默认端口显示 +// C.6 非默认端口显? - (void)testBuildHTTPRequest_NonDefaultPort_InHost { NSURL *url = [NSURL URLWithString:@"http://example.com:8080/"]; NSString *request = [self.client buildHTTPRequestStringWithURL:url userAgent:nil]; @@ -627,7 +627,7 @@ #pragma mark - E. TLS 验证测试 (4个占位符) // 注意:TLS 验证测试需要真实的 SecTrustRef 或复杂的 mock -// 这些测试在实际环境中需要根据测试框架调整 +// 这些测试在实际环境中需要根据测试框架调? // E.1 有效证书返回 YES - (void)testEvaluateServerTrust_ValidCertificate_ReturnsYES { @@ -647,10 +647,10 @@ // E.4 指定域名使用 SSL Policy - (void)testEvaluateServerTrust_WithDomain_UsesSSLPolicy { - // 验证使用了 SecPolicyCreateSSL(true, domain) + // 验证使用?SecPolicyCreateSSL(true, domain) } -#pragma mark - F. 边缘情况测试 (5个) +#pragma mark - F. 边缘情况测试 (5? // F.1 超长 URL - (void)testPerformRequest_VeryLongURL_HandlesCorrectly { @@ -666,7 +666,7 @@ XCTAssertTrue(request.length > 5000); } -// F.2 空 User-Agent +// F.2 ?User-Agent - (void)testBuildRequest_EmptyUserAgent_NoUserAgentHeader { NSURL *url = [NSURL URLWithString:@"http://example.com/"]; NSString *requestWithNil = [self.client buildHTTPRequestStringWithURL:url userAgent:nil]; @@ -674,7 +674,7 @@ XCTAssertFalse([requestWithNil containsString:@"User-Agent:"]); } -// F.3 超大响应体 +// F.3 超大响应? - (void)testParseResponse_VeryLargeBody_HandlesCorrectly { NSData *largeBody = [HttpdnsNWHTTPClientTestHelper randomDataWithSize:5 * 1024 * 1024]; NSData *responseData = [HttpdnsNWHTTPClientTestHelper createHTTPResponseWithStatus:200 @@ -697,7 +697,7 @@ XCTAssertEqual(body.length, largeBody.length); } -// F.4 Chunked 解码失败回退到原始数据 +// F.4 Chunked 解码失败回退到原始数? - (void)testParseResponse_ChunkedDecodeFails_FallsBackToRaw { NSString *badChunked = @"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nBAD_CHUNK_DATA"; NSData *responseData = [badChunked dataUsingEncoding:NSUTF8StringEncoding]; @@ -717,7 +717,7 @@ XCTAssertNotNil(body); } -// F.5 连接池 key 生成测试 +// F.5 连接?key 生成测试 - (void)testConnectionPoolKey_DifferentHosts_SeparateKeys { NSString *key1 = [self.client connectionPoolKeyForHost:@"host1.com" port:@"80" useTLS:NO]; NSString *key2 = [self.client connectionPoolKeyForHost:@"host2.com" port:@"80" useTLS:NO]; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_BasicIntegrationTests.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_BasicIntegrationTests.m index 3206048..952e220 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_BasicIntegrationTests.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_BasicIntegrationTests.m @@ -1,12 +1,12 @@ // // HttpdnsNWHTTPClient_BasicIntegrationTests.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // -// 基础集成测试 - 包含基础功能 (G) 和连接复用 (J) 测试组 -// 测试总数:12 个(G:7 + J:5) +// 基础集成测试 - 包含基础功能 (G) 和连接复?(J) 测试? +// 测试总数?2 个(G:7 + J:5? // #import "HttpdnsNWHTTPClientTestBase.h" @@ -134,7 +134,7 @@ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSError *error = nil; - // httpbin.org/stream-bytes 返回 chunked 编码的响应 + // httpbin.org/stream-bytes 返回 chunked 编码的响? HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/stream-bytes/1024" userAgent:@"HttpdnsNWHTTPClient/1.0" timeout:15.0 @@ -145,7 +145,7 @@ XCTAssertEqual(response.statusCode, 200); XCTAssertEqual(response.body.length, 1024, @"Should receive exactly 1024 bytes"); - // 验证 Transfer-Encoding 头 + // 验证 Transfer-Encoding ? NSString *transferEncoding = response.headers[@"transfer-encoding"]; if (transferEncoding) { XCTAssertTrue([transferEncoding containsString:@"chunked"], @"Should use chunked encoding"); @@ -157,7 +157,7 @@ [self waitForExpectations:@[expectation] timeout:20.0]; } -#pragma mark - 额外的集成测试 +#pragma mark - 额外的集成测? // G.6 超时测试(可选) - (void)testIntegration_RequestTimeout_ReturnsError { @@ -165,7 +165,7 @@ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSError *error = nil; - // httpbin.org/delay/10 会延迟 10 秒响应,我们设置 2 秒超时 + // httpbin.org/delay/10 会延?10 秒响应,我们设置 2 秒超? HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/10" userAgent:@"HttpdnsNWHTTPClient/1.0" timeout:2.0 @@ -180,7 +180,7 @@ [self waitForExpectations:@[expectation] timeout:5.0]; } -// G.7 多个不同头部的请求 +// G.7 多个不同头部的请? - (void)testIntegration_CustomHeaders_Reflected { XCTestExpectation *expectation = [self expectationWithDescription:@"Custom headers"]; @@ -194,7 +194,7 @@ XCTAssertNotNil(response); XCTAssertEqual(response.statusCode, 200); - // 解析 JSON 响应,验证我们的 User-Agent 被发送 + // 解析 JSON 响应,验证我们的 User-Agent 被发? NSError *jsonError = nil; NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:response.body options:0 @@ -212,7 +212,7 @@ #pragma mark - J. 连接复用详细测试 -// J.1 连接过期测试(31秒后创建新连接) +// J.1 连接过期测试?1秒后创建新连接) - (void)testConnectionReuse_Expiry31Seconds_NewConnectionCreated { if (getenv("SKIP_SLOW_TESTS")) { return; @@ -252,12 +252,12 @@ [self waitForExpectations:@[expectation] timeout:70.0]; } -// J.2 连接池容量限制验证 +// J.2 连接池容量限制验? - (void)testConnectionReuse_TenRequests_OnlyFourConnectionsKept { XCTestExpectation *expectation = [self expectationWithDescription:@"Pool size limit"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // 连续10个请求 + // 连续10个请? for (NSInteger i = 0; i < 10; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" @@ -267,7 +267,7 @@ XCTAssertTrue(response != nil || error != nil); } - // 等待所有连接归还 + // 等待所有连接归? [NSThread sleepForTimeInterval:1.0]; // 无法直接验证池大小,但如果实现正确,池应自动限制 @@ -330,7 +330,7 @@ error:&httpError]; XCTAssertTrue(httpResponse != nil || httpError != nil); - // HTTPS 请求(应该使用不同的连接池 key) + // HTTPS 请求(应该使用不同的连接?key? NSError *httpsError = nil; HttpdnsNWHTTPClientResponse *httpsResponse = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" userAgent:@"HTTPS" @@ -345,7 +345,7 @@ [self waitForExpectations:@[expectation] timeout:35.0]; } -// J.5 长连接保持测试 +// J.5 长连接保持测? - (void)testConnectionReuse_TwentyRequestsOneSecondApart_ConnectionKeptAlive { if (getenv("SKIP_SLOW_TESTS")) { return; @@ -359,7 +359,7 @@ // 20个请求,间隔1秒(第一个请求立即执行) for (NSInteger i = 0; i < 20; i++) { - // 除第一个请求外,每次请求前等待1秒 + // 除第一个请求外,每次请求前等待1? if (i > 0) { [NSThread sleepForTimeInterval:1.0]; } @@ -381,10 +381,10 @@ } } - // 至少大部分请求应该成功 + // 至少大部分请求应该成? XCTAssertGreaterThan(successCount, 15, @"Most requests should succeed with connection reuse"); - // 验证连接复用:后续请求应该更快(如果使用了keep-alive) + // 验证连接复用:后续请求应该更快(如果使用了keep-alive? if (requestTimes.count >= 10) { double firstRequestTime = [requestTimes[0] doubleValue]; double laterAvgTime = 0; @@ -399,7 +399,7 @@ [expectation fulfill]; }); - // 超时计算: 19秒sleep + 20个请求×~2秒 = 59秒,设置50秒(提前退出机制保证效率) + // 超时计算: 19秒sleep + 20个请求×~2?= 59秒,设置50秒(提前退出机制保证效率) [self waitForExpectations:@[expectation] timeout:50.0]; } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_ConcurrencyTests.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_ConcurrencyTests.m index 785e948..63ebbaa 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_ConcurrencyTests.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_ConcurrencyTests.m @@ -1,12 +1,12 @@ // // HttpdnsNWHTTPClient_ConcurrencyTests.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // -// 并发测试 - 包含并发请求 (H)、竞态条件 (I)、并发多端口 (N) 测试组 -// 测试总数:13 个(H:5 + I:5 + N:3) +// 并发测试 - 包含并发请求 (H)、竞态条?(I)、并发多端口 (N) 测试? +// 测试总数?3 个(H:5 + I:5 + N:3? // #import "HttpdnsNWHTTPClientTestBase.h" @@ -137,7 +137,7 @@ [self waitForExpectations:expectations timeout:40.0]; } -// H.4 高负载压力测试 +// H.4 高负载压力测? - (void)testConcurrency_HighLoad50Concurrent_NoDeadlock { NSInteger concurrentCount = 50; NSMutableArray *expectations = [NSMutableArray array]; @@ -169,7 +169,7 @@ [self waitForExpectations:expectations timeout:60.0]; - // 至少大部分请求应该成功(允许部分失败,因为高负载) + // 至少大部分请求应该成功(允许部分失败,因为高负载? XCTAssertGreaterThan(successCount, concurrentCount * 0.8, @"At least 80%% should succeed"); } @@ -230,14 +230,14 @@ [self waitForExpectations:@[serialExpectation, parallel1, parallel2, parallel3] timeout:60.0]; } -#pragma mark - I. 竞态条件测试 +#pragma mark - I. 竞态条件测? -// I.1 连接池容量测试 +// I.1 连接池容量测? - (void)testRaceCondition_ExceedPoolCapacity_MaxFourConnections { XCTestExpectation *expectation = [self expectationWithDescription:@"Pool capacity test"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // 快速连续发起 10 个请求 + // 快速连续发?10 个请? for (NSInteger i = 0; i < 10; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" @@ -251,7 +251,7 @@ [NSThread sleepForTimeInterval:1.0]; // 注意:无法直接检查池大小(内部实现),只能通过行为验证 - // 如果实现正确,池应自动限制为最多 4 个空闲连接 + // 如果实现正确,池应自动限制为最?4 个空闲连? [expectation fulfill]; }); @@ -276,7 +276,7 @@ timeout:15.0 error:&error]; XCTAssertTrue(response != nil || error != nil); - // 连接在这里自动归还 + // 连接在这里自动归? [expectation fulfill]; }); @@ -284,15 +284,15 @@ [self waitForExpectations:expectations timeout:30.0]; - // 如果没有崩溃或断言失败,说明并发归还处理正确 + // 如果没有崩溃或断言失败,说明并发归还处理正? } -// I.3 获取-归还-再获取竞态 +// I.3 获取-归还-再获取竞? - (void)testRaceCondition_AcquireReturnReacquire_CorrectState { XCTestExpectation *expectation = [self expectationWithDescription:@"Acquire-Return-Reacquire"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // 第一个请求 + // 第一个请? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"First" @@ -300,7 +300,7 @@ error:&error1]; XCTAssertTrue(response1 != nil || error1 != nil); - // 极短暂等待确保连接归还 + // 极短暂等待确保连接归? [NSThread sleepForTimeInterval:0.1]; // 第二个请求应该能复用连接 @@ -317,7 +317,7 @@ [self waitForExpectations:@[expectation] timeout:35.0]; } -// I.4 超时与活跃连接冲突(需要31秒,标记为慢测试) +// I.4 超时与活跃连接冲突(需?1秒,标记为慢测试? - (void)testRaceCondition_ExpiredConnectionPruning_CreatesNewConnection { // 跳过此测试如果环境变量设置了 SKIP_SLOW_TESTS if (getenv("SKIP_SLOW_TESTS")) { @@ -335,7 +335,7 @@ error:&error1]; XCTAssertTrue(response1 != nil || error1 != nil); - // 等待超过30秒超时 + // 等待超过30秒超? [NSThread sleepForTimeInterval:31.0]; // 新请求应该创建新连接(旧连接已过期) @@ -352,19 +352,19 @@ [self waitForExpectations:@[expectation] timeout:70.0]; } -// I.5 错误恢复竞态 +// I.5 错误恢复竞? - (void)testRaceCondition_ErrorRecovery_PoolRemainsHealthy { NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - // 发起一些会失败的请求 + // 发起一些会失败的请? for (NSInteger i = 0; i < 3; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Error %ld", (long)i]]; [expectations addObject:expectation]; dispatch_async(queue, ^{ NSError *error = nil; - // 使用短超时导致失败 + // 使用短超时导致失? HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/5" userAgent:@"ErrorTest" timeout:1.0 @@ -391,9 +391,9 @@ [self waitForExpectations:@[recoveryExpectation] timeout:20.0]; } -#pragma mark - N. 并发多端口测试 +#pragma mark - N. 并发多端口测? -// N.1 并发保持连接(慢测试) +// N.1 并发保持连接(慢测试? - (void)testConcurrentMultiPort_ParallelKeepAlive_IndependentConnections { if (getenv("SKIP_SLOW_TESTS")) { return; @@ -402,7 +402,7 @@ XCTestExpectation *expectation11443 = [self expectationWithDescription:@"Port 11443 keep-alive"]; XCTestExpectation *expectation11444 = [self expectationWithDescription:@"Port 11444 keep-alive"]; - // 线程 1:向端口 11443 发起 10 个请求,间隔 1 秒 + // 线程 1:向端口 11443 发起 10 个请求,间隔 1 ? dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (NSInteger i = 0; i < 10; i++) { if (i > 0) { @@ -417,7 +417,7 @@ [expectation11443 fulfill]; }); - // 线程 2:同时向端口 11444 发起 10 个请求,间隔 1 秒 + // 线程 2:同时向端口 11444 发起 10 个请求,间隔 1 ? dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (NSInteger i = 0; i < 10; i++) { if (i > 0) { @@ -449,7 +449,7 @@ portRequestCounts[port] = @0; } - // 以轮询方式向 4 个端口分发 100 个请求 + // 以轮询方式向 4 个端口分?100 个请? for (NSInteger i = 0; i < totalRequests; i++) { NSNumber *port = ports[i % ports.count]; NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1:%@/get", port]; @@ -466,7 +466,7 @@ } } - // 验证每个端口大约获得 25 个请求 + // 验证每个端口大约获得 25 个请? for (NSNumber *port in ports) { NSInteger count = [portRequestCounts[port] integerValue]; XCTAssertEqual(count, 25, @"Port %@ should receive 25 requests", port); @@ -478,12 +478,12 @@ [self waitForExpectations:@[expectation] timeout:180.0]; } -// N.3 混合负载多端口场景 +// N.3 混合负载多端口场? - (void)testConcurrentMultiPort_MixedLoadPattern_RobustHandling { NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - // 端口 11443:高负载(20 个请求) + // 端口 11443:高负载?0 个请求) for (NSInteger i = 0; i < 20; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Heavy11443 %ld", (long)i]]; [expectations addObject:expectation]; @@ -498,7 +498,7 @@ }); } - // 端口 11444:中负载(10 个请求) + // 端口 11444:中负载?0 个请求) for (NSInteger i = 0; i < 10; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Medium11444 %ld", (long)i]]; [expectations addObject:expectation]; @@ -513,7 +513,7 @@ }); } - // 端口 11445:低负载(5 个请求) + // 端口 11445:低负载? 个请求) for (NSInteger i = 0; i < 5; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Light11445 %ld", (long)i]]; [expectations addObject:expectation]; diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_EdgeCasesAndTimeoutTests.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_EdgeCasesAndTimeoutTests.m index 491297e..74798b9 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_EdgeCasesAndTimeoutTests.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_EdgeCasesAndTimeoutTests.m @@ -1,12 +1,12 @@ // // HttpdnsNWHTTPClient_EdgeCasesAndTimeoutTests.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // -// 边界条件与超时测试 - 包含边界条件 (M)、超时交互 (P) 和 Connection 头部 (R) 测试组 -// 测试总数:15 个(M:4 + P:6 + R:5) +// 边界条件与超时测?- 包含边界条件 (M)、超时交?(P) ?Connection 头部 (R) 测试? +// 测试总数?5 个(M:4 + P:6 + R:5? // #import "HttpdnsNWHTTPClientTestBase.h" @@ -17,14 +17,14 @@ @implementation HttpdnsNWHTTPClient_EdgeCasesAndTimeoutTests -#pragma mark - M. 边界条件与验证测试 +#pragma mark - M. 边界条件与验证测? // M.1 连接复用边界:端口内复用,端口间隔离 - (void)testEdgeCase_ConnectionReuseWithinPortOnly_NotAcross { XCTestExpectation *expectation = [self expectationWithDescription:@"Reuse boundaries"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // 请求 A 到端口 11443 + // 请求 A 到端?11443 CFAbsoluteTime timeA = CFAbsoluteTimeGetCurrent(); NSError *errorA = nil; HttpdnsNWHTTPClientResponse *responseA = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" @@ -34,7 +34,7 @@ CFAbsoluteTime elapsedA = CFAbsoluteTimeGetCurrent() - timeA; XCTAssertNotNil(responseA); - // 请求 B 到端口 11443(应该复用连接,可能更快) + // 请求 B 到端?11443(应该复用连接,可能更快? CFAbsoluteTime timeB = CFAbsoluteTimeGetCurrent(); NSError *errorB = nil; HttpdnsNWHTTPClientResponse *responseB = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" @@ -44,7 +44,7 @@ CFAbsoluteTime elapsedB = CFAbsoluteTimeGetCurrent() - timeB; XCTAssertNotNil(responseB); - // 请求 C 到端口 11444(应该创建新连接) + // 请求 C 到端?11444(应该创建新连接? CFAbsoluteTime timeC = CFAbsoluteTimeGetCurrent(); NSError *errorC = nil; HttpdnsNWHTTPClientResponse *responseC = [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" @@ -54,7 +54,7 @@ CFAbsoluteTime elapsedC = CFAbsoluteTimeGetCurrent() - timeC; XCTAssertNotNil(responseC); - // 请求 D 到端口 11444(应该复用端口 11444 的连接) + // 请求 D 到端?11444(应该复用端?11444 的连接) CFAbsoluteTime timeD = CFAbsoluteTimeGetCurrent(); NSError *errorD = nil; HttpdnsNWHTTPClientResponse *responseD = [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" @@ -76,14 +76,14 @@ [self waitForExpectations:@[expectation] timeout:70.0]; } -// M.2 高端口数量压力测试 +// M.2 高端口数量压力测? - (void)testEdgeCase_HighPortCount_AllPortsManaged { XCTestExpectation *expectation = [self expectationWithDescription:@"High port count"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSArray *ports = @[@11443, @11444, @11445, @11446]; - // 第一轮:向所有端口各发起一个请求 + // 第一轮:向所有端口各发起一个请? for (NSNumber *port in ports) { NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1:%@/get", port]; NSError *error = nil; @@ -94,7 +94,7 @@ XCTAssertNotNil(response, @"First round request to port %@ should succeed", port); } - // 第二轮:再次向所有端口发起请求(应该复用连接) + // 第二轮:再次向所有端口发起请求(应该复用连接? for (NSNumber *port in ports) { NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1:%@/get", port]; NSError *error = nil; @@ -111,7 +111,7 @@ [self waitForExpectations:@[expectation] timeout:120.0]; } -// M.3 并发池访问安全性 +// M.3 并发池访问安全? - (void)testEdgeCase_ConcurrentPoolAccess_NoDataRace { NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); @@ -119,7 +119,7 @@ NSArray *ports = @[@11443, @11444, @11445]; NSInteger requestsPerPort = 5; - // 向三个端口并发发起请求 + // 向三个端口并发发起请? for (NSNumber *port in ports) { for (NSInteger i = 0; i < requestsPerPort; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Port %@ Req %ld", port, (long)i]]; @@ -132,7 +132,7 @@ userAgent:@"ConcurrentAccess" timeout:15.0 error:&error]; - // 如果没有崩溃或断言失败,说明并发访问安全 + // 如果没有崩溃或断言失败,说明并发访问安? XCTAssertTrue(response != nil || error != nil); [expectation fulfill]; }); @@ -160,7 +160,7 @@ error:&error]; } - // 阶段 2:切换到端口 11444,发起多个请求 + // 阶段 2:切换到端口 11444,发起多个请? for (NSInteger i = 0; i < 5; i++) { NSError *error = nil; [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" @@ -169,10 +169,10 @@ error:&error]; } - // 等待超过 30 秒,让端口 11443 的连接过期 + // 等待超过 30 秒,让端?11443 的连接过? [NSThread sleepForTimeInterval:31.0]; - // 阶段 3:验证端口 11444 仍然可用 + // 阶段 3:验证端?11444 仍然可用 NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" userAgent:@"Port11444After" @@ -180,7 +180,7 @@ error:&error1]; XCTAssertNotNil(response1, @"Port 11444 should still work after 11443 expired"); - // 阶段 4:端口 11443 应该创建新连接(旧连接已过期) + // 阶段 4:端?11443 应该创建新连接(旧连接已过期? NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" userAgent:@"Port11443New" @@ -201,11 +201,11 @@ [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 验证初始状态 + // 验证初始状? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 0, @"Pool should be empty initially"); - // 发起超时请求(delay 10s, timeout 1s) + // 发起超时请求(delay 10s, timeout 1s? NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/10" userAgent:@"TimeoutTest" @@ -219,7 +219,7 @@ // 等待异步 returnConnection 完成 [NSThread sleepForTimeInterval:0.5]; - // 验证池状态:超时连接应该被移除 + // 验证池状态:超时连接应该被移? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 0, @"Timed-out connection should be removed from pool"); XCTAssertEqual([self.client totalConnectionCount], 0, @@ -261,7 +261,7 @@ // 等待 returnConnection [NSThread sleepForTimeInterval:0.5]; - // 验证池恢复:现在应该有 1 个连接(来自第二个请求) + // 验证池恢复:现在应该?1 个连接(来自第二个请求) XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 1, @"Pool should have 1 connection from second request"); @@ -274,14 +274,14 @@ XCTAssertNotNil(response3); XCTAssertEqual(response3.statusCode, 200); - // 验证统计:1 个超时(创建后移除)+ 1 个成功(创建)+ 1 个复用 + // 验证统计? 个超时(创建后移除)+ 1 个成功(创建? 1 个复? XCTAssertEqual(self.client.connectionCreationCount, 2, @"Should have created 2 connections (1 timed out, 1 succeeded)"); XCTAssertEqual(self.client.connectionReuseCount, 1, @"Third request should reuse second's connection"); } -// P.3 并发场景:部分超时不影响成功请求的连接复用 +// P.3 并发场景:部分超时不影响成功请求的连接复? - (void)testTimeout_ConcurrentPartialTimeout_SuccessfulRequestsReuse { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; @@ -294,7 +294,7 @@ __block NSInteger successCount = 0; __block NSInteger timeoutCount = 0; - // 发起 10 个请求:5 个正常,5 个超时 + // 发起 10 个请求:5 个正常,5 个超? for (NSInteger i = 0; i < 10; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %ld", (long)i]]; [expectations addObject:expectation]; @@ -305,11 +305,11 @@ NSTimeInterval timeout; if (i % 2 == 0) { - // 偶数:正常请求 + // 偶数:正常请? urlString = @"http://127.0.0.1:11080/get"; timeout = 15.0; } else { - // 奇数:超时请求 + // 奇数:超时请? urlString = @"http://127.0.0.1:11080/delay/10"; timeout = 0.5; } @@ -339,7 +339,7 @@ XCTAssertEqual(successCount, 5, @"5 requests should succeed"); XCTAssertEqual(timeoutCount, 5, @"5 requests should timeout"); - // 验证连接创建数合理(5个成功 + 5个超时 = 最多10个,可能有复用) + // 验证连接创建数合理(5个成?+ 5个超?= 最?0个,可能有复用) XCTAssertGreaterThan(self.client.connectionCreationCount, 0, @"Should have created connections for concurrent requests"); XCTAssertLessThanOrEqual(self.client.connectionCreationCount, 10, @@ -348,8 +348,8 @@ // 等待所有连接归还(异步操作需要更长时间) [NSThread sleepForTimeInterval:2.0]; - // 验证总连接数合理(无泄漏)- 关键验证点 - // 在并发场景下,成功的连接可能已经被关闭(remote close),池可能为空 + // 验证总连接数合理(无泄漏? 关键验证? + // 在并发场景下,成功的连接可能已经被关闭(remote close),池可能为? XCTAssertLessThanOrEqual([self.client totalConnectionCount], 4, @"Total connections should not exceed pool limit (no leak)"); @@ -363,12 +363,12 @@ XCTAssertEqual(recoveryResponse.statusCode, 200, @"Recovery request should succeed"); } -// P.4 连续超时不导致连接泄漏 +// P.4 连续超时不导致连接泄? - (void)testTimeout_ConsecutiveTimeouts_NoConnectionLeak { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 连续发起 10 个超时请求 + // 连续发起 10 个超时请? for (NSInteger i = 0; i < 10; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/10" @@ -381,13 +381,13 @@ [NSThread sleepForTimeInterval:0.2]; } - // 验证池状态:无连接泄漏 + // 验证池状态:无连接泄? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 0, @"Pool should be empty after consecutive timeouts"); XCTAssertEqual([self.client totalConnectionCount], 0, @"No connections should leak"); - // 验证统计:每次都创建新连接(因为超时的被移除) + // 验证统计:每次都创建新连接(因为超时的被移除? XCTAssertEqual(self.client.connectionCreationCount, 10, @"Should have created 10 connections (all timed out and removed)"); XCTAssertEqual(self.client.connectionReuseCount, 0, @@ -403,7 +403,7 @@ dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - // 请求 A:超时(delay 10s, timeout 2s) + // 请求 A:超时(delay 10s, timeout 2s? dispatch_async(queue, ^{ NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/10" @@ -414,9 +414,9 @@ [timeoutExpectation fulfill]; }); - // 请求 B:正常(应该不受 A 阻塞) + // 请求 B:正常(应该不受 A 阻塞? dispatch_async(queue, ^{ - // 稍微延迟,确保 A 先开始 + // 稍微延迟,确?A 先开? [NSThread sleepForTimeInterval:0.1]; CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent(); @@ -430,7 +430,7 @@ XCTAssertNotNil(response, @"Request B should succeed despite A timing out"); XCTAssertEqual(response.statusCode, 200); - // 验证请求 B 没有被请求 A 阻塞(应该很快完成) + // 验证请求 B 没有被请?A 阻塞(应该很快完成) XCTAssertLessThan(elapsed, 5.0, @"Request B should complete quickly, not blocked by A's timeout"); @@ -442,20 +442,20 @@ // 等待连接归还 [NSThread sleepForTimeInterval:0.5]; - // 验证池状态:只有请求 B 的连接 + // 验证池状态:只有请求 B 的连? NSString *poolKey = @"127.0.0.1:11080:tcp"; XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 1, @"Pool should have 1 connection from successful request B"); } -// P.6 多端口场景下的超时隔离 +// P.6 多端口场景下的超时隔? - (void)testTimeout_MultiPort_IsolatedPoolCleaning { [self.client resetPoolStatistics]; NSString *poolKey11443 = @"127.0.0.1:11443:tls"; NSString *poolKey11444 = @"127.0.0.1:11444:tls"; - // 端口 11443:超时请求 + // 端口 11443:超时请? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/delay/10" userAgent:@"Port11443Timeout" @@ -463,7 +463,7 @@ error:&error1]; XCTAssertNil(response1, @"Port 11443 request should timeout"); - // 端口 11444:正常请求 + // 端口 11444:正常请? NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" userAgent:@"Port11444Success" @@ -475,7 +475,7 @@ // 等待连接归还 [NSThread sleepForTimeInterval:0.5]; - // 验证端口隔离:端口 11443 无连接,端口 11444 有 1 个连接 + // 验证端口隔离:端?11443 无连接,端口 11444 ?1 个连? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey11443], 0, @"Port 11443 pool should be empty (timed out)"); XCTAssertEqual([self.client connectionPoolCountForKey:poolKey11444], 1, @@ -485,7 +485,7 @@ XCTAssertEqual([self.client totalConnectionCount], 1, @"Total should be 1 (only from port 11444)"); - // 再次请求端口 11444:应该复用连接 + // 再次请求端口 11444:应该复用连? NSError *error3 = nil; HttpdnsNWHTTPClientResponse *response3 = [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" userAgent:@"Port11444Reuse" @@ -501,7 +501,7 @@ #pragma mark - R. Connection 头部处理测试 -// R.1 Connection: close 导致连接被立即失效 +// R.1 Connection: close 导致连接被立即失? - (void)testConnectionHeader_Close_ConnectionInvalidated { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; @@ -522,7 +522,7 @@ XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 0, @"Connection with 'Connection: close' header should be invalidated and not returned to pool"); - // 请求 2:应该创建新连接(第一个连接已失效) + // 请求 2:应该创建新连接(第一个连接已失效? NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/connection-test?mode=keep-alive" userAgent:@"KeepAliveTest" @@ -531,7 +531,7 @@ XCTAssertNotNil(response2); XCTAssertEqual(response2.statusCode, 200); - // 验证统计:创建了 2 个连接(第一个被 close,第二个正常) + // 验证统计:创建了 2 个连接(第一个被 close,第二个正常? XCTAssertEqual(self.client.connectionCreationCount, 2, @"Should have created 2 connections (first closed by server)"); XCTAssertEqual(self.client.connectionReuseCount, 0, @@ -559,7 +559,7 @@ XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 1, @"Connection with 'Connection: keep-alive' should be returned to pool"); - // 请求 2:应该复用第一个连接 + // 请求 2:应该复用第一个连? NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/connection-test?mode=keep-alive" userAgent:@"KeepAlive2" @@ -568,7 +568,7 @@ XCTAssertNotNil(response2); XCTAssertEqual(response2.statusCode, 200); - // 验证统计:只创建了 1 个连接,第二个请求复用了它 + // 验证统计:只创建?1 个连接,第二个请求复用了? XCTAssertEqual(self.client.connectionCreationCount, 1, @"Should have created only 1 connection"); XCTAssertEqual(self.client.connectionReuseCount, 1, @@ -592,7 +592,7 @@ // 等待异步 returnConnection 完成 [NSThread sleepForTimeInterval:0.5]; - // 验证:连接不在池中(Proxy-Connection: close 应该失效连接) + // 验证:连接不在池中(Proxy-Connection: close 应该失效连接? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 0, @"Connection with 'Proxy-Connection: close' header should be invalidated"); @@ -605,7 +605,7 @@ XCTAssertNotNil(response2); XCTAssertEqual(response2.statusCode, 200); - // 验证统计:创建了 2 个连接 + // 验证统计:创建了 2 个连? XCTAssertEqual(self.client.connectionCreationCount, 2, @"Should have created 2 connections (first closed by proxy header)"); XCTAssertEqual(self.client.connectionReuseCount, 0, @@ -617,7 +617,7 @@ [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 测试 1:CONNECTION: CLOSE (全大写) + // 测试 1:CONNECTION: CLOSE (全大? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/connection-test?mode=close-uppercase" userAgent:@"UppercaseTest" @@ -628,11 +628,11 @@ [NSThread sleepForTimeInterval:0.5]; - // 验证:连接不在池中(大写 CLOSE 也应生效) + // 验证:连接不在池中(大写 CLOSE 也应生效? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 0, @"'CONNECTION: CLOSE' (uppercase) should also close connection"); - // 测试 2:Connection: Close (混合大小写) + // 测试 2:Connection: Close (混合大小? NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/connection-test?mode=close-mixed" userAgent:@"MixedCaseTest" @@ -654,7 +654,7 @@ @"No reuse for any closed connections"); } -// R.5 并发场景:混合 close 和 keep-alive +// R.5 并发场景:混?close ?keep-alive - (void)testConnectionHeader_ConcurrentMixed_CloseAndKeepAliveIsolated { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; @@ -667,7 +667,7 @@ __block NSInteger closeCount = 0; __block NSInteger keepAliveCount = 0; - // 发起 10 个请求:5 个 close,5 个 keep-alive + // 发起 10 个请求:5 ?close? ?keep-alive for (NSInteger i = 0; i < 10; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %ld", (long)i]]; [expectations addObject:expectation]; @@ -711,23 +711,23 @@ XCTAssertEqual(closeCount, 5, @"5 close requests should succeed"); XCTAssertEqual(keepAliveCount, 5, @"5 keep-alive requests should succeed"); - // 等待所有连接归还 + // 等待所有连接归? [NSThread sleepForTimeInterval:1.0]; // 验证池状态: - // - close 连接全部被失效(不在池中) - // - keep-alive 连接可能在池中(取决于并发时序和 remote close) - // - 关键是:总数不超过 4(池限制),无泄漏 + // - close 连接全部被失效(不在池中? + // - keep-alive 连接可能在池中(取决于并发时序和 remote close? + // - 关键是:总数不超?4(池限制),无泄? NSInteger poolSize = [self.client connectionPoolCountForKey:poolKey]; XCTAssertLessThanOrEqual(poolSize, 4, @"Pool size should not exceed limit (no leak from close connections)"); // 验证统计:close 连接不应该被复用 - // 创建数应该 >= 6 (至少 5 个 close + 1 个 keep-alive,因为 close 不能复用) + // 创建数应?>= 6 (至少 5 ?close + 1 ?keep-alive,因?close 不能复用) XCTAssertGreaterThanOrEqual(self.client.connectionCreationCount, 6, @"Should have created at least 6 connections (5 close + at least 1 keep-alive)"); - // 后续请求验证池仍然健康 + // 后续请求验证池仍然健? NSError *recoveryError = nil; HttpdnsNWHTTPClientResponse *recoveryResponse = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"RecoveryTest" diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_PoolManagementTests.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_PoolManagementTests.m index 4977c99..30070ce 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_PoolManagementTests.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_PoolManagementTests.m @@ -1,12 +1,12 @@ // // HttpdnsNWHTTPClient_PoolManagementTests.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // -// 连接池管理测试 - 包含多端口隔离 (K)、端口池耗尽 (L)、池验证 (O)、空闲超时 (S) 测试组 -// 测试总数:16 个(K:5 + L:3 + O:3 + S:5) +// 连接池管理测?- 包含多端口隔?(K)、端口池耗尽 (L)、池验证 (O)、空闲超?(S) 测试? +// 测试总数?6 个(K:5 + L:3 + O:3 + S:5? // #import "HttpdnsNWHTTPClientTestBase.h" @@ -17,9 +17,9 @@ @implementation HttpdnsNWHTTPClient_PoolManagementTests -#pragma mark - K. 多端口连接隔离测试 +#pragma mark - K. 多端口连接隔离测? -// K.1 不同 HTTPS 端口使用不同连接池 +// K.1 不同 HTTPS 端口使用不同连接? - (void)testMultiPort_DifferentHTTPSPorts_SeparatePoolKeys { XCTestExpectation *expectation = [self expectationWithDescription:@"Different ports use different pools"]; @@ -42,7 +42,7 @@ XCTAssertNotNil(response2, @"First request to port 11444 should succeed"); XCTAssertEqual(response2.statusCode, 200); - // 再次请求端口 11443(应该复用之前的连接) + // 再次请求端口 11443(应该复用之前的连接? NSError *error3 = nil; HttpdnsNWHTTPClientResponse *response3 = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" userAgent:@"Port11443Again" @@ -57,7 +57,7 @@ [self waitForExpectations:@[expectation] timeout:50.0]; } -// K.2 三个不同 HTTPS 端口的并发请求 +// K.2 三个不同 HTTPS 端口的并发请? - (void)testMultiPort_ConcurrentThreePorts_AllSucceed { NSInteger requestsPerPort = 10; NSArray *ports = @[@11443, @11444, @11445]; @@ -97,17 +97,17 @@ XCTAssertEqual(successCount, ports.count * requestsPerPort, @"All 30 requests should succeed"); } -// K.3 快速切换端口模式 +// K.3 快速切换端口模? - (void)testMultiPort_SequentialPortSwitching_ConnectionReusePerPort { XCTestExpectation *expectation = [self expectationWithDescription:@"Sequential port switching"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSArray *urls = @[ - @"https://127.0.0.1:11443/get", // 第一次访问 11443 - @"https://127.0.0.1:11444/get", // 第一次访问 11444 - @"https://127.0.0.1:11445/get", // 第一次访问 11445 - @"https://127.0.0.1:11443/get", // 第二次访问 11443(应复用) - @"https://127.0.0.1:11444/get", // 第二次访问 11444(应复用) + @"https://127.0.0.1:11443/get", // 第一次访?11443 + @"https://127.0.0.1:11444/get", // 第一次访?11444 + @"https://127.0.0.1:11445/get", // 第一次访?11445 + @"https://127.0.0.1:11443/get", // 第二次访?11443(应复用? + @"https://127.0.0.1:11444/get", // 第二次访?11444(应复用? ]; NSMutableArray *responseTimes = [NSMutableArray array]; @@ -140,7 +140,7 @@ XCTestExpectation *expectation = [self expectationWithDescription:@"Per-port pool limits"]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // 向端口 11443 发送 10 个请求 + // 向端?11443 发?10 个请? for (NSInteger i = 0; i < 10; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" @@ -150,7 +150,7 @@ XCTAssertTrue(response != nil || error != nil); } - // 向端口 11444 发送 10 个请求(应该有独立的池) + // 向端?11444 发?10 个请求(应该有独立的池) for (NSInteger i = 0; i < 10; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" @@ -163,7 +163,7 @@ // 等待连接归还 [NSThread sleepForTimeInterval:1.0]; - // 验证两个端口都仍然可用 + // 验证两个端口都仍然可? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" userAgent:@"Verify11443" @@ -193,7 +193,7 @@ NSInteger totalRequests = 20; NSInteger successCount = 0; - // 交错请求:依次循环访问所有端口 + // 交错请求:依次循环访问所有端? for (NSInteger i = 0; i < totalRequests; i++) { NSNumber *port = ports[i % ports.count]; NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1:%@/get", port]; @@ -219,7 +219,7 @@ #pragma mark - L. 基于端口的池耗尽测试 -// L.1 四个端口同时承载高负载 +// L.1 四个端口同时承载高负? - (void)testPoolExhaustion_FourPortsSimultaneous_AllSucceed { NSInteger requestsPerPort = 10; NSArray *ports = @[@11443, @11444, @11445, @11446]; @@ -229,7 +229,7 @@ NSLock *successCountLock = [[NSLock alloc] init]; __block NSInteger successCount = 0; - // 向 4 个端口各发起 10 个并发请求(共 40 个) + // ?4 个端口各发起 10 个并发请求(?40 个) for (NSNumber *port in ports) { for (NSInteger i = 0; i < requestsPerPort; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Port %@ Request %ld", port, (long)i]]; @@ -256,11 +256,11 @@ [self waitForExpectations:expectations timeout:80.0]; - // 验证成功率 > 95%(允许少量因并发导致的失败) + // 验证成功?> 95%(允许少量因并发导致的失败) XCTAssertGreaterThan(successCount, 38, @"At least 95%% of 40 requests should succeed"); } -// L.2 单个端口耗尽时其他端口不受影响 +// L.2 单个端口耗尽时其他端口不受影? - (void)testPoolExhaustion_SinglePortExhausted_OthersUnaffected { NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); @@ -268,7 +268,7 @@ __block NSInteger port11444SuccessCount = 0; NSLock *countLock = [[NSLock alloc] init]; - // 向端口 11443 发起 20 个并发请求(可能导致池耗尽) + // 向端?11443 发起 20 个并发请求(可能导致池耗尽? for (NSInteger i = 0; i < 20; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Exhaust11443 %ld", (long)i]]; [expectations addObject:expectation]; @@ -283,7 +283,7 @@ }); } - // 同时向端口 11444 发起 5 个请求(应该不受 11443 影响) + // 同时向端?11444 发起 5 个请求(应该不受 11443 影响? for (NSInteger i = 0; i < 5; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Port11444 %ld", (long)i]]; [expectations addObject:expectation]; @@ -316,7 +316,7 @@ XCTAssertEqual(port11444SuccessCount, 5, @"All port 11444 requests should succeed despite 11443 load"); } -// L.3 多端口使用后的连接清理 +// L.3 多端口使用后的连接清? - (void)testPoolExhaustion_MultiPortCleanup_ExpiredConnectionsPruned { if (getenv("SKIP_SLOW_TESTS")) { return; @@ -327,7 +327,7 @@ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSArray *ports = @[@11443, @11444, @11445]; - // 向三个端口各发起一个请求 + // 向三个端口各发起一个请? for (NSNumber *port in ports) { NSString *urlString = [NSString stringWithFormat:@"https://127.0.0.1:%@/get", port]; NSError *error = nil; @@ -338,7 +338,7 @@ XCTAssertTrue(response != nil || error != nil); } - // 等待超过 30 秒,让所有连接过期 + // 等待超过 30 秒,让所有连接过? [NSThread sleepForTimeInterval:31.0]; // 再次向三个端口发起请求(应该创建新连接) @@ -358,14 +358,14 @@ [self waitForExpectations:@[expectation] timeout:80.0]; } -#pragma mark - O. 连接池验证测试(使用新增的检查 API) +#pragma mark - O. 连接池验证测试(使用新增的检?API? -// O.1 综合连接池验证 - 演示所有检查能力 +// O.1 综合连接池验?- 演示所有检查能? - (void)testPoolVerification_ComprehensiveCheck_AllAspectsVerified { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 初始状态:无连接 + // 初始状态:无连? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 0, @"Pool should be empty initially"); XCTAssertEqual([self.client totalConnectionCount], 0, @@ -375,7 +375,7 @@ XCTAssertEqual(self.client.connectionReuseCount, 0, @"Reuse count should be 0 initially"); - // 发送 5 个请求到同一端点 + // 发?5 个请求到同一端点 for (NSInteger i = 0; i < 5; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" @@ -386,7 +386,7 @@ XCTAssertEqual(response.statusCode, 200, @"Request %ld should return 200", (long)i); } - // 验证连接池状态 + // 验证连接池状? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 1, @"Should have exactly 1 connection in pool for key: %@", poolKey); XCTAssertEqual([self.client totalConnectionCount], 1, @@ -398,7 +398,7 @@ XCTAssertEqual(self.client.connectionReuseCount, 4, @"Should reuse connection 4 times"); - // 验证连接复用率 + // 验证连接复用? CGFloat reuseRate = (CGFloat)self.client.connectionReuseCount / (self.client.connectionCreationCount + self.client.connectionReuseCount); XCTAssertGreaterThanOrEqual(reuseRate, 0.8, @@ -417,11 +417,11 @@ NSString *key11443 = @"127.0.0.1:11443:tls"; NSString *key11444 = @"127.0.0.1:11444:tls"; - // 初始:两个池都为空 + // 初始:两个池都为? XCTAssertEqual([self.client connectionPoolCountForKey:key11443], 0); XCTAssertEqual([self.client connectionPoolCountForKey:key11444], 0); - // 向端口 11443 发送 3 个请求 + // 向端?11443 发?3 个请? for (NSInteger i = 0; i < 3; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" @@ -431,13 +431,13 @@ XCTAssertNotNil(response); } - // 验证端口 11443 的池状态 + // 验证端口 11443 的池状? XCTAssertEqual([self.client connectionPoolCountForKey:key11443], 1, @"Port 11443 should have 1 connection"); XCTAssertEqual([self.client connectionPoolCountForKey:key11444], 0, @"Port 11444 should still be empty"); - // 向端口 11444 发送 3 个请求 + // 向端?11444 发?3 个请? for (NSInteger i = 0; i < 3; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"https://127.0.0.1:11444/get" @@ -455,7 +455,7 @@ XCTAssertEqual([self.client totalConnectionCount], 2, @"Total should be 2 connections (one per port)"); - // 验证统计:应该创建了 2 个连接,复用了 4 次 + // 验证统计:应该创建了 2 个连接,复用?4 ? XCTAssertEqual(self.client.connectionCreationCount, 2, @"Should create 2 connections (one per port)"); XCTAssertEqual(self.client.connectionReuseCount, 4, @@ -468,12 +468,12 @@ XCTAssertTrue([allKeys containsObject:key11444], @"Should contain key for port 11444"); } -// O.3 连接池容量限制验证 +// O.3 连接池容量限制验? - (void)testPoolVerification_PoolCapacity_MaxFourConnections { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 发送 10 个连续请求(每个请求都会归还连接到池) + // 发?10 个连续请求(每个请求都会归还连接到池? for (NSInteger i = 0; i < 10; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" @@ -486,12 +486,12 @@ // 等待连接归还 [NSThread sleepForTimeInterval:1.0]; - // 验证池大小不超过 4(kHttpdnsNWHTTPClientMaxIdleConnectionsPerKey) + // 验证池大小不超过 4(kHttpdnsNWHTTPClientMaxIdleConnectionsPerKey? NSUInteger poolSize = [self.client connectionPoolCountForKey:poolKey]; XCTAssertLessThanOrEqual(poolSize, 4, @"Pool size should not exceed 4 (actual: %lu)", (unsigned long)poolSize); - // 验证统计:应该只创建了 1 个连接(因为串行请求,每次都复用) + // 验证统计:应该只创建?1 个连接(因为串行请求,每次都复用? XCTAssertEqual(self.client.connectionCreationCount, 1, @"Should create only 1 connection for sequential requests"); XCTAssertEqual(self.client.connectionReuseCount, 9, @@ -500,12 +500,12 @@ #pragma mark - S. 空闲超时详细测试 -// S.1 混合过期和有效连接 - 选择性清理 +// S.1 混合过期和有效连?- 选择性清? - (void)testIdleTimeout_MixedExpiredValid_SelectivePruning { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 创建第一个连接 + // 创建第一个连? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"ConnectionA" @@ -517,7 +517,7 @@ // 等待连接归还 [NSThread sleepForTimeInterval:0.5]; - // 使用 DEBUG API 获取连接 A 并设置为过期(35 秒前) + // 使用 DEBUG API 获取连接 A 并设置为过期?5 秒前? NSArray *connections = [self.client connectionsInPoolForKey:poolKey]; XCTAssertEqual(connections.count, 1, @"Should have 1 connection in pool"); @@ -525,7 +525,7 @@ NSDate *expiredDate = [NSDate dateWithTimeIntervalSinceNow:-35.0]; [connectionA debugSetLastUsedDate:expiredDate]; - // 创建第二个连接(通过并发请求) + // 创建第二个连接(通过并发请求? NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"ConnectionB" @@ -536,12 +536,12 @@ // 等待归还 [NSThread sleepForTimeInterval:0.5]; - // 验证:应该有 1 个连接(connectionA 过期被移除,connectionB 留下) + // 验证:应该有 1 个连接(connectionA 过期被移除,connectionB 留下? connections = [self.client connectionsInPoolForKey:poolKey]; XCTAssertEqual(connections.count, 1, @"Should have only 1 connection (expired A removed, valid B kept)"); - // 第三个请求应该复用 connectionB + // 第三个请求应该复?connectionB [self.client resetPoolStatistics]; NSError *error3 = nil; HttpdnsNWHTTPClientResponse *response3 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" @@ -550,7 +550,7 @@ error:&error3]; XCTAssertNotNil(response3); - // 验证:复用了 connectionB(没有创建新连接) + // 验证:复用了 connectionB(没有创建新连接? XCTAssertEqual(self.client.connectionCreationCount, 0, @"Should not create new connection (reuse existing valid connection)"); XCTAssertEqual(self.client.connectionReuseCount, 1, @@ -562,7 +562,7 @@ [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 创建第一个连接 + // 创建第一个连? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"Initial" @@ -572,17 +572,17 @@ [NSThread sleepForTimeInterval:0.5]; - // 借出连接并保持 inUse=YES + // 借出连接并保?inUse=YES NSArray *connections = [self.client connectionsInPoolForKey:poolKey]; XCTAssertEqual(connections.count, 1); HttpdnsNWReusableConnection *conn = connections.firstObject; - // 手动设置为 60 秒前(远超 30 秒超时) + // 手动设置?60 秒前(远?30 秒超时) NSDate *veryOldDate = [NSDate dateWithTimeIntervalSinceNow:-60.0]; [conn debugSetLastUsedDate:veryOldDate]; - // 将连接标记为使用中 + // 将连接标记为使用? [conn debugSetInUse:YES]; // 触发清理(通过发起另一个并发请求) @@ -593,7 +593,7 @@ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ connectionsBefore = [self.client totalConnectionCount]; - // 发起请求(会触发 pruneConnectionPool) + // 发起请求(会触发 pruneConnectionPool? NSError *error2 = nil; [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"TriggerPrune" @@ -608,18 +608,18 @@ dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC)); - // 清理:重置 inUse 状态 + // 清理:重?inUse 状? [conn debugSetInUse:NO]; - // 验证:inUse=YES 的连接不应该被清理 - // connectionsBefore = 1 (旧连接), connectionsAfter = 2 (旧连接 + 新连接) + // 验证:inUse=YES 的连接不应该被清? + // connectionsBefore = 1 (旧连?, connectionsAfter = 2 (旧连?+ 新连? XCTAssertEqual(connectionsBefore, 1, @"Should have 1 connection before (in-use protected)"); XCTAssertEqual(connectionsAfter, 2, @"Should have 2 connections after (in-use connection NOT pruned, new connection added)"); } -// S.3 所有连接过期 - 批量清理 +// S.3 所有连接过?- 批量清理 - (void)testIdleTimeout_AllExpired_BulkPruning { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; @@ -645,21 +645,21 @@ [self waitForExpectations:expectations timeout:30.0]; - // 等待所有连接归还 + // 等待所有连接归? [NSThread sleepForTimeInterval:1.0]; - // 验证池已满 + // 验证池已? NSUInteger poolSizeBefore = [self.client connectionPoolCountForKey:poolKey]; XCTAssertGreaterThan(poolSizeBefore, 0, @"Pool should have connections"); - // 将所有连接设置为过期(31 秒前) + // 将所有连接设置为过期?1 秒前? NSArray *connections = [self.client connectionsInPoolForKey:poolKey]; NSDate *expiredDate = [NSDate dateWithTimeIntervalSinceNow:-31.0]; for (HttpdnsNWReusableConnection *conn in connections) { [conn debugSetLastUsedDate:expiredDate]; } - // 发起新请求(触发批量清理) + // 发起新请求(触发批量清理? NSError *errorNew = nil; HttpdnsNWHTTPClientResponse *responseNew = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"AfterBulkExpiry" @@ -677,7 +677,7 @@ @"Pool should have only 1 connection (new one after bulk pruning)"); } -// S.4 过期后池状态验证 +// S.4 过期后池状态验? - (void)testIdleTimeout_PoolStateAfterExpiry_DirectVerification { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; @@ -692,11 +692,11 @@ [NSThread sleepForTimeInterval:0.5]; - // 验证连接在池中 + // 验证连接在池? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 1, @"Pool should have 1 connection"); - // 设置连接为过期 + // 设置连接为过? NSArray *connections = [self.client connectionsInPoolForKey:poolKey]; HttpdnsNWReusableConnection *conn = connections.firstObject; [conn debugSetLastUsedDate:[NSDate dateWithTimeIntervalSinceNow:-31.0]]; @@ -711,7 +711,7 @@ [NSThread sleepForTimeInterval:0.5]; - // 直接验证池状态:过期连接已被移除,新连接已加入 + // 直接验证池状态:过期连接已被移除,新连接已加? NSUInteger poolSizeAfter = [self.client connectionPoolCountForKey:poolKey]; XCTAssertEqual(poolSizeAfter, 1, @"Pool should have 1 connection (expired removed, new added)"); @@ -721,7 +721,7 @@ @"Should have created at least 1 new connection"); } -// S.5 快速过期测试(无需等待)- 演示最佳实践 +// S.5 快速过期测试(无需等待? 演示最佳实? - (void)testIdleTimeout_FastExpiry_NoWaiting { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; @@ -740,7 +740,7 @@ [NSThread sleepForTimeInterval:0.5]; - // 使用 DEBUG 辅助函数模拟 31 秒过期(无需实际等待) + // 使用 DEBUG 辅助函数模拟 31 秒过期(无需实际等待? NSArray *connections = [self.client connectionsInPoolForKey:poolKey]; XCTAssertEqual(connections.count, 1); @@ -766,7 +766,7 @@ CFAbsoluteTime elapsed = CFAbsoluteTimeGetCurrent() - startTime; - // 关键验证:测试应该很快完成(< 5 秒),而非等待 30+ 秒 + // 关键验证:测试应该很快完成(< 5 秒),而非等待 30+ ? XCTAssertLessThan(elapsed, 5.0, @"Fast expiry test should complete quickly (%.1fs) without 30s wait", elapsed); } diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_StateMachineTests.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_StateMachineTests.m index dca42c0..26bfaf1 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_StateMachineTests.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/HttpdnsNWHTTPClient_StateMachineTests.m @@ -1,12 +1,12 @@ // // HttpdnsNWHTTPClient_StateMachineTests.m -// AlicloudHttpDNSTests +// TrustHttpDNSTests // // @author Created by Claude Code on 2025-11-01 -// Copyright © 2025 alibaba-inc.com. All rights reserved. +// Copyright © 2025 trustapp.com. All rights reserved. // -// 状态机测试 - 包含状态机与异常场景 (Q) 测试组 -// 测试总数:17 个(Q:17) +// 状态机测试 - 包含状态机与异常场?(Q) 测试? +// 测试总数?7 个(Q:17? // #import "HttpdnsNWHTTPClientTestBase.h" @@ -17,18 +17,18 @@ @implementation HttpdnsNWHTTPClient_StateMachineTests -#pragma mark - Q. 状态机与异常场景测试 +#pragma mark - Q. 状态机与异常场景测? // Q1.1 池溢出时LRU移除策略验证 - (void)testStateMachine_PoolOverflowLRU_RemovesOldestByLastUsedDate { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 需要并发创建5个连接(串行请求会复用) + // 需要并发创?个连接(串行请求会复用) NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - // 并发发起5个请求 + // 并发发起5个请? for (NSInteger i = 0; i < 5; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %ld", (long)i]]; [expectations addObject:expectation]; @@ -42,15 +42,15 @@ error:&error]; [expectation fulfill]; }); - [NSThread sleepForTimeInterval:0.05]; // 小间隔避免完全同时启动 + [NSThread sleepForTimeInterval:0.05]; // 小间隔避免完全同时启? } [self waitForExpectations:expectations timeout:20.0]; - // 等待所有连接归还 + // 等待所有连接归? [NSThread sleepForTimeInterval:1.0]; - // 验证:池大小 ≤ 4(LRU移除溢出部分) + // 验证:池大小 ?4(LRU移除溢出部分? NSUInteger poolCount = [self.client connectionPoolCountForKey:poolKey]; XCTAssertLessThanOrEqual(poolCount, 4, @"Pool should enforce max 4 connections (LRU)"); @@ -65,7 +65,7 @@ [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 快速连续发起10个请求(测试连接归还的幂等性) + // 快速连续发?0个请求(测试连接归还的幂等性) for (NSInteger i = 0; i < 10; i++) { NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" @@ -78,12 +78,12 @@ // 等待连接归还 [NSThread sleepForTimeInterval:1.0]; - // 验证:池中最多1个连接(因为串行请求复用同一连接) + // 验证:池中最?个连接(因为串行请求复用同一连接? NSUInteger poolCount = [self.client connectionPoolCountForKey:poolKey]; XCTAssertLessThanOrEqual(poolCount, 1, @"Pool should have at most 1 connection (rapid sequential reuse)"); - // 验证:创建次数应该是1(所有请求复用同一连接) + // 验证:创建次数应该是1(所有请求复用同一连接? XCTAssertEqual(self.client.connectionCreationCount, 1, @"Should create only 1 connection for sequential requests"); } @@ -94,7 +94,7 @@ NSString *poolKey11080 = @"127.0.0.1:11080:tcp"; NSString *poolKey11443 = @"127.0.0.1:11443:tls"; - // 向端口11080发起请求 + // 向端?1080发起请求 NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"Port11080" @@ -102,7 +102,7 @@ error:&error1]; XCTAssertNotNil(response1); - // 向端口11443发起请求 + // 向端?1443发起请求 NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"https://127.0.0.1:11443/get" userAgent:@"Port11443" @@ -113,7 +113,7 @@ // 等待连接归还 [NSThread sleepForTimeInterval:0.5]; - // 验证:两个池各自有1个连接 + // 验证:两个池各自?个连? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey11080], 1, @"Port 11080 pool should have 1 connection"); XCTAssertEqual([self.client connectionPoolCountForKey:poolKey11443], 1, @@ -128,7 +128,7 @@ - (void)testInvariant_PoolSize_NeverExceedsLimit { [self.client resetPoolStatistics]; - // 快速连续发起20个请求到同一端点 + // 快速连续发?0个请求到同一端点 for (NSInteger i = 0; i < 20; i++) { NSError *error = nil; [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" @@ -137,7 +137,7 @@ error:&error]; } - // 等待所有连接归还 + // 等待所有连接归? [NSThread sleepForTimeInterval:1.5]; // 验证:每个池的大小不超过4 @@ -149,7 +149,7 @@ key, (unsigned long)poolCount); } - // 验证:总连接数也不超过4(因为只有一个池) + // 验证:总连接数也不超过4(因为只有一个池? XCTAssertLessThanOrEqual([self.client totalConnectionCount], 4, @"Total connections should not exceed 4"); } @@ -162,7 +162,7 @@ NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - // 并发发起15个请求(可能复用连接) + // 并发发起15个请求(可能复用连接? for (NSInteger i = 0; i < 15; i++) { XCTestExpectation *expectation = [self expectationWithDescription:[NSString stringWithFormat:@"Request %ld", (long)i]]; [expectations addObject:expectation]; @@ -182,17 +182,17 @@ // 等待连接归还 [NSThread sleepForTimeInterval:1.0]; - // 验证:池大小 ≤ 4(不变式) + // 验证:池大小 ?4(不变式? NSUInteger poolCount = [self.client connectionPoolCountForKey:poolKey]; XCTAssertLessThanOrEqual(poolCount, 4, @"Pool should not have duplicates (max 4 connections)"); - // 验证:创建的连接数合理(≤15,因为可能有复用) + // 验证:创建的连接数合理(?5,因为可能有复用? XCTAssertLessThanOrEqual(self.client.connectionCreationCount, 15, @"Should not create excessive connections"); } -// Q4.1 边界条件:恰好30秒后连接过期 +// Q4.1 边界条件:恰?0秒后连接过期 - (void)testBoundary_Exactly30Seconds_ConnectionExpired { if (getenv("SKIP_SLOW_TESTS")) { return; @@ -200,7 +200,7 @@ [self.client resetPoolStatistics]; - // 第一个请求 + // 第一个请? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"InitialRequest" @@ -211,7 +211,7 @@ // 等待恰好30.5秒(超过30秒过期时间) [NSThread sleepForTimeInterval:30.5]; - // 第二个请求:应该创建新连接(旧连接已过期) + // 第二个请求:应该创建新连接(旧连接已过期? NSError *error2 = nil; HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"AfterExpiry" @@ -219,18 +219,18 @@ error:&error2]; XCTAssertNotNil(response2); - // 验证:创建了2个连接(旧连接过期,无法复用) + // 验证:创建了2个连接(旧连接过期,无法复用? XCTAssertEqual(self.client.connectionCreationCount, 2, @"Should create 2 connections (first expired after 30s)"); XCTAssertEqual(self.client.connectionReuseCount, 0, @"Should not reuse expired connection"); } -// Q4.2 边界条件:29秒内连接未过期 +// Q4.2 边界条件?9秒内连接未过? - (void)testBoundary_Under30Seconds_ConnectionNotExpired { [self.client resetPoolStatistics]; - // 第一个请求 + // 第一个请? NSError *error1 = nil; HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"InitialRequest" @@ -249,19 +249,19 @@ error:&error2]; XCTAssertNotNil(response2); - // 验证:只创建了1个连接(复用了) + // 验证:只创建?个连接(复用了) XCTAssertEqual(self.client.connectionCreationCount, 1, @"Should create only 1 connection (reused within 30s)"); XCTAssertEqual(self.client.connectionReuseCount, 1, @"Should reuse connection within 30s"); } -// Q4.3 边界条件:恰好4个连接全部保留 +// Q4.3 边界条件:恰?个连接全部保? - (void)testBoundary_ExactlyFourConnections_AllKept { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 并发发起4个请求(使用延迟确保同时在飞行中,创建4个独立连接) + // 并发发起4个请求(使用延迟确保同时在飞行中,创?个独立连接) NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); @@ -272,7 +272,7 @@ dispatch_async(queue, ^{ NSError *error = nil; - // 使用 /delay/2 确保所有请求同时在飞行中 + // 使用 /delay/2 确保所有请求同时在飞行? [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/2" userAgent:[NSString stringWithFormat:@"Request%ld", (long)i] timeout:15.0 @@ -280,7 +280,7 @@ [expectation fulfill]; }); - [NSThread sleepForTimeInterval:0.05]; // 小间隔避免完全同时启动 + [NSThread sleepForTimeInterval:0.05]; // 小间隔避免完全同时启? } [self waitForExpectations:expectations timeout:20.0]; @@ -288,22 +288,22 @@ // 等待连接归还 [NSThread sleepForTimeInterval:1.0]; - // 验证:池恰好有4个连接(全部保留) + // 验证:池恰好?个连接(全部保留? NSUInteger poolCount = [self.client connectionPoolCountForKey:poolKey]; XCTAssertEqual(poolCount, 4, @"Pool should keep all 4 connections (not exceeding limit)"); - // 验证:恰好创建4个连接 + // 验证:恰好创?个连? XCTAssertEqual(self.client.connectionCreationCount, 4, @"Should create exactly 4 connections"); } -// Q1.2 正常状态序列验证 +// Q1.2 正常状态序列验? - (void)testStateMachine_NormalSequence_StateTransitionsCorrect { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 第1步:创建并使用连接 (CREATING → IN_USE → IDLE) + // ?步:创建并使用连?(CREATING ?IN_USE ?IDLE) HttpdnsNWHTTPClientResponse *response1 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"StateTest" timeout:15.0 @@ -312,18 +312,18 @@ [NSThread sleepForTimeInterval:1.0]; // 等待归还 - // 验证:池中有1个连接 + // 验证:池中有1个连? XCTAssertEqual([self.client connectionPoolCountForKey:poolKey], 1, @"Connection should be in pool"); - // 第2步:复用连接 (IDLE → IN_USE → IDLE) + // ?步:复用连接 (IDLE ?IN_USE ?IDLE) HttpdnsNWHTTPClientResponse *response2 = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"StateTest" timeout:15.0 error:nil]; XCTAssertNotNil(response2, @"Second request should reuse connection"); - // 验证:复用计数增加 + // 验证:复用计数增? XCTAssertEqual(self.client.connectionReuseCount, 1, @"Should have reused connection once"); } @@ -333,7 +333,7 @@ [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 发起请求并归还 + // 发起请求并归? [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"InUseTest" timeout:15.0 @@ -364,20 +364,20 @@ [NSThread sleepForTimeInterval:1.0]; - // 获取连接并设置 lastUsedDate 为 nil + // 获取连接并设?lastUsedDate ?nil NSArray *connections = [self.client connectionsInPoolForKey:poolKey]; XCTAssertEqual(connections.count, 1, @"Should have connection"); HttpdnsNWReusableConnection *conn = connections.firstObject; [conn debugSetLastUsedDate:nil]; - // 发起新请求触发 prune(内部应使用 distantPast 处理 nil) + // 发起新请求触?prune(内部应使用 distantPast 处理 nil? HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"NilDateTest" timeout:15.0 error:nil]; - // 验证:不崩溃,正常工作 + // 验证:不崩溃,正常工? XCTAssertNotNil(response, @"Should handle nil lastUsedDate gracefully"); } @@ -386,7 +386,7 @@ [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 发起多个请求(包括成功和超时) + // 发起多个请求(包括成功和超时? for (NSInteger i = 0; i < 3; i++) { [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"InvariantTest" @@ -394,7 +394,7 @@ error:nil]; } - // 发起1个超时请求 + // 发起1个超时请? [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/10" userAgent:@"TimeoutTest" timeout:0.5 @@ -402,7 +402,7 @@ [NSThread sleepForTimeInterval:2.0]; - // 获取池中所有连接 + // 获取池中所有连? NSArray *connections = [self.client connectionsInPoolForKey:poolKey]; // 验证:池中无失效连接 @@ -411,12 +411,12 @@ } } -// Q3.4 lastUsedDate 单调性验证 +// Q3.4 lastUsedDate 单调性验? - (void)testInvariant_LastUsedDate_Monotonic { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 第1次使用 + // ?次使? [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"MonotonicTest" timeout:15.0 @@ -429,10 +429,10 @@ NSDate *date1 = connections1.firstObject.lastUsedDate; XCTAssertNotNil(date1, @"lastUsedDate should be set"); - // 等待1秒确保时间推进 + // 等待1秒确保时间推? [NSThread sleepForTimeInterval:1.0]; - // 第2次使用同一连接 + // ?次使用同一连接 [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"MonotonicTest" timeout:15.0 @@ -449,12 +449,12 @@ @"lastUsedDate should increase after reuse"); } -// Q5.1 超时+池溢出复合场景 +// Q5.1 超时+池溢出复合场? - (void)testCompound_TimeoutDuringPoolOverflow_Handled { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; - // 先填满池(4个成功连接) + // 先填满池?个成功连接) NSMutableArray *expectations = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); @@ -477,9 +477,9 @@ [NSThread sleepForTimeInterval:1.0]; NSUInteger poolCountBefore = [self.client connectionPoolCountForKey:poolKey]; - XCTAssertLessThanOrEqual(poolCountBefore, 4, @"Pool should have ≤4 connections"); + XCTAssertLessThanOrEqual(poolCountBefore, 4, @"Pool should have ? connections"); - // 第5个请求超时 + // ?个请求超? NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [self.client performRequestWithURLString:@"http://127.0.0.1:11080/delay/10" userAgent:@"TimeoutRequest" @@ -491,7 +491,7 @@ [NSThread sleepForTimeInterval:1.0]; - // 验证:超时连接未加入池 + // 验证:超时连接未加入? NSUInteger poolCountAfter = [self.client connectionPoolCountForKey:poolKey]; XCTAssertLessThanOrEqual(poolCountAfter, 4, @"Timed-out connection should not be added to pool"); } @@ -507,15 +507,15 @@ timeout:2.0 error:&error]; - // 验证:请求失败 + // 验证:请求失? XCTAssertNil(response, @"Should fail to connect to invalid port"); - // 验证:无连接加入池 + // 验证:无连接加入? XCTAssertEqual([self.client totalConnectionCount], 0, @"Failed connection should not be added to pool"); } -// Q2.5 多次 invalidate 幂等性 +// Q2.5 多次 invalidate 幂等? - (void)testAbnormal_MultipleInvalidate_Idempotent { [self.client resetPoolStatistics]; NSString *poolKey = @"127.0.0.1:11080:tcp"; @@ -542,11 +542,11 @@ XCTAssertTrue(conn.isInvalidated, @"Connection should be invalidated"); } -// Q5.2 并发 dequeue 竞态测试 +// Q5.2 并发 dequeue 竞态测? - (void)testCompound_ConcurrentDequeueDuringPrune_Safe { [self.client resetPoolStatistics]; - // 在两个端口创建连接 + // 在两个端口创建连? [self.client performRequestWithURLString:@"http://127.0.0.1:11080/get" userAgent:@"RaceTest" timeout:15.0 @@ -562,7 +562,7 @@ // 等待30秒让连接过期 [NSThread sleepForTimeInterval:30.5]; - // 并发触发两个端口的 dequeue(会触发 prune) + // 并发触发两个端口?dequeue(会触发 prune? dispatch_group_t group = dispatch_group_create(); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/MOCK_SERVER.md b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/MOCK_SERVER.md index 7275ae6..7ffda1a 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/MOCK_SERVER.md +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/MOCK_SERVER.md @@ -1,78 +1,78 @@ # HTTP Mock Server for Integration Tests -本目录包含用于 `HttpdnsNWHTTPClient` 集成测试的 HTTP/HTTPS mock server,用于替代 httpbin.org。 +本目录包含用?`HttpdnsNWHTTPClient` 集成测试?HTTP/HTTPS mock server,用于替?httpbin.org? --- -## 为什么需要 Mock Server? +## 为什么需?Mock Server? -1. **可靠性**: httpbin.org 在高并发测试下表现不稳定,经常返回非预期的 HTTP 状态码(如 429 Too Many Requests) +1. **可靠?*: httpbin.org 在高并发测试下表现不稳定,经常返回非预期?HTTP 状态码(如 429 Too Many Requests? 2. **速度**: 本地服务器响应更快,缩短测试执行时间 3. **离线测试**: 无需网络连接即可运行集成测试 -4. **可控性**: 完全掌控测试环境,便于调试和复现问题 +4. **可控?*: 完全掌控测试环境,便于调试和复现问题 --- -## 快速开始 +## 快速开? ### 1. 启动 Mock Server ```bash # 进入测试目录 -cd AlicloudHttpDNSTests/Network +cd TrustHttpDNSTests/Network -# 启动服务器(无需 sudo 权限,使用非特权端口) +# 启动服务器(无需 sudo 权限,使用非特权端口? python3 mock_server.py ``` **注意**: -- **无需 root 权限**(使用非特权端口 11080/11443-11446) +- **无需 root 权限**(使用非特权端口 11080/11443-11446? - 首次运行会自动生成自签名证书 (`server.pem`) -- 按 `Ctrl+C` 停止服务器 +- ?`Ctrl+C` 停止服务? ### 2. 运行集成测试 -在另一个终端窗口: +在另一个终端窗? ```bash -cd ~/Project/iOS/alicloud-ios-sdk-httpdns +cd ~/Project/iOS/Trust-ios-sdk-httpdns -# 运行所有集成测试 +# 运行所有集成测? xcodebuild test \ - -workspace AlicloudHttpDNS.xcworkspace \ - -scheme AlicloudHttpDNSTests \ + -workspace TrustHttpDNS.xcworkspace \ + -scheme TrustHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ - -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests + -only-testing:TrustHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests # 运行单个测试 xcodebuild test \ - -workspace AlicloudHttpDNS.xcworkspace \ - -scheme AlicloudHttpDNSTests \ + -workspace TrustHttpDNS.xcworkspace \ + -scheme TrustHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ - -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests/testConcurrency_ParallelRequestsSameHost_AllSucceed + -only-testing:TrustHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests/testConcurrency_ParallelRequestsSameHost_AllSucceed ``` --- -## 支持的 Endpoints +## 支持?Endpoints -Mock server 实现了以下 httpbin.org 兼容的 endpoints: +Mock server 实现了以?httpbin.org 兼容?endpoints: | Endpoint | 功能 | 示例 | |----------|------|------| -| `GET /get` | 返回请求信息(headers, args, origin) | `http://127.0.0.1:11080/get` | -| `GET /status/{code}` | 返回指定状态码(100-599) | `http://127.0.0.1:11080/status/404` | -| `GET /stream-bytes/{n}` | 返回 chunked 编码的 N 字节数据 | `http://127.0.0.1:11080/stream-bytes/1024` | -| `GET /delay/{seconds}` | 延迟指定秒数后返回(最多10秒) | `http://127.0.0.1:11080/delay/5` | -| `GET /headers` | 返回所有请求头部 | `http://127.0.0.1:11080/headers` | +| `GET /get` | 返回请求信息(headers, args, origin?| `http://127.0.0.1:11080/get` | +| `GET /status/{code}` | 返回指定状态码?00-599?| `http://127.0.0.1:11080/status/404` | +| `GET /stream-bytes/{n}` | 返回 chunked 编码?N 字节数据 | `http://127.0.0.1:11080/stream-bytes/1024` | +| `GET /delay/{seconds}` | 延迟指定秒数后返回(最?0秒) | `http://127.0.0.1:11080/delay/5` | +| `GET /headers` | 返回所有请求头?| `http://127.0.0.1:11080/headers` | | `GET /uuid` | 返回随机 UUID | `http://127.0.0.1:11080/uuid` | | `GET /user-agent` | 返回 User-Agent 头部 | `http://127.0.0.1:11080/user-agent` | **端口配置**: - **HTTP**: `127.0.0.1:11080` -- **HTTPS**: `127.0.0.1:11443`, `11444`, `11445`, `11446`(4个端口用于测试连接池隔离) +- **HTTPS**: `127.0.0.1:11443`, `11444`, `11445`, `11446`?个端口用于测试连接池隔离? -所有 endpoints 在 HTTP 和 HTTPS 端口上均可访问。 +所?endpoints ?HTTP ?HTTPS 端口上均可访问? --- @@ -80,25 +80,25 @@ Mock server 实现了以下 httpbin.org 兼容的 endpoints: ### 架构 -- **HTTP 服务器**: 监听 `127.0.0.1:11080` -- **HTTPS 服务器**: 监听 `127.0.0.1:11443`, `11444`, `11445`, `11446`(4个端口,使用自签名证书) -- **多端口目的**: 测试连接池的端口隔离机制,确保不同端口使用独立的连接池 -- **并发模型**: 多线程(`ThreadingMixIn`),支持高并发请求 +- **HTTP 服务?*: 监听 `127.0.0.1:11080` +- **HTTPS 服务?*: 监听 `127.0.0.1:11443`, `11444`, `11445`, `11446`?个端口,使用自签名证书) +- **多端口目?*: 测试连接池的端口隔离机制,确保不同端口使用独立的连接? +- **并发模型**: 多线程(`ThreadingMixIn`),支持高并发请? ### TLS 证书 -- 自动生成自签名证书(RSA 2048位,有效期 365 天) +- 自动生成自签名证书(RSA 2048位,有效?365 天) - CN (Common Name): `localhost` -- 证书文件: `server.pem`(同时包含密钥和证书) +- 证书文件: `server.pem`(同时包含密钥和证书? **重要**: 集成测试通过环境变量 `HTTPDNS_SKIP_TLS_VERIFY=1` 跳过 TLS 验证,这是安全的,因为: 1. 仅在测试环境生效 -2. 不影响生产代码 -3. 连接限制为本地 loopback (127.0.0.1) +2. 不影响生产代? +3. 连接限制为本?loopback (127.0.0.1) ### 响应格式 -所有 JSON 响应遵循 httpbin.org 格式,例如: +所?JSON 响应遵循 httpbin.org 格式,例? ```json { @@ -131,7 +131,7 @@ XXXXXXXXXX **错误信息**: ``` -✗ 端口 80 已被占用,请关闭占用端口的进程或使用其他端口 +?端口 80 已被占用,请关闭占用端口的进程或使用其他端口 ``` **解决方法**: @@ -147,9 +147,9 @@ sudo lsof -i :443 sudo kill -9 ``` -3. 或修改 mock_server.py 使用其他端口: +3. 或修?mock_server.py 使用其他端口: ```python -# 修改端口号(同时需要更新测试代码中的 URL) +# 修改端口号(同时需要更新测试代码中?URL? run_http_server(port=8080) run_https_server(port=8443) ``` @@ -158,13 +158,13 @@ run_https_server(port=8443) **错误信息**: ``` -✗ 未找到 openssl 命令,请安装 OpenSSL +?未找?openssl 命令,请安装 OpenSSL ``` **解决方法**: ```bash -# macOS (通常已预装) +# macOS (通常已预? brew install openssl # Ubuntu/Debian @@ -174,11 +174,11 @@ sudo apt-get install openssl sudo yum install openssl ``` -### 权限被拒绝 +### 权限被拒? **错误信息**: ``` -✗ 错误: 需要 root 权限以绑定 80/443 端口 +?错误: 需?root 权限以绑?80/443 端口 ``` **解决方法**: @@ -190,21 +190,21 @@ sudo python3 mock_server.py --- -## 切换回 httpbin.org +## 切换?httpbin.org -如需使用真实的 httpbin.org 进行测试(例如验证兼容性): +如需使用真实?httpbin.org 进行测试(例如验证兼容性): 1. 编辑 `HttpdnsNWHTTPClientIntegrationTests.m` -2. 将所有 `127.0.0.1` 替换回 `httpbin.org` -3. 注释掉 setUp/tearDown 中的环境变量设置 +2. 将所?`127.0.0.1` 替换?`httpbin.org` +3. 注释?setUp/tearDown 中的环境变量设置 --- ## 开发与扩展 -### 添加新 Endpoint +### 添加?Endpoint -在 `mock_server.py` 的 `MockHTTPHandler.do_GET()` 方法中添加: +?`mock_server.py` ?`MockHTTPHandler.do_GET()` 方法中添? ```python def do_GET(self): @@ -215,14 +215,14 @@ def do_GET(self): # ... 其他 endpoints def _handle_your_endpoint(self): - """处理自定义 endpoint""" + """处理自定?endpoint""" data = {'custom': 'data'} self._send_json(200, data) ``` ### 调试模式 -取消注释 `log_message` 方法以启用详细日志: +取消注释 `log_message` 方法以启用详细日? ```python def log_message(self, format, *args): @@ -234,20 +234,20 @@ def log_message(self, format, *args): ## 技术栈 - **Python 3.7+** (标准库,无需额外依赖) -- **http.server**: HTTP 服务器实现 +- **http.server**: HTTP 服务器实? - **ssl**: TLS/SSL 支持 -- **socketserver.ThreadingMixIn**: 多线程并发 +- **socketserver.ThreadingMixIn**: 多线程并? --- ## 安全注意事项 -1. **仅用于测试**: 此服务器设计用于本地测试,不适合生产环境 -2. **自签名证书**: HTTPS 使用不受信任的自签名证书 -3. **无身份验证**: 不实现任何身份验证机制 -4. **本地绑定**: 服务器仅绑定到 `127.0.0.1`,不接受外部连接 +1. **仅用于测?*: 此服务器设计用于本地测试,不适合生产环境 +2. **自签名证?*: HTTPS 使用不受信任的自签名证书 +3. **无身份验?*: 不实现任何身份验证机? +4. **本地绑定**: 服务器仅绑定?`127.0.0.1`,不接受外部连接 --- -**最后更新**: 2025-11-01 -**维护者**: Claude Code +**最后更?*: 2025-11-01 +**维护?*: Claude Code diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/README.md b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/README.md index 4cc767e..fe008af 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/README.md +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/README.md @@ -1,62 +1,62 @@ # HttpdnsNWHTTPClient 测试套件 -本目录包含 `HttpdnsNWHTTPClient` 和 `HttpdnsNWReusableConnection` 的完整测试套件。 +本目录包?`HttpdnsNWHTTPClient` ?`HttpdnsNWReusableConnection` 的完整测试套件? ## 测试文件结构 ``` -AlicloudHttpDNSTests/Network/ +TrustHttpDNSTests/Network/ ├── HttpdnsNWHTTPClientTests.m # 主单元测试(44个) -├── HttpdnsNWHTTPClientIntegrationTests.m # 集成测试(7个) -├── HttpdnsNWHTTPClientTestHelper.h/m # 测试辅助工具类 -└── README.md # 本文件 +├── HttpdnsNWHTTPClientIntegrationTests.m # 集成测试?个) +├── HttpdnsNWHTTPClientTestHelper.h/m # 测试辅助工具? +└── README.md # 本文? ``` ## 测试覆盖范围 ### 单元测试 (HttpdnsNWHTTPClientTests.m) -#### A. HTTP 解析逻辑测试 (25个) -- **A1. Header 解析 (9个)** +#### A. HTTP 解析逻辑测试 (25? +- **A1. Header 解析 (9?** - 正常响应解析 - 多个头部字段 - - 不完整数据处理 + - 不完整数据处? - 无效状态行 - - 空格处理与 trim - - 空值头部 + - 空格处理?trim + - 空值头? - 非数字状态码 - 状态码为零 - - 无效头部行 + - 无效头部? -- **A2. Chunked 编码检查 (8个)** +- **A2. Chunked 编码检?(8?** - 单个 chunk - 多个 chunks - - 不完整 chunk + - 不完?chunk - Chunk extension 支持 - 无效十六进制 size - Chunk size 溢出 - - 缺少 CRLF 终止符 - - 带 trailers 的 chunked + - 缺少 CRLF 终止? + - ?trailers ?chunked -- **A3. Chunked 解码 (2个)** +- **A3. Chunked 解码 (2?** - 多个 chunks 正确解码 - 无效格式返回 nil -- **A4. 完整响应解析 (6个)** +- **A4. 完整响应解析 (6?** - Content-Length 响应 - Chunked 编码响应 - - 空 body - - Content-Length 不匹配 - - 空数据错误 - - 只有 headers 无 body + - ?body + - Content-Length 不匹? + - 空数据错? + - 只有 headers ?body -#### C. 请求构建测试 (7个) +#### C. 请求构建测试 (7? - 基本 GET 请求格式 - 查询参数处理 - User-Agent 头部 - HTTP 默认端口处理 - HTTPS 默认端口处理 -- 非默认端口显示 +- 非默认端口显? - 固定头部验证 #### E. TLS 验证测试 (4个占位符) @@ -65,95 +65,95 @@ AlicloudHttpDNSTests/Network/ - 无效证书返回 NO - 指定域名使用 SSL Policy -*注:TLS 测试需要真实的 SecTrustRef 或复杂 mock,当前为占位符* +*注:TLS 测试需要真实的 SecTrustRef 或复?mock,当前为占位? -#### F. 边缘情况测试 (8个) +#### F. 边缘情况测试 (8? - 超长 URL 处理 -- 空 User-Agent -- 超大响应体(5MB) +- ?User-Agent +- 超大响应体(5MB? - Chunked 解码失败回退 -- 连接池 key - 不同 hosts -- 连接池 key - 不同 ports -- 连接池 key - HTTP vs HTTPS +- 连接?key - 不同 hosts +- 连接?key - 不同 ports +- 连接?key - HTTP vs HTTPS ### 集成测试 (HttpdnsNWHTTPClientIntegrationTests.m) -使用 httpbin.org 进行真实网络测试 (22个): +使用 httpbin.org 进行真实网络测试 (22?? -**G. 基础集成测试 (7个)** +**G. 基础集成测试 (7?** - HTTP GET 请求 - HTTPS GET 请求 - HTTP 404 响应 - 连接复用(两次请求) - Chunked 响应处理 - 请求超时测试 -- 自定义头部验证 +- 自定义头部验? -**H. 并发测试 (5个)** -- 并发请求同一主机(10个线程) -- 并发请求不同路径(5个不同endpoint) +**H. 并发测试 (5?** +- 并发请求同一主机?0个线程) +- 并发请求不同路径?个不同endpoint? - 混合 HTTP + HTTPS 并发(各5个线程) - 高负载压力测试(50个并发请求) - 混合串行+并发模式 -**I. 竞态条件测试 (5个)** +**I. 竞态条件测?(5?** - 连接池容量测试(超过4个连接上限) -- 同时归还连接(5个并发) -- 获取-归还-再获取竞态 +- 同时归还连接?个并发) +- 获取-归还-再获取竞? - 超时与活跃连接冲突(需31秒,可跳过) -- 错误恢复后连接池健康状态 +- 错误恢复后连接池健康状? -**J. 高级连接复用测试 (5个)** +**J. 高级连接复用测试 (5?** - 连接过期与清理(31秒,可跳过) - 连接池容量限制验证(10个连续请求) -- 不同路径复用连接(4个不同路径) +- 不同路径复用连接?个不同路径) - HTTP vs HTTPS 使用不同连接池key -- 长连接保持测试(20个请求间隔1秒,可跳过) +- 长连接保持测试(20个请求间?秒,可跳过) ## 运行测试 -### 运行所有单元测试 +### 运行所有单元测? ```bash xcodebuild test \ - -workspace AlicloudHttpDNS.xcworkspace \ - -scheme AlicloudHttpDNSTests \ + -workspace TrustHttpDNS.xcworkspace \ + -scheme TrustHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ - -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientTests + -only-testing:TrustHttpDNSTests/HttpdnsNWHTTPClientTests ``` ### 运行集成测试(需要网络) ```bash xcodebuild test \ - -workspace AlicloudHttpDNS.xcworkspace \ - -scheme AlicloudHttpDNSTests \ + -workspace TrustHttpDNS.xcworkspace \ + -scheme TrustHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ - -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests + -only-testing:TrustHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests ``` ### 运行单个测试 ```bash xcodebuild test \ - -workspace AlicloudHttpDNS.xcworkspace \ - -scheme AlicloudHttpDNSTests \ + -workspace TrustHttpDNS.xcworkspace \ + -scheme TrustHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ - -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientTests/testParseHTTPHeaders_ValidResponse_Success + -only-testing:TrustHttpDNSTests/HttpdnsNWHTTPClientTests/testParseHTTPHeaders_ValidResponse_Success ``` ## 测试辅助工具 ### HttpdnsNWHTTPClientTestHelper -提供以下工具方法: +提供以下工具方法? -#### HTTP 响应构造 +#### HTTP 响应构? ```objc -// 构造标准 HTTP 响应 +// 构造标?HTTP 响应 + (NSData *)createHTTPResponseWithStatus:(NSInteger)statusCode statusText:(NSString *)statusText headers:(NSDictionary *)headers body:(NSData *)body; -// 构造 chunked 响应 +// 构?chunked 响应 + (NSData *)createChunkedHTTPResponseWithStatus:(NSInteger)statusCode headers:(NSDictionary *)headers chunks:(NSArray *)chunks; @@ -175,19 +175,19 @@ xcodebuild test \ | 测试类别 | 测试数量 | 覆盖范围 | |---------|---------|---------| -| HTTP 解析 | 25 | HTTP 头部、Chunked 编码、完整响应 | -| 请求构建 | 7 | URL 处理、头部生成 | -| TLS 验证 | 4 (占位符) | 证书验证 | +| HTTP 解析 | 25 | HTTP 头部、Chunked 编码、完整响?| +| 请求构建 | 7 | URL 处理、头部生?| +| TLS 验证 | 4 (占位? | 证书验证 | | 边缘情况 | 8 | 异常输入、连接池 key | | **单元测试合计** | **43** | - | -| 基础集成测试 (G) | 7 | 真实网络请求、基本场景 | +| 基础集成测试 (G) | 7 | 真实网络请求、基本场?| | 并发测试 (H) | 5 | 多线程并发、高负载 | -| 竞态条件测试 (I) | 5 | 连接池竞态、错误恢复 | -| 连接复用测试 (J) | 5 | 连接过期、长连接、协议隔离 | -| 多端口连接隔离 (K) | 5 | 不同端口独立连接池 | +| 竞态条件测?(I) | 5 | 连接池竞态、错误恢?| +| 连接复用测试 (J) | 5 | 连接过期、长连接、协议隔?| +| 多端口连接隔?(K) | 5 | 不同端口独立连接?| | 端口池耗尽测试 (L) | 3 | 多端口高负载、池隔离 | | 边界条件验证 (M) | 4 | 端口迁移、高端口数量 | -| 并发多端口场景 (N) | 3 | 并行 keep-alive、轮询分配 | +| 并发多端口场?(N) | 3 | 并行 keep-alive、轮询分?| | **集成测试合计** | **37** | - | | **总计** | **80** | - | @@ -195,24 +195,24 @@ xcodebuild test \ 以下测试组涉及复杂的 Mock 场景,可根据需要添加: -### B. 连接池管理测试 (18个) -需要 Mock `HttpdnsNWReusableConnection` 的完整生命周期 +### B. 连接池管理测?(18? +需?Mock `HttpdnsNWReusableConnection` 的完整生命周? -### D. 完整流程测试 (13个) -需要 Mock 连接池和网络层的集成场景 +### D. 完整流程测试 (13? +需?Mock 连接池和网络层的集成场景 ## Mock Server 使用 -集成测试使用本地 mock server (127.0.0.1) 替代 httpbin.org,提供稳定可靠的测试环境。 +集成测试使用本地 mock server (127.0.0.1) 替代 httpbin.org,提供稳定可靠的测试环境? ### 启动 Mock Server ```bash -cd AlicloudHttpDNSTests/Network +cd TrustHttpDNSTests/Network python3 mock_server.py ``` -**注意**:使用非特权端口(11080/11443-11446),无需 `sudo` 权限。 +**注意**:使用非特权端口?1080/11443-11446),无需 `sudo` 权限? ### 运行集成测试 @@ -220,38 +220,38 @@ python3 mock_server.py ```bash xcodebuild test \ - -workspace AlicloudHttpDNS.xcworkspace \ - -scheme AlicloudHttpDNSTests \ + -workspace TrustHttpDNS.xcworkspace \ + -scheme TrustHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ - -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests + -only-testing:TrustHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests ``` -### Mock Server 特性 +### Mock Server 特? - **HTTP**: 监听 `127.0.0.1:11080` -- **HTTPS**: 监听 `127.0.0.1:11443`, `11444`, `11445`, `11446` (自签名证书) -- **多端口目的**: 测试连接池的端口隔离机制 +- **HTTPS**: 监听 `127.0.0.1:11443`, `11444`, `11445`, `11446` (自签名证? +- **多端口目?*: 测试连接池的端口隔离机制 - **并发支持**: 多线程处理,适合并发测试 -- **零延迟**: 本地响应,测试速度快 +- **零延?*: 本地响应,测试速度? 详见 [MOCK_SERVER.md](./MOCK_SERVER.md) ## 注意事项 -1. **集成测试依赖 Mock Server**:`HttpdnsNWHTTPClientIntegrationTests` 使用本地 mock server (127.0.0.1)。测试前需先启动 `mock_server.py`。 +1. **集成测试依赖 Mock Server**:`HttpdnsNWHTTPClientIntegrationTests` 使用本地 mock server (127.0.0.1)。测试前需先启?`mock_server.py`? -2. **慢测试跳过**:部分测试需要等待31秒(测试连接过期),可设置环境变量 `SKIP_SLOW_TESTS=1` 跳过这些测试: +2. **慢测试跳?*:部分测试需要等?1秒(测试连接过期),可设置环境变?`SKIP_SLOW_TESTS=1` 跳过这些测试? - `testRaceCondition_ExpiredConnectionPruning_CreatesNewConnection` - `testConnectionReuse_Expiry31Seconds_NewConnectionCreated` - `testConnectionReuse_TwentyRequestsOneSecondApart_ConnectionKeptAlive` -3. **并发测试容错**:并发和压力测试允许部分失败(例如 H.4 要求80%成功率),因为高负载下仍可能出现网络波动。 +3. **并发测试容错**:并发和压力测试允许部分失败(例?H.4 要求80%成功率),因为高负载下仍可能出现网络波动? -4. **TLS 测试占位符**:E 组 TLS 测试需要真实的 `SecTrustRef` 或高级 mock 框架,当前仅为占位符。 +4. **TLS 测试占位?*:E ?TLS 测试需要真实的 `SecTrustRef` 或高?mock 框架,当前仅为占位符? -5. **新文件添加到 Xcode**:创建的测试文件需要手动添加到 `AlicloudHttpDNSTests` target。 +5. **新文件添加到 Xcode**:创建的测试文件需要手动添加到 `TrustHttpDNSTests` target? -6. **测试数据**:使用 `HttpdnsNWHTTPClientTestHelper` 生成测试数据,确保测试的可重复性。 +6. **测试数据**:使?`HttpdnsNWHTTPClientTestHelper` 生成测试数据,确保测试的可重复性? ## 文件依赖 @@ -263,20 +263,20 @@ xcodebuild test \ ## 贡献指南 -添加新测试时,请遵循: +添加新测试时,请遵循? 1. 命名规范:`test__` 2. 使用 `#pragma mark` 组织测试分组 -3. 添加清晰的注释说明测试目的 -4. 验证测试覆盖率并更新本文档 +3. 添加清晰的注释说明测试目? +4. 验证测试覆盖率并更新本文? --- -**最后更新**: 2025-11-01 +**最后更?*: 2025-11-01 **测试框架**: XCTest + OCMock -**维护者**: Claude Code +**维护?*: Claude Code **更新日志**: -- 2025-11-01: 新增 15 个多端口连接复用测试(K、L、M、N组),测试总数增至 37 个 -- 2025-11-01: Mock server 新增 3 个 HTTPS 端口(11444-11446)用于测试连接池隔离 -- 2025-11-01: 新增本地 mock server,替代 httpbin.org,提供稳定测试环境 +- 2025-11-01: 新增 15 个多端口连接复用测试(K、L、M、N组),测试总数增至 37 ? +- 2025-11-01: Mock server 新增 3 ?HTTPS 端口?1444-11446)用于测试连接池隔离 +- 2025-11-01: 新增本地 mock server,替?httpbin.org,提供稳定测试环? - 2025-11-01: 新增 15 个并发、竞态和连接复用集成测试(H、I、J组) diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md index 9a0dc32..dcebb69 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md @@ -8,82 +8,82 @@ ## 连接状态机定义 -### 状态属性 +### 状态属? **HttpdnsNWReusableConnection.h:9-11** ```objc -@property (nonatomic, strong) NSDate *lastUsedDate; // 最后使用时间 -@property (nonatomic, assign) BOOL inUse; // 是否正在被使用 -@property (nonatomic, assign, getter=isInvalidated, readonly) BOOL invalidated; // 是否已失效 +@property (nonatomic, strong) NSDate *lastUsedDate; // 最后使用时? +@property (nonatomic, assign) BOOL inUse; // 是否正在被使? +@property (nonatomic, assign, getter=isInvalidated, readonly) BOOL invalidated; // 是否已失? ``` -### 状态枚举 +### 状态枚? 虽然没有显式枚举,但连接实际存在以下逻辑状态: -| 状态 | `inUse` | `invalidated` | `pool` | 描述 | +| 状?| `inUse` | `invalidated` | `pool` | 描述 | |------|---------|---------------|--------|------| -| **CREATING** | - | NO | ✗ | 新创建,尚未打开 | -| **IN_USE** | YES | NO | ✓ | 已借出,正在使用 | -| **IDLE** | NO | NO | ✓ | 空闲,可复用 | -| **EXPIRED** | NO | NO | ✓ | 空闲超30秒,待清理 | -| **INVALIDATED** | - | YES | ✗ | 已失效,已移除 | +| **CREATING** | - | NO | ?| 新创建,尚未打开 | +| **IN_USE** | YES | NO | ?| 已借出,正在使?| +| **IDLE** | NO | NO | ?| 空闲,可复用 | +| **EXPIRED** | NO | NO | ?| 空闲?0秒,待清?| +| **INVALIDATED** | - | YES | ?| 已失效,已移?| --- ## 状态转换图 ``` - ┌─────────┐ - │CREATING │ (new connection) - └────┬────┘ - │ openWithTimeout success - ▼ - ┌─────────┐ - │ IN_USE │ (inUse=YES, in pool) - └────┬────┘ - │ - ├──success──► returnConnection(shouldClose=NO) - │ │ - │ ▼ - │ ┌─────────┐ - │ │ IDLE │ (inUse=NO, in pool) - │ └────┬────┘ - │ │ - │ ├──dequeue──► IN_USE (reuse) - │ │ - │ ├──idle 30s──► EXPIRED - │ │ │ - │ │ └──prune──► INVALIDATED - │ │ - │ └──!isViable──► INVALIDATED (skip in dequeue) - │ - ├──error/timeout──► returnConnection(shouldClose=YES) - │ │ - │ ▼ - └──────────► ┌──────────────┐ - │ INVALIDATED │ (removed from pool) - └──────────────┘ + ┌─────────? + │CREATING ?(new connection) + └────┬────? + ?openWithTimeout success + ? + ┌─────────? + ?IN_USE ?(inUse=YES, in pool) + └────┬────? + ? + ├──success──?returnConnection(shouldClose=NO) + ? ? + ? ? + ? ┌─────────? + ? ? IDLE ?(inUse=NO, in pool) + ? └────┬────? + ? ? + ? ├──dequeue──?IN_USE (reuse) + ? ? + ? ├──idle 30s──?EXPIRED + ? ? ? + ? ? └──prune──?INVALIDATED + ? ? + ? └──!isViable──?INVALIDATED (skip in dequeue) + ? + ├──error/timeout──?returnConnection(shouldClose=YES) + ? ? + ? ? + └──────────?┌──────────────? + ?INVALIDATED ?(removed from pool) + └──────────────? ``` --- -## 代码中的状态转换 +## 代码中的状态转? -### 1. CREATING → IN_USE (新连接) +### 1. CREATING ?IN_USE (新连? **HttpdnsNWHTTPClient.m:248-249** ```objc newConnection.inUse = YES; newConnection.lastUsedDate = now; -[pool addObject:newConnection]; // 加入池 +[pool addObject:newConnection]; // 加入? ``` **何时触发:** - `dequeueConnectionForHost` 找不到可复用连接 - 创建新连接并成功打开 -### 2. IDLE → IN_USE (复用) +### 2. IDLE ?IN_USE (复用) **HttpdnsNWHTTPClient.m:210-214** ```objc @@ -97,16 +97,16 @@ for (HttpdnsNWReusableConnection *candidate in pool) { } ``` -**关键检查:** -- `!candidate.inUse` - 必须是空闲状态 +**关键检?** +- `!candidate.inUse` - 必须是空闲状? - `[candidate isViable]` - 连接必须仍然有效 -### 3. IN_USE → IDLE (正常归还) +### 3. IN_USE ?IDLE (正常归还) **HttpdnsNWHTTPClient.m:283-288** ```objc if (shouldClose || connection.isInvalidated) { - // → INVALIDATED (见#4) + // ?INVALIDATED (?4) } else { connection.inUse = NO; connection.lastUsedDate = now; @@ -120,7 +120,7 @@ if (shouldClose || connection.isInvalidated) { **防护措施:** - Line 285: `if (![pool containsObject:connection])` - 防止重复添加 -### 4. IN_USE/IDLE → INVALIDATED (失效) +### 4. IN_USE/IDLE ?INVALIDATED (失效) **HttpdnsNWHTTPClient.m:279-281** ```objc @@ -132,9 +132,9 @@ if (shouldClose || connection.isInvalidated) { **触发条件:** - `shouldClose=YES` (timeout, error, parse failure, remote close) -- `connection.isInvalidated=YES` (连接已失效) +- `connection.isInvalidated=YES` (连接已失? -### 5. EXPIRED → INVALIDATED (过期清理) +### 5. EXPIRED ?INVALIDATED (过期清理) **HttpdnsNWHTTPClient.m:297-312** ```objc @@ -145,7 +145,7 @@ if (shouldClose || connection.isInvalidated) { if (conn.inUse) continue; // 跳过使用中的 NSTimeInterval idle = [referenceDate timeIntervalSinceDate:conn.lastUsedDate]; - if (idle > kHttpdnsNWHTTPClientConnectionIdleTimeout) { // 30秒 + if (idle > kHttpdnsNWHTTPClientConnectionIdleTimeout) { // 30? [toRemove addObject:conn]; } } @@ -155,7 +155,7 @@ if (shouldClose || connection.isInvalidated) { [pool removeObject:conn]; } - // 限制池大小 ≤ 4 + // 限制池大??4 while (pool.count > kHttpdnsNWHTTPClientMaxIdleConnectionsPerHost) { HttpdnsNWReusableConnection *oldest = pool.firstObject; [oldest invalidate]; @@ -168,72 +168,72 @@ if (shouldClose || connection.isInvalidated) { ## 当前测试覆盖情况 -### ✅ 已测试的正常流程 +### ?已测试的正常流程 -| 状态转换 | 测试 | 覆盖 | +| 状态转?| 测试 | 覆盖 | |----------|------|------| -| CREATING → IN_USE → IDLE | G.1-G.7, O.1 | ✅ | -| IDLE → IN_USE (复用) | G.2, O.1-O.3, J.1-J.5 | ✅ | -| IN_USE → INVALIDATED (timeout) | P.1-P.6 | ✅ | -| EXPIRED → INVALIDATED (30s) | J.2, M.4, I.4 | ✅ | -| 池容量限制 (max 4) | O.3, J.3 | ✅ | -| 并发状态访问 | I.1-I.5, M.3 | ✅ | +| CREATING ?IN_USE ?IDLE | G.1-G.7, O.1 | ?| +| IDLE ?IN_USE (复用) | G.2, O.1-O.3, J.1-J.5 | ?| +| IN_USE ?INVALIDATED (timeout) | P.1-P.6 | ?| +| EXPIRED ?INVALIDATED (30s) | J.2, M.4, I.4 | ?| +| 池容量限?(max 4) | O.3, J.3 | ?| +| 并发状态访?| I.1-I.5, M.3 | ?| -### ❌ 未测试的异常场景 +### ?未测试的异常场景 -#### 1. **连接在池中失效(Stale Connection)** +#### 1. **连接在池中失效(Stale Connection?* **场景:** - 连接空闲 29 秒(未到 30 秒过期) -- 服务器主动关闭连接 -- `dequeue` 时 `isViable` 返回 NO +- 服务器主动关闭连? +- `dequeue` ?`isViable` 返回 NO **当前代码行为:** ```objc for (HttpdnsNWReusableConnection *candidate in pool) { - if (!candidate.inUse && [candidate isViable]) { // ← isViable 检查 - // 只复用有效连接 + if (!candidate.inUse && [candidate isViable]) { // ?isViable 检? + // 只复用有效连? } } -// 如果所有连接都 !isViable,会创建新连接 +// 如果所有连接都 !isViable,会创建新连? ``` -**风险:** 未验证 `isViable` 检查是否真的工作 +**风险:** 未验?`isViable` 检查是否真的工? -**测试需求:** Q.1 +**测试需?** Q.1 ```objc testStateTransition_StaleConnectionInPool_SkipsAndCreatesNew ``` --- -#### 2. **双重归还(Double Return)** +#### 2. **双重归还(Double Return?* **场景:** -- 连接被归还 +- 连接被归? - 代码错误,再次归还同一连接 **当前代码防护:** ```objc if (![pool containsObject:connection]) { - [pool addObject:connection]; // ← 防止重复添加 + [pool addObject:connection]; // ?防止重复添加 } ``` -**风险:** 未验证防护是否有效 +**风险:** 未验证防护是否有? -**测试需求:** Q.2 +**测试需?** Q.2 ```objc testStateTransition_DoubleReturn_Idempotent ``` --- -#### 3. **归还错误的池键(Wrong Pool Key)** +#### 3. **归还错误的池键(Wrong Pool Key?* **场景:** - 从池A借出连接 -- 归还到池B(错误的key) +- 归还到池B(错误的key? **当前代码行为:** ```objc @@ -246,9 +246,9 @@ testStateTransition_DoubleReturn_Idempotent } ``` -**风险:** 可能导致池污染 +**风险:** 可能导致池污? -**测试需求:** Q.3 +**测试需?** Q.3 ```objc testStateTransition_ReturnToWrongPool_Isolated ``` @@ -259,67 +259,67 @@ testStateTransition_ReturnToWrongPool_Isolated **场景:** - 连接被借出 (inUse=YES) -- `sendRequestData` 过程中网络错误 -- 连接被标记 invalidated +- `sendRequestData` 过程中网络错? +- 连接被标?invalidated **当前代码行为:** ```objc NSData *rawResponse = [connection sendRequestData:requestData ...]; if (!rawResponse) { - [self returnConnection:connection forKey:poolKey shouldClose:YES]; // ← invalidated + [self returnConnection:connection forKey:poolKey shouldClose:YES]; // ?invalidated } ``` -**测试需求:** Q.4 +**测试需?** Q.4 ```objc testStateTransition_ErrorDuringUse_Invalidated ``` --- -#### 5. **池容量超限时的移除策略** +#### 5. **池容量超限时的移除策?* **场景:** -- 池已有 4 个连接 -- 第 5 个连接被归还 +- 池已?4 个连? +- ?5 个连接被归还 **当前代码行为:** ```objc while (pool.count > kHttpdnsNWHTTPClientMaxIdleConnectionsPerHost) { - HttpdnsNWReusableConnection *oldest = pool.firstObject; // ← 移除最老的 + HttpdnsNWReusableConnection *oldest = pool.firstObject; // ?移除最老的 [oldest invalidate]; [pool removeObject:oldest]; } ``` **问题:** -- 移除 `pool.firstObject` - 是按添加顺序还是使用顺序? +- 移除 `pool.firstObject` - 是按添加顺序还是使用顺序? - NSMutableArray 顺序是否能保证? -**测试需求:** Q.5 +**测试需?** Q.5 ```objc testStateTransition_PoolOverflow_RemovesOldest ``` --- -#### 6. **并发状态竞态** +#### 6. **并发状态竞?* **场景:** -- Thread A: dequeue 连接,设置 `inUse=YES` +- Thread A: dequeue 连接,设?`inUse=YES` - Thread B: 同时 prune 过期连接 -- 竞态:连接同时被标记 inUse 和被移除 +- 竞态:连接同时被标?inUse 和被移除 **当前代码防护:** ```objc - (void)pruneConnectionPool:... { for (HttpdnsNWReusableConnection *conn in pool) { - if (conn.inUse) continue; // ← 跳过使用中的 + if (conn.inUse) continue; // ?跳过使用中的 } } ``` -**测试需求:** Q.6 (可能已被 I 组部分覆盖) +**测试需?** Q.6 (可能已被 I 组部分覆? ```objc testStateTransition_ConcurrentDequeueAndPrune_NoCorruption ``` @@ -335,100 +335,100 @@ testStateTransition_ConcurrentDequeueAndPrune_NoCorruption **当前代码行为:** ```objc if (![newConnection openWithTimeout:timeout error:error]) { - [newConnection invalidate]; // ← 立即失效 - return nil; // ← 不加入池 + [newConnection invalidate]; // ?立即失效 + return nil; // ?不加入池 } ``` -**测试需求:** Q.7 +**测试需?** Q.7 ```objc testStateTransition_OpenFails_NotAddedToPool ``` --- -## 状态不变式(State Invariants) +## 状态不变式(State Invariants? -### 应该始终成立的约束 +### 应该始终成立的约? -1. **互斥性:** +1. **互斥?** ``` - ∀ connection: (inUse=YES) ⇒ (dequeue count ≤ 1) + ∀ connection: (inUse=YES) ?(dequeue count ?1) ``` 同一连接不能被多次借出 -2. **池完整性:** +2. **池完整?** ``` - ∀ pool: ∑(connections) ≤ maxPoolSize (4) + ∀ pool: ?connections) ?maxPoolSize (4) ``` - 每个池最多 4 个连接 + 每个池最?4 个连? -3. **状态一致性:** +3. **状态一致?** ``` ∀ connection in pool: !invalidated ``` - 池中不应有失效连接 + 池中不应有失效连? -4. **时间单调性:** +4. **时间单调?** ``` ∀ connection: lastUsedDate 随每次使用递增 ``` -5. **失效不可逆:** +5. **失效不可?** ``` - invalidated=YES ⇒ connection removed from pool + invalidated=YES ?connection removed from pool ``` - 失效连接必须从池中移除 + 失效连接必须从池中移? --- ## 测试设计建议 -### Q 组:状态机异常转换测试(7个新测试) +### Q 组:状态机异常转换测试?个新测试? | 测试 | 验证内容 | 难度 | |------|---------|------| -| **Q.1** | Stale connection 被 `isViable` 检测并跳过 | 🔴 高(需要模拟服务器关闭) | -| **Q.2** | 双重归还是幂等的 | 🟢 低 | -| **Q.3** | 归还到错误池键不污染其他池 | 🟡 中 | -| **Q.4** | 使用中错误导致连接失效 | 🟢 低(已有 P 组部分覆盖) | -| **Q.5** | 池溢出时移除最旧连接 | 🟡 中 | -| **Q.6** | 并发 dequeue/prune 竞态 | 🔴 高(需要精确时序) | -| **Q.7** | 打开失败的连接不加入池 | 🟢 低 | +| **Q.1** | Stale connection ?`isViable` 检测并跳过 | 🔴 高(需要模拟服务器关闭?| +| **Q.2** | 双重归还是幂等的 | 🟢 ?| +| **Q.3** | 归还到错误池键不污染其他?| 🟡 ?| +| **Q.4** | 使用中错误导致连接失?| 🟢 低(已有 P 组部分覆盖) | +| **Q.5** | 池溢出时移除最旧连?| 🟡 ?| +| **Q.6** | 并发 dequeue/prune 竞?| 🔴 高(需要精确时序) | +| **Q.7** | 打开失败的连接不加入?| 🟢 ?| --- ## 状态机验证策略 -### 方法1: 直接状态检查 +### 方法1: 直接状态检? ```objc -// 验证状态属性 +// 验证状态属? XCTAssertTrue(connection.inUse); XCTAssertFalse(connection.isInvalidated); XCTAssertEqual([poolCount], expectedCount); ``` -### 方法2: 状态转换序列 +### 方法2: 状态转换序? ```objc // 验证转换序列 [client resetPoolStatistics]; -// CREATING → IN_USE +// CREATING ?IN_USE response1 = [client performRequest...]; XCTAssertEqual(creationCount, 1); -// IN_USE → IDLE +// IN_USE ?IDLE [NSThread sleepForTimeInterval:0.5]; XCTAssertEqual(poolCount, 1); -// IDLE → IN_USE (reuse) +// IDLE ?IN_USE (reuse) response2 = [client performRequest...]; XCTAssertEqual(reuseCount, 1); ``` -### 方法3: 不变式验证 +### 方法3: 不变式验? ```objc // 验证池不变式 @@ -441,32 +441,32 @@ for (NSString *key in keys) { --- -## 当前覆盖率评估 +## 当前覆盖率评? -### 状态转换覆盖矩阵 +### 状态转换覆盖矩? -| From ↓ / To → | CREATING | IN_USE | IDLE | EXPIRED | INVALIDATED | +| From ?/ To ?| CREATING | IN_USE | IDLE | EXPIRED | INVALIDATED | |---------------|----------|--------|------|---------|-------------| -| **CREATING** | - | ✅ | ❌ | ❌ | ✅ (Q.7 needed) | -| **IN_USE** | ❌ | - | ✅ | ❌ | ✅ | -| **IDLE** | ❌ | ✅ | - | ✅ | ❌ (Q.1 needed) | -| **EXPIRED** | ❌ | ❌ | ❌ | - | ✅ | -| **INVALIDATED** | ❌ | ❌ | ❌ | ❌ | - | +| **CREATING** | - | ?| ?| ?| ?(Q.7 needed) | +| **IN_USE** | ?| - | ?| ?| ?| +| **IDLE** | ?| ?| - | ?| ?(Q.1 needed) | +| **EXPIRED** | ?| ?| ?| - | ?| +| **INVALIDATED** | ?| ?| ?| ?| - | -**覆盖率:** 6/25 transitions = 24% -**有效覆盖率:** 6/10 valid transitions = 60% +**覆盖?** 6/25 transitions = 24% +**有效覆盖?** 6/10 valid transitions = 60% ### 异常场景覆盖 | 异常场景 | 当前测试 | 覆盖 | |----------|---------|------| -| Stale connection | ❌ | 0% | -| Double return | ❌ | 0% | -| Wrong pool key | ❌ | 0% | +| Stale connection | ?| 0% | +| Double return | ?| 0% | +| Wrong pool key | ?| 0% | | Error during use | P.1-P.6 | 100% | -| Pool overflow | O.3, J.3 | 50% (未验证移除策略) | +| Pool overflow | O.3, J.3 | 50% (未验证移除策? | | Concurrent race | I.1-I.5 | 80% | -| Open failure | ❌ | 0% | +| Open failure | ?| 0% | **总体异常覆盖:** ~40% @@ -476,15 +476,15 @@ for (NSString *key in keys) { ### 高风险未测试场景 -**风险等级 🔴 高:** +**风险等级 🔴 ?** 1. **Stale Connection (Q.1)** - 可能导致请求失败 -2. **Concurrent Dequeue/Prune (Q.6)** - 可能导致状态不一致 +2. **Concurrent Dequeue/Prune (Q.6)** - 可能导致状态不一? -**风险等级 🟡 中:** -3. **Wrong Pool Key (Q.3)** - 可能导致池污染 +**风险等级 🟡 ?** +3. **Wrong Pool Key (Q.3)** - 可能导致池污? 4. **Pool Overflow Strategy (Q.5)** - LRU vs FIFO 影响性能 -**风险等级 🟢 低:** +**风险等级 🟢 ?** 5. **Double Return (Q.2)** - 已有代码防护 6. **Open Failure (Q.7)** - 已有错误处理 @@ -494,21 +494,21 @@ for (NSString *key in keys) { ### 短期(关键) -1. ✅ **添加 Q.2 测试** - 验证双重归还防护 -2. ✅ **添加 Q.5 测试** - 验证池溢出移除策略 -3. ✅ **添加 Q.7 测试** - 验证打开失败处理 +1. ?**添加 Q.2 测试** - 验证双重归还防护 +2. ?**添加 Q.5 测试** - 验证池溢出移除策? +3. ?**添加 Q.7 测试** - 验证打开失败处理 ### 中期(增强) -4. ⚠️ **添加 Q.3 测试** - 验证池隔离 -5. ⚠️ **添加 Q.1 测试** - 验证 stale connection(需要 mock) +4. ⚠️ **添加 Q.3 测试** - 验证池隔? +5. ⚠️ **添加 Q.1 测试** - 验证 stale connection(需?mock? ### 长期(完整) -6. 🔬 **添加 Q.6 测试** - 验证并发竞态(复杂) +6. 🔬 **添加 Q.6 测试** - 验证并发竞态(复杂? --- **创建时间**: 2025-11-01 -**作者**: Claude Code -**状态**: 分析完成,待实现 Q 组测试 +**作?*: Claude Code +**状?*: 分析完成,待实现 Q 组测? diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/TIMEOUT_ANALYSIS.md b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/TIMEOUT_ANALYSIS.md index 3545d50..80ed39f 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/TIMEOUT_ANALYSIS.md +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Network/TIMEOUT_ANALYSIS.md @@ -2,10 +2,10 @@ ## 问题描述 -当前测试套件没有充分验证**超时与连接池交互**的"无形结果"(intangible outcomes),可能存在以下风险: +当前测试套件没有充分验证**超时与连接池交互**?无形结果"(intangible outcomes),可能存在以下风险? - 超时后的连接泄漏 - 连接池被超时连接污染 -- 连接池无法从超时中恢复 +- 连接池无法从超时中恢? - 并发场景下部分超时影响整体池健康 --- @@ -26,11 +26,11 @@ if (!rawResponse) { ```objc if (shouldClose || connection.isInvalidated) { [connection invalidate]; // 取消底层 nw_connection - [pool removeObject:connection]; // 从池中移除 + [pool removeObject:connection]; // 从池中移? } ``` -**结论**:代码逻辑正确,超时连接**会被移除**而非留在池中。 +**结论**:代码逻辑正确,超时连?*会被移除**而非留在池中? --- @@ -38,33 +38,33 @@ if (shouldClose || connection.isInvalidated) { ### 已有测试:`testIntegration_RequestTimeout_ReturnsError` -**验证内容:** -- ✅ 超时返回 `nil` response -- ✅ 超时设置 `error` +**验证内容?* +- ?超时返回 `nil` response +- ?超时设置 `error` **未验证内容(缺失):** -- ❌ 连接是否从池中移除 -- ❌ 池计数是否正确 -- ❌ 后续请求是否正常工作 -- ❌ 是否存在连接泄漏 -- ❌ 并发场景下部分超时的影响 +- ?连接是否从池中移? +- ?池计数是否正? +- ?后续请求是否正常工作 +- ?是否存在连接泄漏 +- ?并发场景下部分超时的影响 --- ## 需要验证的"无形结果" -### 1. 单次超时后的池清理 +### 1. 单次超时后的池清? -**场景**: -1. 请求 A 超时(timeout=1s, endpoint=/delay/10) -2. 验证池状态 +**场景**? +1. 请求 A 超时(timeout=1s, endpoint=/delay/10? +2. 验证池状? **应验证:** -- Pool count = 0(连接已移除) +- Pool count = 0(连接已移除? - Total connection count 没有异常增长 -- 无连接泄漏 +- 无连接泄? -**测试方法**: +**测试方法**? ```objc [client resetPoolStatistics]; @@ -78,7 +78,7 @@ HttpdnsNWHTTPClientResponse *response = [client performRequestWithURLString:@"ht XCTAssertNil(response); XCTAssertNotNil(error); -// 验证池状态 +// 验证池状? NSString *poolKey = @"127.0.0.1:11080:tcp"; XCTAssertEqual([client connectionPoolCountForKey:poolKey], 0, @"Timed-out connection should be removed"); XCTAssertEqual([client totalConnectionCount], 0, @"No connections should remain"); @@ -88,72 +88,72 @@ XCTAssertEqual(client.connectionReuseCount, 0, @"No reuse for timed-out connecti --- -### 2. 超时后的池恢复能力 +### 2. 超时后的池恢复能? -**场景**: +**场景**? 1. 请求 A 超时 -2. 请求 B 正常(验证池恢复) -3. 请求 C 复用 B 的连接 +2. 请求 B 正常(验证池恢复? +3. 请求 C 复用 B 的连? **应验证:** - 请求 B 成功(池已恢复) -- 请求 C 复用连接(connectionReuseCount = 1) -- Pool count = 1(只有 B/C 的连接) +- 请求 C 复用连接(connectionReuseCount = 1? +- Pool count = 1(只?B/C 的连接) --- ### 3. 并发场景:部分超时不影响成功请求 -**场景**: -1. 并发发起 10 个请求 -2. 5 个正常(timeout=15s) -3. 5 个超时(timeout=0.5s, endpoint=/delay/10) +**场景**? +1. 并发发起 10 个请? +2. 5 个正常(timeout=15s? +3. 5 个超时(timeout=0.5s, endpoint=/delay/10? **应验证:** -- 5 个正常请求成功 -- 5 个超时请求失败 -- Pool count ≤ 5(只保留成功的连接) -- Total connection count ≤ 5(无泄漏) -- connectionCreationCount ≤ 10(合理范围) -- 成功的请求可以复用连接 +- 5 个正常请求成? +- 5 个超时请求失? +- Pool count ?5(只保留成功的连接) +- Total connection count ?5(无泄漏? +- connectionCreationCount ?10(合理范围) +- 成功的请求可以复用连? --- -### 4. 连续超时不导致资源泄漏 +### 4. 连续超时不导致资源泄? -**场景**: -1. 连续 20 次超时请求 -2. 验证连接池没有累积"僵尸连接" +**场景**? +1. 连续 20 次超时请? +2. 验证连接池没有累?僵尸连接" **应验证:** - Pool count = 0 - Total connection count = 0 -- connectionCreationCount = 20(每次都创建新连接,因为超时的被移除) +- connectionCreationCount = 20(每次都创建新连接,因为超时的被移除? - connectionReuseCount = 0(超时连接不可复用) -- 无内存泄漏(虽然代码层面无法直接测试) +- 无内存泄漏(虽然代码层面无法直接测试? --- ### 5. 超时不阻塞连接池 -**场景**: -1. 请求 A 超时(endpoint=/delay/10, timeout=1s) -2. 同时请求 B 正常(endpoint=/get, timeout=15s) +**场景**? +1. 请求 A 超时(endpoint=/delay/10, timeout=1s? +2. 同时请求 B 正常(endpoint=/get, timeout=15s? **应验证:** -- 请求 A 和 B 并发执行(不互相阻塞) -- 请求 B 成功(不受 A 超时影响) +- 请求 A ?B 并发执行(不互相阻塞? +- 请求 B 成功(不?A 超时影响? - 请求 A 的超时连接被正确移除 -- Pool 中只有请求 B 的连接 +- Pool 中只有请?B 的连? --- -### 6. 多端口场景下的超时隔离 +### 6. 多端口场景下的超时隔? -**场景**: +**场景**? 1. 端口 11443 请求超时 2. 端口 11444 请求正常 -3. 验证端口间隔离 +3. 验证端口间隔? **应验证:** - 端口 11443 pool count = 0 @@ -175,52 +175,52 @@ XCTAssertEqual(client.connectionReuseCount, 0, @"No reuse for timed-out connecti **P.3 并发部分超时** - `testTimeout_ConcurrentPartialTimeout_SuccessfulRequestsReuse` -**P.4 连续超时无泄漏** +**P.4 连续超时无泄?* - `testTimeout_ConsecutiveTimeouts_NoConnectionLeak` **P.5 超时不阻塞池** - `testTimeout_NonBlocking_ConcurrentNormalRequestSucceeds` -**P.6 多端口超时隔离** +**P.6 多端口超时隔?* - `testTimeout_MultiPort_IsolatedPoolCleaning` --- ## Mock Server 支持 -需要添加可配置延迟的 endpoint: -- `/delay/10` - 延迟 10 秒(已有) -- 测试时设置短 timeout(如 0.5s-2s)触发超时 +需要添加可配置延迟?endpoint? +- `/delay/10` - 延迟 10 秒(已有? +- 测试时设置短 timeout(如 0.5s-2s)触发超? --- ## 预期测试结果 -| 验证项 | 当前状态 | 目标状态 | +| 验证?| 当前状?| 目标状?| |--------|---------|---------| -| 超时连接移除 | 未验证 | ✅ 验证池计数=0 | -| 池恢复能力 | 未验证 | ✅ 后续请求成功 | -| 并发超时隔离 | 未验证 | ✅ 成功请求不受影响 | -| 无连接泄漏 | 未验证 | ✅ 总连接数稳定 | -| 超时不阻塞 | 未验证 | ✅ 并发执行不阻塞 | -| 多端口隔离 | 未验证 | ✅ 端口间独立清理 | +| 超时连接移除 | 未验?| ?验证池计?0 | +| 池恢复能?| 未验?| ?后续请求成功 | +| 并发超时隔离 | 未验?| ?成功请求不受影响 | +| 无连接泄?| 未验?| ?总连接数稳定 | +| 超时不阻?| 未验?| ?并发执行不阻?| +| 多端口隔?| 未验?| ?端口间独立清?| --- ## 风险评估 -**如果不测试这些场景的风险:** -1. **连接泄漏**:超时连接可能未正确清理,导致内存泄漏 -2. **池污染**:超时连接留在池中,被后续请求复用导致失败 +**如果不测试这些场景的风险?* +1. **连接泄漏**:超时连接可能未正确清理,导致内存泄? +2. **池污?*:超时连接留在池中,被后续请求复用导致失? 3. **级联故障**:部分超时影响整体连接池健康 4. **资源耗尽**:连续超时累积连接,最终耗尽系统资源 -**当前代码逻辑正确性:** ✅ 高(代码分析显示正确处理) -**测试验证覆盖率:** ❌ 低(缺少池交互验证) +**当前代码逻辑正确性:** ?高(代码分析显示正确处理? +**测试验证覆盖率:** ?低(缺少池交互验证) -**建议:** 添加 P 组测试以提供**可观测的证据**证明超时处理正确。 +**建议?* 添加 P 组测试以提供**可观测的证据**证明超时处理正确? --- **创建时间**: 2025-11-01 -**维护者**: Claude Code +**维护?*: Claude Code diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/OutdatedTest/NetworkManager.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/OutdatedTest/NetworkManager.m index 4d9f4cc..2d8543a 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/OutdatedTest/NetworkManager.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/OutdatedTest/NetworkManager.m @@ -12,7 +12,7 @@ #import #import -static char *const networkManagerQueue = "com.alibaba.managerQueue"; +static char *const networkManagerQueue = "com.Trust.managerQueue"; static dispatch_queue_t reachabilityQueue; @implementation NetworkManager { diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.h index 9898ef8..6fef01e 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.h @@ -1,9 +1,9 @@ // // TestBase.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/4/14. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.m index 59fc0fb..349a42c 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/TestBase.m @@ -1,9 +1,9 @@ // // TestBase.m -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/4/14. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import "TestBase.h" diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.h b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.h index 18e697d..5098ff0 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.h +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.h @@ -1,9 +1,9 @@ // // TestBase.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/4/14. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import diff --git a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.m b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.m index ac3196a..4ef4885 100644 --- a/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.m +++ b/EdgeHttpDNS/sdk/ios/AlicloudHttpDNSTests/Testbase/XCTestCase+AsyncTesting.m @@ -1,9 +1,9 @@ // // TestBase.h -// AlicloudHttpDNS +// TrustHttpDNS // // Created by ElonChan(地风) on 2017/4/14. -// Copyright © 2017年 alibaba-inc.com. All rights reserved. +// Copyright © 2017?trustapp.com. All rights reserved. // #import "XCTestCase+AsyncTesting.h" diff --git a/EdgeHttpDNS/sdk/ios/README.md b/EdgeHttpDNS/sdk/ios/README.md index 801c69a..549e33a 100644 --- a/EdgeHttpDNS/sdk/ios/README.md +++ b/EdgeHttpDNS/sdk/ios/README.md @@ -1,9 +1,9 @@ -# HTTPDNS iOS SDK (SNI Hidden v1.0.0) +# HTTPDNS iOS SDK (SNI Hidden v1.0.0) ## 1. Init ```objc -#import +#import HttpdnsEdgeService *service = [[HttpdnsEdgeService alloc] initWithAppId:@"app1f1ndpo9" diff --git a/EdgeHttpDNS/新建文本文档.txt b/EdgeHttpDNS/新建文本文档.txt new file mode 100644 index 0000000..6b422d2 --- /dev/null +++ b/EdgeHttpDNS/新建文本文档.txt @@ -0,0 +1,50 @@ +1.4.7版本changelog(重大版本) + +1、将edge-node边缘节点的日志处理逻辑做了改造,由原来的发送给api组件再存入mysql,改成写入本地再由fluent-bit上传至clickhouse; +2、将edge-dns节点的日志处理逻辑做了改造,由原来的发送给api组件再存入mysql,改成写入本地再由fluent-bit上传至clickhouse; +3、edge-admin新增了clickhouse配置页面; +4、edge-admin新增了双写、单写mysql、单写clickhouse的日志策略; +5、优化了日志展示内容,可以查看更详细的日志内容; +7、node和dns节点新增了fluent-bit自动安装和配置逻辑,可以在平台新增边缘节点时直接完成fluent-bit的安装和配置; +8、新增clickhouse自动安装和配置脚本; +9、优化了edge-user的新增网站逻辑,新增了日志、统计、websocket、waf等必要功能的开关,让网站接入操作更简便; +10、优化了登录界面和后台风格,优化了部分功能展示,让平台整体显得更专业。 + +1.4.7版本升级步骤 + +1、将edge-api、edge-admin、edge-user三个组件的configs文件夹、平台的mysql数据库文件备份一下; + +2、杀掉进程 +killall -9 edge-api +killall -9 edge-admin +killall -9 edge-user + +3、上传文件到/data/并解压(下面的命令不会覆盖原有有用配置) +unzip -o edge-admin-linux-amd64-v1.4.7.zip -d /data/ +unzip -o edge-user-linux-amd64-v1.4.7.zip -d /data/ + +4、依次运行edge-api、edge-admin、edge-user + +cd /data/edge-admin/edge-api/bin +chmod +x edge-api +nohup ./edge-api 2>&1 & + +cd /data/edge-admin/bin +chmod +x edge-admin +nohup ./edge-admin 2>&1 & + +cd /data/edge-user/bin +chmod +x edge-user +nohup ./edge-user 2>&1 & + +5、检查进程 ps aux | grep edge,看下对应进程是否在; +6、检查端口 ss -tuln,看下对应端口是否监听; +7、检查平台,登录平台,看下版本是否1.4.7,看下(node、dns)边缘节点是否最新(会自动升级),点一下各个页面看是否正常; +8、使用clickhouse安装脚本完成clickhouse安装,并在管理平台--系统设置--高级设置--日志数据库(clickhouse)进行配置; +9、在管理平台--网站列表--日志策略,新增日志策略,选“文件+clickhouse”、公用、停用默认数据库存储; +9、检查业务,打开某个经过waf的网站,查看网站是否正常打开,查看日志显示是否正常; +10、完成升级。 + +特别说明: +1、边缘节点的fluent-bit会自动安装,不需要手工安装和配置; +2、edge-node和edge-dns支持在ubuntu22.04和aws2023系统安装运行,可通过平台下发成功。 diff --git a/EdgeUser/internal/const/const.go b/EdgeUser/internal/const/const.go index 9adfbef..8ab824f 100644 --- a/EdgeUser/internal/const/const.go +++ b/EdgeUser/internal/const/const.go @@ -1,7 +1,7 @@ package teaconst const ( - Version = "1.4.7" //1.3.8.2 + Version = "1.4.8" //1.3.8.2 ProductName = "Edge User" ProcessName = "edge-user" diff --git a/EdgeUser/internal/rpc/rpc_client.go b/EdgeUser/internal/rpc/rpc_client.go index 2dfbdb4..028eea2 100644 --- a/EdgeUser/internal/rpc/rpc_client.go +++ b/EdgeUser/internal/rpc/rpc_client.go @@ -420,6 +420,34 @@ func (this *RPCClient) NSPlanRPC() pb.NSPlanServiceClient { return pb.NewNSPlanServiceClient(this.pickConn()) } +func (this *RPCClient) HTTPDNSClusterRPC() pb.HTTPDNSClusterServiceClient { + return pb.NewHTTPDNSClusterServiceClient(this.pickConn()) +} + +func (this *RPCClient) HTTPDNSNodeRPC() pb.HTTPDNSNodeServiceClient { + return pb.NewHTTPDNSNodeServiceClient(this.pickConn()) +} + +func (this *RPCClient) HTTPDNSAppRPC() pb.HTTPDNSAppServiceClient { + return pb.NewHTTPDNSAppServiceClient(this.pickConn()) +} + +func (this *RPCClient) HTTPDNSDomainRPC() pb.HTTPDNSDomainServiceClient { + return pb.NewHTTPDNSDomainServiceClient(this.pickConn()) +} + +func (this *RPCClient) HTTPDNSRuleRPC() pb.HTTPDNSRuleServiceClient { + return pb.NewHTTPDNSRuleServiceClient(this.pickConn()) +} + +func (this *RPCClient) HTTPDNSAccessLogRPC() pb.HTTPDNSAccessLogServiceClient { + return pb.NewHTTPDNSAccessLogServiceClient(this.pickConn()) +} + +func (this *RPCClient) HTTPDNSSandboxRPC() pb.HTTPDNSSandboxServiceClient { + return pb.NewHTTPDNSSandboxServiceClient(this.pickConn()) +} + func (this *RPCClient) ServerBandwidthStatRPC() pb.ServerBandwidthStatServiceClient { return pb.NewServerBandwidthStatServiceClient(this.pickConn()) } diff --git a/EdgeUser/internal/web/actions/default/httpdns/addPortPopup.go b/EdgeUser/internal/web/actions/default/httpdns/addPortPopup.go new file mode 100644 index 0000000..c533db3 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/addPortPopup.go @@ -0,0 +1,123 @@ +package httpdns + +import ( + "github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/actions" + "github.com/iwind/TeaGo/maps" + "github.com/iwind/TeaGo/types" + "regexp" + "strings" +) + +type AddPortPopupAction struct { + actionutils.ParentAction +} + +func (this *AddPortPopupAction) Init() { + this.Nav("", "", "") +} + +func (this *AddPortPopupAction) RunGet(params struct { + Protocol string + From string + SupportRange bool +}) { + this.Data["from"] = params.From + + var protocols = serverconfigs.FindAllServerProtocols() + if len(params.Protocol) > 0 { + result := []maps.Map{} + for _, p := range protocols { + if p.GetString("code") == params.Protocol { + result = append(result, p) + } + } + protocols = result + } + this.Data["protocols"] = protocols + + this.Data["supportRange"] = params.SupportRange + + this.Show() +} + +func (this *AddPortPopupAction) RunPost(params struct { + SupportRange bool + + Protocol string + Address string + + Must *actions.Must +}) { + // 鏍¢獙鍦板潃 + var addr = maps.Map{ + "protocol": params.Protocol, + "host": "", + "portRange": "", + "minPort": 0, + "maxPort": 0, + } + + var portRegexp = regexp.MustCompile(`^\d+$`) + if portRegexp.MatchString(params.Address) { // 鍗曚釜绔彛 + addr["portRange"] = this.checkPort(params.Address) + } else if params.SupportRange && regexp.MustCompile(`^\d+\s*-\s*\d+$`).MatchString(params.Address) { // Port1-Port2 + addr["portRange"], addr["minPort"], addr["maxPort"] = this.checkPortRange(params.Address) + } else if strings.Contains(params.Address, ":") { // IP:Port + index := strings.LastIndex(params.Address, ":") + addr["host"] = strings.TrimSpace(params.Address[:index]) + port := strings.TrimSpace(params.Address[index+1:]) + if portRegexp.MatchString(port) { + addr["portRange"] = this.checkPort(port) + } else if params.SupportRange && regexp.MustCompile(`^\d+\s*-\s*\d+$`).MatchString(port) { // Port1-Port2 + addr["portRange"], addr["minPort"], addr["maxPort"] = this.checkPortRange(port) + } else { + this.FailField("address", "璇疯緭鍏ユ纭殑绔彛鎴栬€呯綉缁滃湴鍧€") + } + } else { + this.FailField("address", "璇疯緭鍏ユ纭殑绔彛鎴栬€呯綉缁滃湴鍧€") + } + + this.Data["address"] = addr + this.Success() +} + +func (this *AddPortPopupAction) checkPort(port string) (portRange string) { + var intPort = types.Int(port) + if intPort < 1 { + this.FailField("address", "绔彛鍙蜂笉鑳藉皬浜?") + } + if intPort > 65535 { + this.FailField("address", "绔彛鍙蜂笉鑳藉ぇ浜?5535") + } + return port +} + +func (this *AddPortPopupAction) checkPortRange(port string) (portRange string, minPort int, maxPort int) { + var pieces = strings.Split(port, "-") + var piece1 = strings.TrimSpace(pieces[0]) + var piece2 = strings.TrimSpace(pieces[1]) + var port1 = types.Int(piece1) + var port2 = types.Int(piece2) + + if port1 < 1 { + this.FailField("address", "绔彛鍙蜂笉鑳藉皬浜?") + } + if port1 > 65535 { + this.FailField("address", "绔彛鍙蜂笉鑳藉ぇ浜?5535") + } + + if port2 < 1 { + this.FailField("address", "绔彛鍙蜂笉鑳藉皬浜?") + } + if port2 > 65535 { + this.FailField("address", "绔彛鍙蜂笉鑳藉ぇ浜?5535") + } + + if port1 > port2 { + port1, port2 = port2, port1 + } + + return types.String(port1) + "-" + types.String(port2), port1, port2 +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/app.go b/EdgeUser/internal/web/actions/default/httpdns/apps/app.go new file mode 100644 index 0000000..86bc071 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/app.go @@ -0,0 +1,26 @@ +package apps + +import ( + "strconv" + + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" +) + +type AppAction struct { + actionutils.ParentAction +} + +func (this *AppAction) Init() { + this.Nav("httpdns", "app", "") +} + +func (this *AppAction) RunGet(params struct { + AppId int64 +}) { + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + this.RedirectURL("/httpdns/apps/domains?appId=" + strconv.FormatInt(app.GetInt64("id"), 10)) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/appSettings.go b/EdgeUser/internal/web/actions/default/httpdns/apps/appSettings.go new file mode 100644 index 0000000..1243c21 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/appSettings.go @@ -0,0 +1,120 @@ +package apps + +import ( + "strconv" + + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" + "github.com/iwind/TeaGo/actions" + "github.com/iwind/TeaGo/maps" +) + +type AppSettingsAction struct { + actionutils.ParentAction +} + +func (this *AppSettingsAction) Init() { + this.Nav("httpdns", "app", "settings") +} + +func (this *AppSettingsAction) RunGet(params struct { + AppId int64 + Section string +}) { + httpdnsutils.AddLeftMenu(this.Parent()) + + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + + httpdnsutils.AddAppTabbar(this.Parent(), app.GetString("name"), app.GetInt64("id"), "settings") + + section := params.Section + if len(section) == 0 { + section = "basic" + } + this.Data["activeSection"] = section + + appIDStr := strconv.FormatInt(app.GetInt64("id"), 10) + this.Data["leftMenuItems"] = []maps.Map{ + { + "name": "基础配置", + "url": "/httpdns/apps/app/settings?appId=" + appIDStr + "§ion=basic", + "isActive": section == "basic", + }, + { + "name": "认证与密钥", + "url": "/httpdns/apps/app/settings?appId=" + appIDStr + "§ion=auth", + "isActive": section == "auth", + }, + } + + clusterResp, err := this.RPC().HTTPDNSClusterRPC().FindAllHTTPDNSClusters(this.UserContext(), &pb.FindAllHTTPDNSClustersRequest{}) + if err != nil { + this.ErrorPage(err) + return + } + clusterDomainMap := map[int64]string{} + for _, cluster := range clusterResp.GetClusters() { + clusterDomainMap[cluster.GetId()] = cluster.GetServiceDomain() + } + + primaryClusterId := app.GetInt64("primaryClusterId") + backupClusterId := app.GetInt64("backupClusterId") + settings := maps.Map{ + "appId": app.GetString("appId"), + "appStatus": app.GetBool("isOn"), + "primaryClusterId": primaryClusterId, + "backupClusterId": backupClusterId, + "primaryServiceDomain": clusterDomainMap[primaryClusterId], + "backupServiceDomain": clusterDomainMap[backupClusterId], + "signEnabled": app.GetBool("signEnabled"), + "signSecretPlain": app.GetString("signSecretPlain"), + "signSecretMasked": app.GetString("signSecretMasked"), + "signSecretUpdatedAt": app.GetString("signSecretUpdated"), + } + this.Data["app"] = app + this.Data["settings"] = settings + this.Show() +} + +func (this *AppSettingsAction) RunPost(params struct { + AppId int64 + + AppStatus bool + + Must *actions.Must + CSRF *actionutils.CSRF +}) { + params.Must.Field("appId", params.AppId).Gt(0, "请选择应用") + + appResp, err := this.RPC().HTTPDNSAppRPC().FindHTTPDNSApp(this.UserContext(), &pb.FindHTTPDNSAppRequest{ + AppDbId: params.AppId, + }) + if err != nil { + this.ErrorPage(err) + return + } + if appResp.GetApp() == nil { + this.Fail("找不到对应的应用") + return + } + + _, err = this.RPC().HTTPDNSAppRPC().UpdateHTTPDNSApp(this.UserContext(), &pb.UpdateHTTPDNSAppRequest{ + AppDbId: params.AppId, + Name: appResp.GetApp().GetName(), + PrimaryClusterId: appResp.GetApp().GetPrimaryClusterId(), + BackupClusterId: appResp.GetApp().GetBackupClusterId(), + IsOn: params.AppStatus, + UserId: appResp.GetApp().GetUserId(), + }) + if err != nil { + this.ErrorPage(err) + return + } + + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/appSettingsResetSignSecret.go b/EdgeUser/internal/web/actions/default/httpdns/apps/appSettingsResetSignSecret.go new file mode 100644 index 0000000..49c5f6f --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/appSettingsResetSignSecret.go @@ -0,0 +1,29 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/actions" +) + +type AppSettingsResetSignSecretAction struct { + actionutils.ParentAction +} + +func (this *AppSettingsResetSignSecretAction) RunPost(params struct { + AppId int64 + + Must *actions.Must +}) { + params.Must.Field("appId", params.AppId).Gt(0, "璇烽€夋嫨搴旂敤") + + _, err := this.RPC().HTTPDNSAppRPC().ResetHTTPDNSAppSignSecret(this.UserContext(), &pb.ResetHTTPDNSAppSignSecretRequest{ + AppDbId: params.AppId, + }) + if err != nil { + this.ErrorPage(err) + return + } + + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/appSettingsToggleSignEnabled.go b/EdgeUser/internal/web/actions/default/httpdns/apps/appSettingsToggleSignEnabled.go new file mode 100644 index 0000000..85b825e --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/appSettingsToggleSignEnabled.go @@ -0,0 +1,31 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/actions" +) + +type AppSettingsToggleSignEnabledAction struct { + actionutils.ParentAction +} + +func (this *AppSettingsToggleSignEnabledAction) RunPost(params struct { + AppId int64 + IsOn int + + Must *actions.Must +}) { + params.Must.Field("appId", params.AppId).Gt(0, "璇烽€夋嫨搴旂敤") + + _, err := this.RPC().HTTPDNSAppRPC().UpdateHTTPDNSAppSignEnabled(this.UserContext(), &pb.UpdateHTTPDNSAppSignEnabledRequest{ + AppDbId: params.AppId, + SignEnabled: params.IsOn == 1, + }) + if err != nil { + this.ErrorPage(err) + return + } + + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/create.go b/EdgeUser/internal/web/actions/default/httpdns/apps/create.go new file mode 100644 index 0000000..d3a6961 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/create.go @@ -0,0 +1,47 @@ +package apps + +import ( + "strconv" + "time" + + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/actions" +) + +type CreateAction struct { + actionutils.ParentAction +} + +func (this *CreateAction) Init() { + this.Nav("", "", "create") +} + +func (this *CreateAction) RunGet(params struct{}) { + this.Show() +} + +func (this *CreateAction) RunPost(params struct { + Name string + + Must *actions.Must + CSRF *actionutils.CSRF +}) { + params.Must.Field("name", params.Name).Require("请输入应用名称") + + createResp, err := this.RPC().HTTPDNSAppRPC().CreateHTTPDNSApp(this.UserContext(), &pb.CreateHTTPDNSAppRequest{ + Name: params.Name, + AppId: "app" + strconv.FormatInt(time.Now().UnixNano()%1_000_000_000_000, 36), + PrimaryClusterId: 0, + BackupClusterId: 0, + IsOn: true, + SignEnabled: true, + }) + if err != nil { + this.ErrorPage(err) + return + } + + this.Data["appId"] = createResp.GetAppDbId() + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/customRecords.go b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecords.go new file mode 100644 index 0000000..e9a5d67 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecords.go @@ -0,0 +1,55 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" + "github.com/iwind/TeaGo/maps" +) + +type CustomRecordsAction struct { + actionutils.ParentAction +} + +func (this *CustomRecordsAction) Init() { + this.Nav("httpdns", "app", "") +} + +func (this *CustomRecordsAction) RunGet(params struct { + AppId int64 + DomainId int64 +}) { + httpdnsutils.AddLeftMenu(this.Parent()) + + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + httpdnsutils.AddAppTabbar(this.Parent(), app.GetString("name"), app.GetInt64("id"), "domains") + + domains, err := listDomainMaps(this.Parent(), app.GetInt64("id"), "") + if err != nil { + this.ErrorPage(err) + return + } + domain := findDomainMap(domains, params.DomainId) + + records := make([]maps.Map, 0) + if domain.GetInt64("id") > 0 { + records, err = listCustomRuleMaps(this.Parent(), domain.GetInt64("id")) + if err != nil { + this.ErrorPage(err) + return + } + for _, record := range records { + record["domain"] = domain.GetString("name") + record["lineText"] = buildLineText(record) + record["recordValueText"] = buildRecordValueText(record) + } + } + + this.Data["app"] = app + this.Data["domain"] = domain + this.Data["records"] = records + this.Show() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsCreatePopup.go b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsCreatePopup.go new file mode 100644 index 0000000..5321f10 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsCreatePopup.go @@ -0,0 +1,263 @@ +package apps + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/actions" + "github.com/iwind/TeaGo/maps" +) + +type CustomRecordsCreatePopupAction struct { + actionutils.ParentAction +} + +func (this *CustomRecordsCreatePopupAction) Init() { + this.Nav("", "", "") +} + +func (this *CustomRecordsCreatePopupAction) RunGet(params struct { + AppId int64 + DomainId int64 + RecordId int64 +}) { + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + + domains, err := listDomainMaps(this.Parent(), app.GetInt64("id"), "") + if err != nil { + this.ErrorPage(err) + return + } + domain := findDomainMap(domains, params.DomainId) + + record := maps.Map{ + "id": int64(0), + "domain": domain.GetString("name"), + "lineScope": "china", + "lineCarrier": "榛樿", + "lineRegion": "榛樿", + "lineProvince": "榛樿", + "lineContinent": "榛樿", + "lineCountry": "榛樿", + "ruleName": "", + "weightEnabled": false, + "ttl": 30, + "isOn": true, + "recordItemsJson": `[{"type":"A","value":"","weight":100}]`, + } + + if params.RecordId > 0 && domain.GetInt64("id") > 0 { + rules, err := listCustomRuleMaps(this.Parent(), domain.GetInt64("id")) + if err != nil { + this.ErrorPage(err) + return + } + for _, rule := range rules { + if rule.GetInt64("id") != params.RecordId { + continue + } + record["id"] = rule.GetInt64("id") + record["domain"] = domain.GetString("name") + record["lineScope"] = rule.GetString("lineScope") + record["lineCarrier"] = defaultLineField(rule.GetString("lineCarrier")) + record["lineRegion"] = defaultLineField(rule.GetString("lineRegion")) + record["lineProvince"] = defaultLineField(rule.GetString("lineProvince")) + record["lineContinent"] = defaultLineField(rule.GetString("lineContinent")) + record["lineCountry"] = defaultLineField(rule.GetString("lineCountry")) + record["ruleName"] = rule.GetString("ruleName") + record["weightEnabled"] = rule.GetBool("weightEnabled") + record["ttl"] = rule.GetInt("ttl") + record["isOn"] = rule.GetBool("isOn") + record["recordItemsJson"] = marshalJSON(rule["recordValues"], "[]") + break + } + } + + this.Data["app"] = app + this.Data["domain"] = domain + this.Data["record"] = record + this.Data["isEditing"] = params.RecordId > 0 + this.Show() +} + +func (this *CustomRecordsCreatePopupAction) RunPost(params struct { + AppId int64 + DomainId int64 + + RecordId int64 + Domain string + LineScope string + + LineCarrier string + LineRegion string + LineProvince string + LineContinent string + LineCountry string + + RuleName string + RecordItemsJSON string + WeightEnabled bool + Ttl int + IsOn bool + + Must *actions.Must + CSRF *actionutils.CSRF +}) { + params.Must.Field("appId", params.AppId).Gt(0, "璇烽€夋嫨搴旂敤") + params.Must.Field("domainId", params.DomainId).Gt(0, "请选择所属域名") + + params.LineScope = strings.ToLower(strings.TrimSpace(params.LineScope)) + if params.LineScope != "china" && params.LineScope != "overseas" { + params.LineScope = "china" + } + params.RuleName = strings.TrimSpace(params.RuleName) + if len(params.RuleName) == 0 { + this.Fail("请输入规则名称") + return + } + if params.Ttl <= 0 || params.Ttl > 86400 { + this.Fail("TTL值必须在 1-86400 范围内") + return + } + + recordValues, err := parseRecordItemsJSON(params.RecordItemsJSON, params.WeightEnabled) + if err != nil { + this.Fail(err.Error()) + return + } + if len(recordValues) == 0 { + this.Fail("请输入解析记录值") + return + } + if len(recordValues) > 10 { + this.Fail("单个规则最多只能添加 10 条解析记录") + return + } + + lineCarrier := strings.TrimSpace(params.LineCarrier) + lineRegion := strings.TrimSpace(params.LineRegion) + lineProvince := strings.TrimSpace(params.LineProvince) + lineContinent := strings.TrimSpace(params.LineContinent) + lineCountry := strings.TrimSpace(params.LineCountry) + if len(lineCarrier) == 0 { + lineCarrier = "榛樿" + } + if len(lineRegion) == 0 { + lineRegion = "榛樿" + } + if len(lineProvince) == 0 { + lineProvince = "榛樿" + } + if len(lineContinent) == 0 { + lineContinent = "榛樿" + } + if len(lineCountry) == 0 { + lineCountry = "榛樿" + } + if params.LineScope == "overseas" { + lineCarrier = "" + lineRegion = "" + lineProvince = "" + } else { + lineContinent = "" + lineCountry = "" + } + + records := make([]*pb.HTTPDNSRuleRecord, 0, len(recordValues)) + for i, item := range recordValues { + records = append(records, &pb.HTTPDNSRuleRecord{ + Id: 0, + RuleId: 0, + RecordType: item.GetString("type"), + RecordValue: item.GetString("value"), + Weight: int32(item.GetInt("weight")), + Sort: int32(i + 1), + }) + } + + rule := &pb.HTTPDNSCustomRule{ + Id: params.RecordId, + AppId: params.AppId, + DomainId: params.DomainId, + RuleName: params.RuleName, + LineScope: params.LineScope, + LineCarrier: lineCarrier, + LineRegion: lineRegion, + LineProvince: lineProvince, + LineContinent: lineContinent, + LineCountry: lineCountry, + Ttl: int32(params.Ttl), + IsOn: params.IsOn, + Priority: 100, + Records: records, + } + + if params.RecordId > 0 { + err = updateCustomRule(this.Parent(), rule) + } else { + _, err = createCustomRule(this.Parent(), rule) + } + if err != nil { + this.ErrorPage(err) + return + } + + this.Success() +} + +func parseRecordItemsJSON(raw string, weightEnabled bool) ([]maps.Map, error) { + raw = strings.TrimSpace(raw) + if len(raw) == 0 { + return []maps.Map{}, nil + } + + list := []maps.Map{} + if err := json.Unmarshal([]byte(raw), &list); err != nil { + return nil, fmt.Errorf("解析记录格式不正确") + } + + result := make([]maps.Map, 0, len(list)) + for _, item := range list { + recordType := strings.ToUpper(strings.TrimSpace(item.GetString("type"))) + recordValue := strings.TrimSpace(item.GetString("value")) + if len(recordType) == 0 && len(recordValue) == 0 { + continue + } + if recordType != "A" && recordType != "AAAA" { + return nil, fmt.Errorf("记录类型只能是 A 或 AAAA") + } + if len(recordValue) == 0 { + return nil, fmt.Errorf("记录值不能为空") + } + + weight := item.GetInt("weight") + if !weightEnabled { + weight = 100 + } + if weight < 1 || weight > 100 { + return nil, fmt.Errorf("鏉冮噸鍊煎繀椤诲湪 1-100 涔嬮棿") + } + + result = append(result, maps.Map{ + "type": recordType, + "value": recordValue, + "weight": weight, + }) + } + return result, nil +} + +func marshalJSON(v interface{}, fallback string) string { + b, err := json.Marshal(v) + if err != nil { + return fallback + } + return string(b) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsDelete.go b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsDelete.go new file mode 100644 index 0000000..0673a1a --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsDelete.go @@ -0,0 +1,21 @@ +package apps + +import "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + +type CustomRecordsDeleteAction struct { + actionutils.ParentAction +} + +func (this *CustomRecordsDeleteAction) RunPost(params struct { + AppId int64 + RecordId int64 +}) { + if params.RecordId > 0 { + err := deleteCustomRule(this.Parent(), params.RecordId) + if err != nil { + this.ErrorPage(err) + return + } + } + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsToggle.go b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsToggle.go new file mode 100644 index 0000000..c55a70f --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/customRecordsToggle.go @@ -0,0 +1,22 @@ +package apps + +import "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + +type CustomRecordsToggleAction struct { + actionutils.ParentAction +} + +func (this *CustomRecordsToggleAction) RunPost(params struct { + AppId int64 + RecordId int64 + IsOn bool +}) { + if params.RecordId > 0 { + err := toggleCustomRule(this.Parent(), params.RecordId, params.IsOn) + if err != nil { + this.ErrorPage(err) + return + } + } + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/delete.go b/EdgeUser/internal/web/actions/default/httpdns/apps/delete.go new file mode 100644 index 0000000..001af1e --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/delete.go @@ -0,0 +1,48 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" +) + +type DeleteAction struct { + actionutils.ParentAction +} + +func (this *DeleteAction) Init() { + this.Nav("httpdns", "app", "delete") +} + +func (this *DeleteAction) RunGet(params struct { + AppId int64 +}) { + httpdnsutils.AddLeftMenu(this.Parent()) + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + httpdnsutils.AddAppTabbar(this.Parent(), app.GetString("name"), app.GetInt64("id"), "delete") + this.Data["app"] = app + domains, err := listDomainMaps(this.Parent(), app.GetInt64("id"), "") + if err != nil { + this.ErrorPage(err) + return + } + this.Data["domainCount"] = len(domains) + this.Show() +} + +func (this *DeleteAction) RunPost(params struct { + AppId int64 +}) { + if params.AppId > 0 { + err := deleteAppByID(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + } + + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/domains.go b/EdgeUser/internal/web/actions/default/httpdns/apps/domains.go new file mode 100644 index 0000000..44a2aa0 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/domains.go @@ -0,0 +1,39 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" +) + +type DomainsAction struct { + actionutils.ParentAction +} + +func (this *DomainsAction) Init() { + this.Nav("httpdns", "app", "domains") +} + +func (this *DomainsAction) RunGet(params struct { + AppId int64 +}) { + httpdnsutils.AddLeftMenu(this.Parent()) + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + + // 鏋勫缓椤堕儴 tabbar + httpdnsutils.AddAppTabbar(this.Parent(), app.GetString("name"), params.AppId, "domains") + + domains, err := listDomainMaps(this.Parent(), app.GetInt64("id"), "") + if err != nil { + this.ErrorPage(err) + return + } + + this.Data["app"] = app + this.Data["domains"] = domains + this.Data["keyword"] = "" + this.Show() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/domainsCreatePopup.go b/EdgeUser/internal/web/actions/default/httpdns/apps/domainsCreatePopup.go new file mode 100644 index 0000000..b8b7386 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/domainsCreatePopup.go @@ -0,0 +1,44 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/actions" +) + +type DomainsCreatePopupAction struct { + actionutils.ParentAction +} + +func (this *DomainsCreatePopupAction) Init() { + this.Nav("", "", "") +} + +func (this *DomainsCreatePopupAction) RunGet(params struct { + AppId int64 +}) { + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + this.Data["app"] = app + this.Show() +} + +func (this *DomainsCreatePopupAction) RunPost(params struct { + AppId int64 + Domain string + + Must *actions.Must + CSRF *actionutils.CSRF +}) { + params.Must.Field("appId", params.AppId).Gt(0, "璇烽€夋嫨搴旂敤") + params.Must.Field("domain", params.Domain).Require("请输入域名") + + err := createDomain(this.Parent(), params.AppId, params.Domain) + if err != nil { + this.ErrorPage(err) + return + } + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/domainsDelete.go b/EdgeUser/internal/web/actions/default/httpdns/apps/domainsDelete.go new file mode 100644 index 0000000..1cad958 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/domainsDelete.go @@ -0,0 +1,20 @@ +package apps + +import "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + +type DomainsDeleteAction struct { + actionutils.ParentAction +} + +func (this *DomainsDeleteAction) RunPost(params struct { + DomainId int64 +}) { + if params.DomainId > 0 { + err := deleteDomain(this.Parent(), params.DomainId) + if err != nil { + this.ErrorPage(err) + return + } + } + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/formatters.go b/EdgeUser/internal/web/actions/default/httpdns/apps/formatters.go new file mode 100644 index 0000000..6f53142 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/formatters.go @@ -0,0 +1,92 @@ +package apps + +import ( + "strconv" + "strings" + + "github.com/iwind/TeaGo/maps" +) + +func maskSecret(secret string) string { + secret = strings.TrimSpace(secret) + if len(secret) < 4 { + return "******" + } + + prefix := "" + for i := 0; i < len(secret); i++ { + if secret[i] == '_' { + prefix = secret[:i+1] + break + } + } + if len(prefix) == 0 { + prefix = secret[:2] + } + + if len(secret) <= 8 { + return prefix + "xxxx" + } + return prefix + "xxxxxxxx" + secret[len(secret)-4:] +} + +func buildLineText(record maps.Map) string { + parts := []string{} + if strings.TrimSpace(record.GetString("lineScope")) == "overseas" { + parts = append(parts, + strings.TrimSpace(record.GetString("lineContinent")), + strings.TrimSpace(record.GetString("lineCountry")), + ) + } else { + parts = append(parts, + strings.TrimSpace(record.GetString("lineCarrier")), + strings.TrimSpace(record.GetString("lineRegion")), + strings.TrimSpace(record.GetString("lineProvince")), + ) + } + + finalParts := make([]string, 0, len(parts)) + for _, part := range parts { + if len(part) == 0 || part == "榛樿" { + continue + } + finalParts = append(finalParts, part) + } + if len(finalParts) == 0 { + return "榛樿" + } + return strings.Join(finalParts, " / ") +} + +func buildRecordValueText(record maps.Map) string { + values, ok := record["recordValues"].([]maps.Map) + if !ok || len(values) == 0 { + return "-" + } + + weightEnabled := record.GetBool("weightEnabled") + defaultType := strings.ToUpper(strings.TrimSpace(record.GetString("recordType"))) + parts := make([]string, 0, len(values)) + for _, item := range values { + value := strings.TrimSpace(item.GetString("value")) + if len(value) == 0 { + continue + } + recordType := strings.ToUpper(strings.TrimSpace(item.GetString("type"))) + if len(recordType) == 0 { + recordType = defaultType + } + if recordType != "A" && recordType != "AAAA" { + recordType = "A" + } + part := recordType + " " + value + if weightEnabled { + part += "(" + strconv.Itoa(item.GetInt("weight")) + ")" + } + parts = append(parts, part) + } + if len(parts) == 0 { + return "-" + } + return strings.Join(parts, ", ") +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/index.go b/EdgeUser/internal/web/actions/default/httpdns/apps/index.go new file mode 100644 index 0000000..aabd719 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/index.go @@ -0,0 +1,28 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" +) + +type IndexAction struct { + actionutils.ParentAction +} + +func (this *IndexAction) Init() { + this.Nav("httpdns", "app", "") +} + +func (this *IndexAction) RunGet(params struct { + Keyword string +}) { + httpdnsutils.AddLeftMenu(this.Parent()) + this.Data["keyword"] = params.Keyword + apps, err := listAppMaps(this.Parent(), params.Keyword) + if err != nil { + this.ErrorPage(err) + return + } + this.Data["apps"] = apps + this.Show() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/init.go b/EdgeUser/internal/web/actions/default/httpdns/apps/init.go new file mode 100644 index 0000000..e900b4f --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/init.go @@ -0,0 +1,35 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/helpers" + "github.com/iwind/TeaGo" +) + +func init() { + TeaGo.BeforeStart(func(server *TeaGo.Server) { + server. + Helper(helpers.NewUserMustAuth("")). + Data("teaMenu", "httpdns"). + Data("teaSubMenu", "app"). + Prefix("/httpdns/apps"). + Get("", new(IndexAction)). + Get("/app", new(AppAction)). + Get("/sdk", new(SdkAction)). + Get("/sdk/check", new(SdkCheckAction)). + Get("/sdk/download", new(SdkDownloadAction)). + Get("/sdk/doc", new(SdkDocAction)). + GetPost("/app/settings", new(AppSettingsAction)). + Post("/app/settings/toggleSignEnabled", new(AppSettingsToggleSignEnabledAction)). + Post("/app/settings/resetSignSecret", new(AppSettingsResetSignSecretAction)). + Get("/domains", new(DomainsAction)). + Get("/customRecords", new(CustomRecordsAction)). + GetPost("/create", new(CreateAction)). + GetPost("/delete", new(DeleteAction)). + GetPost("/domains/createPopup", new(DomainsCreatePopupAction)). + Post("/domains/delete", new(DomainsDeleteAction)). + GetPost("/customRecords/createPopup", new(CustomRecordsCreatePopupAction)). + Post("/customRecords/delete", new(CustomRecordsDeleteAction)). + Post("/customRecords/toggle", new(CustomRecordsToggleAction)). + EndAll() + }) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/rpc_helpers.go b/EdgeUser/internal/web/actions/default/httpdns/apps/rpc_helpers.go new file mode 100644 index 0000000..6ecd29d --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/rpc_helpers.go @@ -0,0 +1,298 @@ +package apps + +import ( + "errors" + "strconv" + "strings" + "time" + + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/maps" + timeutil "github.com/iwind/TeaGo/utils/time" +) + +func listAppMaps(parent *actionutils.ParentAction, keyword string) ([]maps.Map, error) { + resp, err := parent.RPC().HTTPDNSAppRPC().ListHTTPDNSApps(parent.UserContext(), &pb.ListHTTPDNSAppsRequest{ + Offset: 0, + Size: 10_000, + Keyword: strings.TrimSpace(keyword), + }) + if err != nil { + return nil, err + } + + result := make([]maps.Map, 0, len(resp.GetApps())) + for _, app := range resp.GetApps() { + domainResp, err := parent.RPC().HTTPDNSDomainRPC().ListHTTPDNSDomainsWithAppId(parent.UserContext(), &pb.ListHTTPDNSDomainsWithAppIdRequest{ + AppDbId: app.GetId(), + }) + if err != nil { + return nil, err + } + + result = append(result, appPBToMap(app, int64(len(domainResp.GetDomains())))) + } + + return result, nil +} + +func findAppMap(parent *actionutils.ParentAction, appDbId int64) (maps.Map, error) { + if appDbId > 0 { + resp, err := parent.RPC().HTTPDNSAppRPC().FindHTTPDNSApp(parent.UserContext(), &pb.FindHTTPDNSAppRequest{ + AppDbId: appDbId, + }) + if err != nil { + return nil, err + } + if resp.GetApp() != nil { + domainResp, err := parent.RPC().HTTPDNSDomainRPC().ListHTTPDNSDomainsWithAppId(parent.UserContext(), &pb.ListHTTPDNSDomainsWithAppIdRequest{ + AppDbId: appDbId, + }) + if err != nil { + return nil, err + } + return appPBToMap(resp.GetApp(), int64(len(domainResp.GetDomains()))), nil + } + + return nil, errors.New("应用不存在或无权限访问") + } + + apps, err := listAppMaps(parent, "") + if err != nil { + return nil, err + } + if len(apps) == 0 { + return maps.Map{ + "id": int64(0), + "name": "", + "appId": "", + }, nil + } + return apps[0], nil +} + +func createApp(parent *actionutils.ParentAction, name string, primaryClusterId int64, backupClusterId int64) (int64, error) { + newAppId := "app" + strconv.FormatInt(time.Now().UnixNano()%1_000_000_000_000, 36) + resp, err := parent.RPC().HTTPDNSAppRPC().CreateHTTPDNSApp(parent.UserContext(), &pb.CreateHTTPDNSAppRequest{ + Name: strings.TrimSpace(name), + AppId: newAppId, + PrimaryClusterId: primaryClusterId, + BackupClusterId: backupClusterId, + IsOn: true, + SignEnabled: true, + }) + if err != nil { + return 0, err + } + return resp.GetAppDbId(), nil +} + +func deleteAppByID(parent *actionutils.ParentAction, appDbId int64) error { + _, err := parent.RPC().HTTPDNSAppRPC().DeleteHTTPDNSApp(parent.UserContext(), &pb.DeleteHTTPDNSAppRequest{ + AppDbId: appDbId, + }) + return err +} + +func updateAppSettings(parent *actionutils.ParentAction, appDbId int64, name string, primaryClusterId int64, backupClusterId int64, isOn bool, userId int64) error { + _, err := parent.RPC().HTTPDNSAppRPC().UpdateHTTPDNSApp(parent.UserContext(), &pb.UpdateHTTPDNSAppRequest{ + AppDbId: appDbId, + Name: strings.TrimSpace(name), + PrimaryClusterId: primaryClusterId, + BackupClusterId: backupClusterId, + IsOn: isOn, + UserId: userId, + }) + return err +} + +func updateAppSignEnabled(parent *actionutils.ParentAction, appDbId int64, signEnabled bool) error { + _, err := parent.RPC().HTTPDNSAppRPC().UpdateHTTPDNSAppSignEnabled(parent.UserContext(), &pb.UpdateHTTPDNSAppSignEnabledRequest{ + AppDbId: appDbId, + SignEnabled: signEnabled, + }) + return err +} + +func resetAppSignSecret(parent *actionutils.ParentAction, appDbId int64) (*pb.ResetHTTPDNSAppSignSecretResponse, error) { + return parent.RPC().HTTPDNSAppRPC().ResetHTTPDNSAppSignSecret(parent.UserContext(), &pb.ResetHTTPDNSAppSignSecretRequest{ + AppDbId: appDbId, + }) +} + +func listDomainMaps(parent *actionutils.ParentAction, appDbId int64, keyword string) ([]maps.Map, error) { + resp, err := parent.RPC().HTTPDNSDomainRPC().ListHTTPDNSDomainsWithAppId(parent.UserContext(), &pb.ListHTTPDNSDomainsWithAppIdRequest{ + AppDbId: appDbId, + Keyword: strings.TrimSpace(keyword), + }) + if err != nil { + return nil, err + } + + result := make([]maps.Map, 0, len(resp.GetDomains())) + for _, domain := range resp.GetDomains() { + result = append(result, maps.Map{ + "id": domain.GetId(), + "name": domain.GetDomain(), + "isOn": domain.GetIsOn(), + "customRecordCount": domain.GetRuleCount(), + }) + } + return result, nil +} + +func createDomain(parent *actionutils.ParentAction, appDbId int64, domain string) error { + _, err := parent.RPC().HTTPDNSDomainRPC().CreateHTTPDNSDomain(parent.UserContext(), &pb.CreateHTTPDNSDomainRequest{ + AppDbId: appDbId, + Domain: strings.TrimSpace(domain), + IsOn: true, + }) + return err +} + +func deleteDomain(parent *actionutils.ParentAction, domainId int64) error { + _, err := parent.RPC().HTTPDNSDomainRPC().DeleteHTTPDNSDomain(parent.UserContext(), &pb.DeleteHTTPDNSDomainRequest{ + DomainId: domainId, + }) + return err +} + +func findDomainMap(domains []maps.Map, domainID int64) maps.Map { + if len(domains) == 0 { + return maps.Map{} + } + if domainID <= 0 { + return domains[0] + } + for _, domain := range domains { + if domain.GetInt64("id") == domainID { + return domain + } + } + return domains[0] +} + +func listCustomRuleMaps(parent *actionutils.ParentAction, domainId int64) ([]maps.Map, error) { + resp, err := parent.RPC().HTTPDNSRuleRPC().ListHTTPDNSCustomRulesWithDomainId(parent.UserContext(), &pb.ListHTTPDNSCustomRulesWithDomainIdRequest{ + DomainId: domainId, + }) + if err != nil { + return nil, err + } + + result := make([]maps.Map, 0, len(resp.GetRules())) + for _, rule := range resp.GetRules() { + recordValues := make([]maps.Map, 0, len(rule.GetRecords())) + recordType := "A" + weightEnabled := false + for _, record := range rule.GetRecords() { + if len(recordType) == 0 { + recordType = strings.ToUpper(strings.TrimSpace(record.GetRecordType())) + } + if record.GetWeight() > 0 && record.GetWeight() != 100 { + weightEnabled = true + } + recordValues = append(recordValues, maps.Map{ + "type": strings.ToUpper(strings.TrimSpace(record.GetRecordType())), + "value": record.GetRecordValue(), + "weight": record.GetWeight(), + }) + } + if len(recordValues) == 0 { + recordValues = append(recordValues, maps.Map{ + "type": "A", + "value": "", + "weight": 100, + }) + } + + item := maps.Map{ + "id": rule.GetId(), + "lineScope": rule.GetLineScope(), + "lineCarrier": defaultLineField(rule.GetLineCarrier()), + "lineRegion": defaultLineField(rule.GetLineRegion()), + "lineProvince": defaultLineField(rule.GetLineProvince()), + "lineContinent": defaultLineField(rule.GetLineContinent()), + "lineCountry": defaultLineField(rule.GetLineCountry()), + "ruleName": rule.GetRuleName(), + "recordType": recordType, + "recordValues": recordValues, + "weightEnabled": weightEnabled, + "ttl": rule.GetTtl(), + "isOn": rule.GetIsOn(), + "updatedAt": formatDateTime(rule.GetUpdatedAt()), + } + item["lineText"] = buildLineText(item) + item["recordValueText"] = buildRecordValueText(item) + result = append(result, item) + } + return result, nil +} + +func createCustomRule(parent *actionutils.ParentAction, rule *pb.HTTPDNSCustomRule) (int64, error) { + resp, err := parent.RPC().HTTPDNSRuleRPC().CreateHTTPDNSCustomRule(parent.UserContext(), &pb.CreateHTTPDNSCustomRuleRequest{ + Rule: rule, + }) + if err != nil { + return 0, err + } + return resp.GetRuleId(), nil +} + +func updateCustomRule(parent *actionutils.ParentAction, rule *pb.HTTPDNSCustomRule) error { + _, err := parent.RPC().HTTPDNSRuleRPC().UpdateHTTPDNSCustomRule(parent.UserContext(), &pb.UpdateHTTPDNSCustomRuleRequest{ + Rule: rule, + }) + return err +} + +func deleteCustomRule(parent *actionutils.ParentAction, ruleId int64) error { + _, err := parent.RPC().HTTPDNSRuleRPC().DeleteHTTPDNSCustomRule(parent.UserContext(), &pb.DeleteHTTPDNSCustomRuleRequest{ + RuleId: ruleId, + }) + return err +} + +func toggleCustomRule(parent *actionutils.ParentAction, ruleId int64, isOn bool) error { + _, err := parent.RPC().HTTPDNSRuleRPC().UpdateHTTPDNSCustomRuleStatus(parent.UserContext(), &pb.UpdateHTTPDNSCustomRuleStatusRequest{ + RuleId: ruleId, + IsOn: isOn, + }) + return err +} + +func appPBToMap(app *pb.HTTPDNSApp, domainCount int64) maps.Map { + signSecret := app.GetSignSecret() + return maps.Map{ + "id": app.GetId(), + "name": app.GetName(), + "appId": app.GetAppId(), + "clusterId": app.GetPrimaryClusterId(), + "primaryClusterId": app.GetPrimaryClusterId(), + "backupClusterId": app.GetBackupClusterId(), + "userId": app.GetUserId(), + "isOn": app.GetIsOn(), + "domainCount": domainCount, + "sniPolicyText": "闅愬尶 SNI", + "signEnabled": app.GetSignEnabled(), + "signSecretPlain": signSecret, + "signSecretMasked": maskSecret(signSecret), + "signSecretUpdated": formatDateTime(app.GetSignUpdatedAt()), + } +} + +func defaultLineField(value string) string { + value = strings.TrimSpace(value) + if len(value) == 0 { + return "榛樿" + } + return value +} + +func formatDateTime(ts int64) string { + if ts <= 0 { + return "" + } + return timeutil.FormatTime("Y-m-d H:i:s", ts) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/sdk.go b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk.go new file mode 100644 index 0000000..969cf2c --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk.go @@ -0,0 +1,30 @@ +package apps + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" +) + +type SdkAction struct { + actionutils.ParentAction +} + +func (this *SdkAction) Init() { + this.Nav("httpdns", "app", "sdk") +} + +func (this *SdkAction) RunGet(params struct { + AppId int64 +}) { + httpdnsutils.AddLeftMenu(this.Parent()) + + app, err := findAppMap(this.Parent(), params.AppId) + if err != nil { + this.ErrorPage(err) + return + } + + httpdnsutils.AddAppTabbar(this.Parent(), app.GetString("name"), params.AppId, "sdk") + this.Data["app"] = app + this.Show() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_check.go b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_check.go new file mode 100644 index 0000000..1325000 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_check.go @@ -0,0 +1,67 @@ +package apps + +import ( + "net/url" + "strings" + + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" +) + +type SdkCheckAction struct { + actionutils.ParentAction +} + +func (this *SdkCheckAction) Init() { + this.Nav("", "", "") +} + +func (this *SdkCheckAction) RunGet(params struct { + Platform string + Version string + Type string +}) { + platform, _, _, filename, err := resolveSDKPlatform(params.Platform) + if err != nil { + this.Data["exists"] = false + this.Data["message"] = err.Error() + this.Success() + return + } + + t := strings.ToLower(strings.TrimSpace(params.Type)) + if t == "doc" { + docPath := findUploadedSDKDocPath(platform, params.Version) + if len(docPath) == 0 { + this.Data["exists"] = false + this.Data["message"] = "Documentation is unavailable, please contact admin" + this.Success() + return + } + + downloadURL := "/httpdns/apps/sdk/doc?platform=" + url.QueryEscape(platform) + if len(strings.TrimSpace(params.Version)) > 0 { + downloadURL += "&version=" + url.QueryEscape(strings.TrimSpace(params.Version)) + } + this.Data["exists"] = true + this.Data["url"] = downloadURL + this.Success() + return + } + + archivePath := findSDKArchivePath(filename, params.Version) + if len(archivePath) == 0 { + this.Data["exists"] = false + this.Data["message"] = "SDK package is unavailable, please contact admin" + this.Success() + return + } + + downloadURL := "/httpdns/apps/sdk/download?platform=" + url.QueryEscape(platform) + if len(strings.TrimSpace(params.Version)) > 0 { + downloadURL += "&version=" + url.QueryEscape(strings.TrimSpace(params.Version)) + } + downloadURL += "&raw=1" + this.Data["exists"] = true + this.Data["url"] = downloadURL + this.Success() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_doc.go b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_doc.go new file mode 100644 index 0000000..ce7edb2 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_doc.go @@ -0,0 +1,65 @@ +package apps + +import ( + "os" + "path/filepath" + "strings" + + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" +) + +type SdkDocAction struct { + actionutils.ParentAction +} + +func (this *SdkDocAction) Init() { + this.Nav("", "", "") +} + +func (this *SdkDocAction) RunGet(params struct { + Platform string + Version string +}) { + platform, _, readmeRelativePath, _, err := resolveSDKPlatform(params.Platform) + if err != nil { + this.Data["exists"] = false + this.Data["message"] = err.Error() + this.Success() + return + } + + var data []byte + uploadedDocPath := findUploadedSDKDocPath(platform, params.Version) + if len(uploadedDocPath) > 0 { + data, err = os.ReadFile(uploadedDocPath) + } + + sdkRoot, sdkRootErr := findSDKRoot() + if len(data) == 0 && sdkRootErr == nil { + readmePath := filepath.Join(sdkRoot, readmeRelativePath) + data, err = os.ReadFile(readmePath) + } + + if len(data) == 0 { + localDocPath := findLocalSDKDocPath(platform) + if len(localDocPath) > 0 { + data, err = os.ReadFile(localDocPath) + } + } + + if len(data) == 0 || err != nil { + this.Data["exists"] = false + this.Data["message"] = "SDK documentation is unavailable for current platform, please contact admin" + this.Success() + return + } + + downloadName := filepath.Base(uploadedDocPath) + if len(downloadName) == 0 || downloadName == "." || downloadName == string(filepath.Separator) { + downloadName = "httpdns-sdk-" + strings.ToLower(platform) + ".md" + } + + this.AddHeader("Content-Type", "text/markdown; charset=utf-8") + this.AddHeader("Content-Disposition", "attachment; filename=\""+downloadName+"\";") + _, _ = this.ResponseWriter.Write(data) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_download.go b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_download.go new file mode 100644 index 0000000..0f6f4a7 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_download.go @@ -0,0 +1,65 @@ +package apps + +import ( + "io" + "os" + "path/filepath" + + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" +) + +type SdkDownloadAction struct { + actionutils.ParentAction +} + +func (this *SdkDownloadAction) Init() { + this.Nav("", "", "") +} + +func (this *SdkDownloadAction) RunGet(params struct { + Platform string + Version string + Raw int +}) { + _, _, _, filename, err := resolveSDKPlatform(params.Platform) + if err != nil { + this.Data["exists"] = false + this.Data["message"] = err.Error() + this.Success() + return + } + + archivePath := findSDKArchivePath(filename, params.Version) + if len(archivePath) == 0 { + this.Data["exists"] = false + this.Data["message"] = "SDK archive is unavailable for current platform, please contact admin: " + filename + this.Success() + return + } + + fp, err := os.Open(archivePath) + if err != nil { + this.Data["exists"] = false + this.Data["message"] = "failed to open SDK archive: " + err.Error() + this.Success() + return + } + defer func() { + _ = fp.Close() + }() + + downloadName := filepath.Base(archivePath) + if len(downloadName) == 0 || downloadName == "." || downloadName == string(filepath.Separator) { + downloadName = filename + } + + if params.Raw == 1 { + this.AddHeader("Content-Type", "application/octet-stream") + this.AddHeader("X-SDK-Filename", downloadName) + } else { + this.AddHeader("Content-Type", "application/zip") + this.AddHeader("Content-Disposition", "attachment; filename=\""+downloadName+"\";") + } + this.AddHeader("X-Accel-Buffering", "no") + _, _ = io.Copy(this.ResponseWriter, fp) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_helpers.go b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_helpers.go new file mode 100644 index 0000000..a1095c6 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/apps/sdk_helpers.go @@ -0,0 +1,218 @@ +package apps + +import ( + "errors" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/iwind/TeaGo/Tea" +) + +func sdkUploadDir() string { + dirs := sdkUploadDirs() + if len(dirs) > 0 { + return dirs[0] + } + return filepath.Clean(Tea.Root + "/data/httpdns/sdk") +} + +func sdkUploadDirs() []string { + candidates := []string{ + filepath.Clean(Tea.Root + "/../data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/../edge-admin/data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/../edge-user/data/httpdns/sdk"), + filepath.Clean(Tea.Root + "/../../data/httpdns/sdk"), + } + results := make([]string, 0, len(candidates)) + seen := map[string]bool{} + for _, dir := range candidates { + if len(dir) == 0 || seen[dir] { + continue + } + seen[dir] = true + results = append(results, dir) + } + return results +} + +func sdkUploadSearchDirs() []string { + dirs := sdkUploadDirs() + results := make([]string, 0, len(dirs)) + for _, dir := range dirs { + stat, err := os.Stat(dir) + if err == nil && stat.IsDir() { + results = append(results, dir) + } + } + if len(results) == 0 { + results = append(results, sdkUploadDir()) + } + return results +} + +func findFirstExistingDir(paths []string) string { + for _, path := range paths { + stat, err := os.Stat(path) + if err == nil && stat.IsDir() { + return path + } + } + return "" +} + +func findFirstExistingFile(paths []string) string { + for _, path := range paths { + stat, err := os.Stat(path) + if err == nil && !stat.IsDir() && stat.Size() > 0 { + return path + } + } + return "" +} + +func findNewestExistingFile(paths []string) string { + type fileInfo struct { + path string + modTime time.Time + } + result := fileInfo{} + for _, path := range paths { + stat, err := os.Stat(path) + if err != nil || stat.IsDir() { + continue + } + if stat.Size() <= 0 { + continue + } + if len(result.path) == 0 || stat.ModTime().After(result.modTime) || (stat.ModTime().Equal(result.modTime) && path > result.path) { + result.path = path + result.modTime = stat.ModTime() + } + } + return result.path +} + +func findSDKRoot() (string, error) { + candidates := []string{ + filepath.Clean(Tea.Root + "/EdgeHttpDNS/sdk"), + filepath.Clean(Tea.Root + "/edge-httpdns/sdk"), + filepath.Clean(Tea.Root + "/edge-httpdns/edge-httpdns/sdk"), + filepath.Clean(Tea.Root + "/../EdgeHttpDNS/sdk"), + filepath.Clean(Tea.Root + "/../../EdgeHttpDNS/sdk"), + filepath.Clean(Tea.Root + "/../edge-httpdns/sdk"), + filepath.Clean(Tea.Root + "/../../edge-httpdns/sdk"), + } + + dir := findFirstExistingDir(candidates) + if len(dir) > 0 { + return dir, nil + } + + return "", errors.New("SDK files are not found on current server") +} + +func resolveSDKPlatform(platform string) (key string, relativeDir string, readmeRelativePath string, downloadFilename string, err error) { + switch strings.ToLower(strings.TrimSpace(platform)) { + case "android": + return "android", "android", "android/README.md", "httpdns-sdk-android.zip", nil + case "ios": + return "ios", "ios", "ios/README.md", "httpdns-sdk-ios.zip", nil + case "flutter": + return "flutter", "flutter/aliyun_httpdns", "flutter/aliyun_httpdns/README.md", "httpdns-sdk-flutter.zip", nil + default: + return "", "", "", "", errors.New("invalid platform, expected one of: android, ios, flutter") + } +} + +func findSDKArchivePath(downloadFilename string, version string) string { + searchDirs := sdkUploadSearchDirs() + + normalizedVersion := strings.TrimSpace(version) + base := strings.TrimSuffix(downloadFilename, ".zip") + if len(normalizedVersion) > 0 { + versionFiles := []string{} + for _, dir := range searchDirs { + versionFiles = append(versionFiles, filepath.Join(dir, base+"-v"+normalizedVersion+".zip")) + } + if path := findFirstExistingFile(versionFiles); len(path) > 0 { + return path + } + return "" + } + + patternName := base + "-v*.zip" + matches := []string{} + for _, dir := range searchDirs { + found, _ := filepath.Glob(filepath.Join(dir, patternName)) + for _, file := range found { + stat, err := os.Stat(file) + if err == nil && !stat.IsDir() { + matches = append(matches, file) + } + } + } + if len(matches) > 0 { + return findNewestExistingFile(matches) + } + + exactFiles := []string{} + for _, dir := range searchDirs { + exactFiles = append(exactFiles, filepath.Join(dir, downloadFilename)) + } + if path := findFirstExistingFile(exactFiles); len(path) > 0 { + return path + } + + return "" +} + +func findUploadedSDKDocPath(platform string, version string) string { + platform = strings.ToLower(strings.TrimSpace(platform)) + if len(platform) == 0 { + return "" + } + + searchDirs := sdkUploadSearchDirs() + normalizedVersion := strings.TrimSpace(version) + if len(normalizedVersion) > 0 { + exactVersion := []string{} + for _, dir := range searchDirs { + exactVersion = append(exactVersion, filepath.Join(dir, "httpdns-sdk-"+platform+"-v"+normalizedVersion+".md")) + } + if file := findFirstExistingFile(exactVersion); len(file) > 0 { + return file + } + return "" + } + + matches := []string{} + for _, dir := range searchDirs { + pattern := filepath.Join(dir, "httpdns-sdk-"+platform+"-v*.md") + found, _ := filepath.Glob(pattern) + matches = append(matches, found...) + } + if len(matches) > 0 { + sort.Strings(matches) + return findNewestExistingFile(matches) + } + + exact := []string{} + for _, dir := range searchDirs { + exact = append(exact, filepath.Join(dir, "httpdns-sdk-"+platform+".md")) + } + return findFirstExistingFile(exact) +} + +func findLocalSDKDocPath(platform string) string { + filename := strings.ToLower(strings.TrimSpace(platform)) + ".md" + candidates := []string{ + filepath.Clean(Tea.Root + "/edge-admin/web/views/@default/httpdns/apps/docs/" + filename), + filepath.Clean(Tea.Root + "/EdgeUser/web/views/@default/httpdns/apps/docs/" + filename), + filepath.Clean(Tea.Root + "/EdgeAdmin/web/views/@default/httpdns/apps/docs/" + filename), + } + return findFirstExistingFile(candidates) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils/helper.go b/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils/helper.go new file mode 100644 index 0000000..1856e6f --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils/helper.go @@ -0,0 +1,57 @@ +package httpdnsutils + +import ( + "strconv" + + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/iwind/TeaGo/maps" +) + +func AddLeftMenu(action *actionutils.ParentAction) { + tab := action.Data.GetString("mainTab") + action.Data["teaMenu"] = "httpdns" + action.Data["teaSubMenu"] = tab + action.Data["leftMenuItems"] = []maps.Map{ + { + "name": "\u5e94\u7528\u7ba1\u7406", + "url": "/httpdns/apps", + "isActive": tab == "app", + }, + { + "name": "\u8bbf\u95ee\u65e5\u5fd7", + "url": "/httpdns/resolveLogs", + "isActive": tab == "resolveLogs", + }, + { + "name": "\u89e3\u6790\u6d4b\u8bd5", + "url": "/httpdns/sandbox", + "isActive": tab == "sandbox", + }, + } +} + +// AddClusterTabbar builds the top tabbar on cluster pages. +func AddClusterTabbar(action *actionutils.ParentAction, clusterName string, clusterId int64, selectedTab string) { + cid := strconv.FormatInt(clusterId, 10) + tabbar := actionutils.NewTabbar() + tabbar.Add("", "", "/httpdns/clusters", "arrow left", false) + titleItem := tabbar.Add(clusterName, "", "/httpdns/clusters/cluster?clusterId="+cid, "angle right", true) + titleItem["isTitle"] = true + tabbar.Add("\u8282\u70b9\u5217\u8868", "", "/httpdns/clusters/cluster?clusterId="+cid, "server", selectedTab == "node") + tabbar.Add("\u96c6\u7fa4\u8bbe\u7f6e", "", "/httpdns/clusters/cluster/settings?clusterId="+cid, "setting", selectedTab == "setting") + tabbar.Add("\u5220\u9664\u96c6\u7fa4", "", "/httpdns/clusters/delete?clusterId="+cid, "trash", selectedTab == "delete") + actionutils.SetTabbar(action, tabbar) +} + +// AddAppTabbar builds the top tabbar on app pages. +func AddAppTabbar(action *actionutils.ParentAction, appName string, appId int64, selectedTab string) { + aid := strconv.FormatInt(appId, 10) + tabbar := actionutils.NewTabbar() + tabbar.Add("", "", "/httpdns/apps", "arrow left", false) + titleItem := tabbar.Add(appName, "", "/httpdns/apps/domains?appId="+aid, "angle right", true) + titleItem["isTitle"] = true + tabbar.Add("\u57df\u540d\u5217\u8868", "", "/httpdns/apps/domains?appId="+aid, "list", selectedTab == "domains") + tabbar.Add("\u5e94\u7528\u8bbe\u7f6e", "", "/httpdns/apps/app/settings?appId="+aid, "setting", selectedTab == "settings") + tabbar.Add("\u5220\u9664\u5e94\u7528", "", "/httpdns/apps/delete?appId="+aid, "trash", selectedTab == "delete") + actionutils.SetTabbar(action, tabbar) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/index.go b/EdgeUser/internal/web/actions/default/httpdns/index.go new file mode 100644 index 0000000..aa12486 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/index.go @@ -0,0 +1,11 @@ +package httpdns + +import "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + +type IndexAction struct { + actionutils.ParentAction +} + +func (this *IndexAction) RunGet(params struct{}) { + this.RedirectURL("/httpdns/apps") +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/init.go b/EdgeUser/internal/web/actions/default/httpdns/init.go new file mode 100644 index 0000000..7250741 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/init.go @@ -0,0 +1,18 @@ +package httpdns + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/helpers" + "github.com/iwind/TeaGo" +) + +func init() { + TeaGo.BeforeStart(func(server *TeaGo.Server) { + server. + Helper(helpers.NewUserMustAuth("")). + Data("teaMenu", "httpdns"). + Data("teaSubMenu", "app"). + Prefix("/httpdns"). + Get("", new(IndexAction)). + EndAll() + }) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/resolveLogs/index.go b/EdgeUser/internal/web/actions/default/httpdns/resolveLogs/index.go new file mode 100644 index 0000000..c63c297 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/resolveLogs/index.go @@ -0,0 +1,123 @@ +package resolveLogs + +import ( + "strings" + + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" + timeutil "github.com/iwind/TeaGo/utils/time" +) + +type IndexAction struct { + actionutils.ParentAction +} + +func (this *IndexAction) Init() { + this.Nav("httpdns", "resolveLogs", "") +} + +func (this *IndexAction) RunGet(params struct { + ClusterId int64 + AppId string + Domain string + Status string + Keyword string +}) { + httpdnsutils.AddLeftMenu(this.Parent()) + + if params.ClusterId > 0 { + this.Data["clusterId"] = params.ClusterId + } else { + this.Data["clusterId"] = "" + } + this.Data["appId"] = params.AppId + this.Data["domain"] = params.Domain + this.Data["status"] = params.Status + this.Data["keyword"] = params.Keyword + + clusterResp, err := this.RPC().HTTPDNSClusterRPC().FindAllHTTPDNSClusters(this.UserContext(), &pb.FindAllHTTPDNSClustersRequest{}) + if err != nil { + this.ErrorPage(err) + return + } + clusters := make([]map[string]interface{}, 0, len(clusterResp.GetClusters())) + clusterDomainMap := map[int64]string{} + for _, cluster := range clusterResp.GetClusters() { + serviceDomain := strings.TrimSpace(cluster.GetServiceDomain()) + displayName := serviceDomain + if len(displayName) == 0 { + displayName = cluster.GetName() + } + + clusters = append(clusters, map[string]interface{}{ + "id": cluster.GetId(), + "name": cluster.GetName(), + "serviceDomain": serviceDomain, + "displayName": displayName, + }) + clusterDomainMap[cluster.GetId()] = serviceDomain + } + this.Data["clusters"] = clusters + + logResp, err := this.RPC().HTTPDNSAccessLogRPC().ListHTTPDNSAccessLogs(this.UserContext(), &pb.ListHTTPDNSAccessLogsRequest{ + Day: "", + ClusterId: params.ClusterId, + NodeId: 0, + AppId: strings.TrimSpace(params.AppId), + Domain: strings.TrimSpace(params.Domain), + Status: strings.TrimSpace(params.Status), + Keyword: strings.TrimSpace(params.Keyword), + Offset: 0, + Size: 100, + }) + if err != nil { + this.ErrorPage(err) + return + } + + logs := make([]map[string]interface{}, 0, len(logResp.GetLogs())) + for _, item := range logResp.GetLogs() { + createdTime := "" + if item.GetCreatedAt() > 0 { + createdTime = timeutil.FormatTime("Y-m-d H:i:s", item.GetCreatedAt()) + } + status := item.GetStatus() + if len(status) == 0 { + status = "failed" + } + errorCode := item.GetErrorCode() + if len(errorCode) == 0 { + errorCode = "none" + } + + logs = append(logs, map[string]interface{}{ + "time": createdTime, + "clusterId": item.GetClusterId(), + "serviceDomain": func() string { + serviceDomain := strings.TrimSpace(clusterDomainMap[item.GetClusterId()]) + if len(serviceDomain) > 0 { + return serviceDomain + } + if len(strings.TrimSpace(item.GetClusterName())) > 0 { + return item.GetClusterName() + } + return "-" + }(), + "appName": item.GetAppName(), + "appId": item.GetAppId(), + "domain": item.GetDomain(), + "query": item.GetQtype(), + "clientIp": item.GetClientIP(), + "os": item.GetOs(), + "sdkVersion": item.GetSdkVersion(), + "ips": item.GetResultIPs(), + "status": status, + "errorCode": errorCode, + "costMs": item.GetCostMs(), + }) + } + + this.Data["resolveLogs"] = logs + this.Show() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/resolveLogs/init.go b/EdgeUser/internal/web/actions/default/httpdns/resolveLogs/init.go new file mode 100644 index 0000000..05ce710 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/resolveLogs/init.go @@ -0,0 +1,18 @@ +package resolveLogs + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/helpers" + "github.com/iwind/TeaGo" +) + +func init() { + TeaGo.BeforeStart(func(server *TeaGo.Server) { + server. + Helper(helpers.NewUserMustAuth("")). + Data("teaMenu", "httpdns"). + Data("teaSubMenu", "resolveLogs"). + Prefix("/httpdns/resolveLogs"). + Get("", new(IndexAction)). + EndAll() + }) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/sandbox/index.go b/EdgeUser/internal/web/actions/default/httpdns/sandbox/index.go new file mode 100644 index 0000000..07b4ae1 --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/sandbox/index.go @@ -0,0 +1,74 @@ +package sandbox + +import ( + "strings" + + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/httpdnsutils" + "github.com/iwind/TeaGo/maps" +) + +type IndexAction struct { + actionutils.ParentAction +} + +func (this *IndexAction) Init() { + this.Nav("httpdns", "sandbox", "") +} + +func (this *IndexAction) RunGet(params struct{}) { + httpdnsutils.AddLeftMenu(this.Parent()) + + clusterResp, err := this.RPC().HTTPDNSClusterRPC().FindAllHTTPDNSClusters(this.UserContext(), &pb.FindAllHTTPDNSClustersRequest{}) + if err != nil { + this.ErrorPage(err) + return + } + clusters := make([]maps.Map, 0, len(clusterResp.GetClusters())) + for _, cluster := range clusterResp.GetClusters() { + serviceDomain := strings.TrimSpace(cluster.GetServiceDomain()) + displayName := serviceDomain + if len(displayName) == 0 { + displayName = cluster.GetName() + } + clusters = append(clusters, maps.Map{ + "id": cluster.GetId(), + "name": cluster.GetName(), + "serviceDomain": serviceDomain, + "displayName": displayName, + }) + } + this.Data["clusters"] = clusters + + appResp, err := this.RPC().HTTPDNSAppRPC().FindAllHTTPDNSApps(this.UserContext(), &pb.FindAllHTTPDNSAppsRequest{}) + if err != nil { + this.ErrorPage(err) + return + } + apps := make([]maps.Map, 0, len(appResp.GetApps())) + for _, app := range appResp.GetApps() { + domainResp, err := this.RPC().HTTPDNSDomainRPC().ListHTTPDNSDomainsWithAppId(this.UserContext(), &pb.ListHTTPDNSDomainsWithAppIdRequest{ + AppDbId: app.GetId(), + }) + if err != nil { + this.ErrorPage(err) + return + } + domains := make([]string, 0, len(domainResp.GetDomains())) + for _, domain := range domainResp.GetDomains() { + domains = append(domains, domain.GetDomain()) + } + apps = append(apps, maps.Map{ + "id": app.GetId(), + "name": app.GetName(), + "appId": app.GetAppId(), + "clusterId": app.GetPrimaryClusterId(), + "primaryClusterId": app.GetPrimaryClusterId(), + "backupClusterId": app.GetBackupClusterId(), + "domains": domains, + }) + } + this.Data["apps"] = apps + this.Show() +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/sandbox/init.go b/EdgeUser/internal/web/actions/default/httpdns/sandbox/init.go new file mode 100644 index 0000000..99545ed --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/sandbox/init.go @@ -0,0 +1,19 @@ +package sandbox + +import ( + "github.com/TeaOSLab/EdgeUser/internal/web/helpers" + "github.com/iwind/TeaGo" +) + +func init() { + TeaGo.BeforeStart(func(server *TeaGo.Server) { + server. + Helper(helpers.NewUserMustAuth("")). + Data("teaMenu", "httpdns"). + Data("teaSubMenu", "sandbox"). + Prefix("/httpdns/sandbox"). + Get("", new(IndexAction)). + Post("/test", new(TestAction)). + EndAll() + }) +} diff --git a/EdgeUser/internal/web/actions/default/httpdns/sandbox/test.go b/EdgeUser/internal/web/actions/default/httpdns/sandbox/test.go new file mode 100644 index 0000000..508114f --- /dev/null +++ b/EdgeUser/internal/web/actions/default/httpdns/sandbox/test.go @@ -0,0 +1,154 @@ +package sandbox + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "net/url" + "strconv" + "strings" + "time" + + "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils" + "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/login/loginutils" + "github.com/iwind/TeaGo/maps" + "github.com/iwind/TeaGo/rands" +) + +type TestAction struct { + actionutils.ParentAction +} + +func (this *TestAction) RunPost(params struct { + AppId string + ClusterId int64 + Domain string + ClientIp string + Qtype string +}) { + clientIP := strings.TrimSpace(params.ClientIp) + if len(clientIP) == 0 { + clientIP = strings.TrimSpace(loginutils.RemoteIP(&this.ActionObject)) + } + qtype := strings.ToUpper(strings.TrimSpace(params.Qtype)) + if len(qtype) == 0 { + qtype = "A" + } + + resp, err := this.RPC().HTTPDNSSandboxRPC().TestHTTPDNSResolve(this.UserContext(), &pb.TestHTTPDNSResolveRequest{ + ClusterId: params.ClusterId, + AppId: strings.TrimSpace(params.AppId), + Domain: strings.TrimSpace(params.Domain), + Qtype: qtype, + ClientIP: clientIP, + Sid: "", + SdkVersion: "", + Os: "", + }) + if err != nil { + this.ErrorPage(err) + return + } + + clusterDomain := "" + if params.ClusterId > 0 { + clusterResp, findErr := this.RPC().HTTPDNSClusterRPC().FindAllHTTPDNSClusters(this.UserContext(), &pb.FindAllHTTPDNSClustersRequest{}) + if findErr == nil { + for _, cluster := range clusterResp.GetClusters() { + if cluster.GetId() == params.ClusterId { + clusterDomain = strings.TrimSpace(cluster.GetServiceDomain()) + break + } + } + } + } + if len(clusterDomain) == 0 { + clusterDomain = "httpdns.example.com" + } + query := url.Values{} + query.Set("appId", params.AppId) + query.Set("dn", params.Domain) + query.Set("qtype", qtype) + if len(clientIP) > 0 { + query.Set("cip", clientIP) + } + + signEnabled, signSecret := this.findAppSignConfig(params.AppId) + if signEnabled && len(signSecret) > 0 { + exp := strconv.FormatInt(time.Now().Unix()+300, 10) + nonce := "sandbox-" + rands.HexString(16) + sign := buildSandboxResolveSign(signSecret, params.AppId, params.Domain, qtype, exp, nonce) + query.Set("exp", exp) + query.Set("nonce", nonce) + query.Set("sign", sign) + } + requestURL := "https://" + clusterDomain + "/resolve?" + query.Encode() + + resultCode := 1 + if strings.EqualFold(resp.GetCode(), "SUCCESS") { + resultCode = 0 + } + rows := make([]maps.Map, 0, len(resp.GetRecords())) + ips := make([]string, 0, len(resp.GetRecords())) + lineName := strings.TrimSpace(resp.GetClientCarrier()) + if len(lineName) == 0 { + lineName = "-" + } + for _, record := range resp.GetRecords() { + ips = append(ips, record.GetIp()) + if lineName == "-" && len(record.GetLine()) > 0 { + lineName = record.GetLine() + } + rows = append(rows, maps.Map{ + "domain": resp.GetDomain(), + "type": record.GetType(), + "ip": record.GetIp(), + "ttl": record.GetTtl(), + "region": record.GetRegion(), + "line": record.GetLine(), + }) + } + + this.Data["result"] = maps.Map{ + "code": resultCode, + "message": resp.GetMessage(), + "requestId": resp.GetRequestId(), + "data": maps.Map{ + "request_url": requestURL, + "client_ip": resp.GetClientIP(), + "client_region": resp.GetClientRegion(), + "line_name": lineName, + "ips": ips, + "records": rows, + "ttl": resp.GetTtl(), + }, + } + this.Success() +} + +func (this *TestAction) findAppSignConfig(appId string) (bool, string) { + appId = strings.TrimSpace(appId) + if len(appId) == 0 { + return false, "" + } + + resp, err := this.RPC().HTTPDNSAppRPC().FindAllHTTPDNSApps(this.UserContext(), &pb.FindAllHTTPDNSAppsRequest{}) + if err != nil { + return false, "" + } + + for _, app := range resp.GetApps() { + if strings.EqualFold(strings.TrimSpace(app.GetAppId()), appId) { + return app.GetSignEnabled(), strings.TrimSpace(app.GetSignSecret()) + } + } + return false, "" +} + +func buildSandboxResolveSign(signSecret string, appID string, domain string, qtype string, exp string, nonce string) string { + raw := strings.TrimSpace(appID) + "|" + strings.ToLower(strings.TrimSpace(domain)) + "|" + strings.ToUpper(strings.TrimSpace(qtype)) + "|" + strings.TrimSpace(exp) + "|" + strings.TrimSpace(nonce) + mac := hmac.New(sha256.New, []byte(strings.TrimSpace(signSecret))) + _, _ = mac.Write([]byte(raw)) + return hex.EncodeToString(mac.Sum(nil)) +} diff --git a/EdgeUser/internal/web/helpers/user_must_auth.go b/EdgeUser/internal/web/helpers/user_must_auth.go index 8954213..0ad9358 100644 --- a/EdgeUser/internal/web/helpers/user_must_auth.go +++ b/EdgeUser/internal/web/helpers/user_must_auth.go @@ -426,6 +426,31 @@ func (this *userMustAuth) modules(userId int64, isVerified bool, isIdentified bo },**/ }, }, + { + "code": "httpdns", + "name": "HTTPDNS", + "icon": "shield alternate", + "isOn": registerConfig != nil && + registerConfig.HTTPDNSIsOn && + lists.ContainsString(featureCodes, userconfigs.UserFeatureCodeHTTPDNS), + "subItems": []maps.Map{ + { + "name": "应用管理", + "code": "app", + "url": "/httpdns/apps", + }, + { + "name": "访问日志", + "code": "resolveLogs", + "url": "/httpdns/resolveLogs", + }, + { + "name": "解析测试", + "code": "sandbox", + "url": "/httpdns/sandbox", + }, + }, + }, { "code": "finance", "name": "财务管理", diff --git a/EdgeUser/internal/web/import.go b/EdgeUser/internal/web/import.go index 1a415e8..9f0ed26 100644 --- a/EdgeUser/internal/web/import.go +++ b/EdgeUser/internal/web/import.go @@ -106,6 +106,12 @@ import ( _ "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/ns" _ "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/ns/routes" + // httpdns + _ "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns" + _ "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/apps" + _ "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/resolveLogs" + _ "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/httpdns/sandbox" + // api _ "github.com/TeaOSLab/EdgeUser/internal/web/actions/default/api" diff --git a/EdgeUser/web/views/@default/@layout.html b/EdgeUser/web/views/@default/@layout.html index b66981f..0344605 100644 --- a/EdgeUser/web/views/@default/@layout.html +++ b/EdgeUser/web/views/@default/@layout.html @@ -18,10 +18,10 @@ {$echo "header"} @@ -80,8 +80,8 @@ class="disabled">消息(0) - - + + {{teaUsername}}

- + :class="{active:teaMenu == module.code && (teaSubMenu || '').length == 0, separator:(module.code || '').length == 0}" + :style="(teaMenu == module.code && (teaSubMenu || '').length == 0) ? 'background: rgba(230, 230, 230, 0.45) !important;' : ''"> + {{module.name}} @@ -131,14 +131,14 @@
-
{$echo "footer"} diff --git a/EdgeUser/web/views/@default/httpdns/apps/@menu.html b/EdgeUser/web/views/@default/httpdns/apps/@menu.html new file mode 100644 index 0000000..dda96cc --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/@menu.html @@ -0,0 +1,4 @@ + + 应用列表 + [添加应用] + \ No newline at end of file diff --git a/EdgeUser/web/views/@default/httpdns/apps/appSettings.html b/EdgeUser/web/views/@default/httpdns/apps/appSettings.html new file mode 100644 index 0000000..db09696 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/appSettings.html @@ -0,0 +1,134 @@ +{$layout} +{$template "menu"} +{$template "/left_menu_with_menu"} + + + +
+
+ + + + + + + + + + + + +
应用启用 + +
SNI 防护配置 + 隐匿 SNI +

当前默认采用隐匿 SNI 策略,避免在 TLS 握手阶段暴露业务域名。

+
+ + + + + + + + + + + + + + + + + + + + + + +
App ID + {{settings.appId}} + +
主服务域名 + {{settings.primaryServiceDomain}} + 未配置 + +
备用服务域名 + {{settings.backupServiceDomain}} + 未配置 + +
请求验签 + {{settings.signEnabled ? "已开启" : "已关闭"}} + {{settings.signEnabled ? "关闭请求验签" : "开启请求验签"}} +

打开后,服务端会对请求进行签名校验。

+
加签 Secret +
+ {{signSecretVisible ? settings.signSecretPlain : settings.signSecretMasked}} + + + +
+

最近更新:{{settings.signSecretUpdatedAt}}

+

请求验签已关闭,当前不使用加签 Secret。

+

用于生成鉴权接口的安全密钥。

+
+ + +
+
diff --git a/EdgeUser/web/views/@default/httpdns/apps/appSettings.js b/EdgeUser/web/views/@default/httpdns/apps/appSettings.js new file mode 100644 index 0000000..1f5d8f6 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/appSettings.js @@ -0,0 +1,95 @@ +Tea.context(function () { + this.activeSection = this.activeSection || "basic"; + this.success = NotifyReloadSuccess("保存成功"); + this.signSecretVisible = false; + + this.toggleSignEnabled = function () { + let that = this; + let targetIsOn = !this.settings.signEnabled; + + if (targetIsOn) { + teaweb.confirm("html:开启后,服务端会对解析请求进行签名鉴权,未签名、签名无效或过期的请求都会解析失败,确认开启吗?", function () { + that.$post("/httpdns/apps/app/settings/toggleSignEnabled") + .params({ + appId: that.app.id, + isOn: 1 + }) + .success(function () { + that.settings.signEnabled = true; + teaweb.success("请求验签已开启"); + }); + }); + return; + } + + teaweb.confirm("html:关闭后,服务端不会对解析请求进行签名鉴权,可能存在被刷风险,确认关闭吗?", function () { + that.$post("/httpdns/apps/app/settings/toggleSignEnabled") + .params({ + appId: that.app.id, + isOn: 0 + }) + .success(function () { + that.settings.signEnabled = false; + teaweb.success("请求验签已关闭"); + }); + }); + }; + + this.copySecret = function (text, name) { + if (typeof text != "string" || text.length == 0) { + teaweb.warn("没有可复制的内容"); + return; + } + + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(function () { + teaweb.success(name + "已复制"); + }).catch(function () { + this.copyByTextarea(text, name); + }.bind(this)); + return; + } + + this.copyByTextarea(text, name); + }; + + this.copyByTextarea = function (text, name) { + let input = document.createElement("textarea"); + input.value = text; + input.setAttribute("readonly", "readonly"); + input.style.position = "fixed"; + input.style.left = "-10000px"; + input.style.top = "-10000px"; + document.body.appendChild(input); + input.select(); + + let ok = false; + try { + ok = document.execCommand("copy"); + } catch (e) { + ok = false; + } + document.body.removeChild(input); + + if (ok) { + teaweb.success(name + "已复制"); + } else { + teaweb.warn("复制失败,请手动复制"); + } + }; + + this.resetSignSecret = function () { + let that = this; + teaweb.confirm("确定要重置加签 Secret 吗?", function () { + that.$post("/httpdns/apps/app/settings/resetSignSecret") + .params({ + appId: that.app.id + }) + .success(function () { + teaweb.success("加签 Secret 已重置", function () { + teaweb.reload(); + }); + }); + }); + }; +}); diff --git a/EdgeUser/web/views/@default/httpdns/apps/create.html b/EdgeUser/web/views/@default/httpdns/apps/create.html new file mode 100644 index 0000000..7f329f4 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/create.html @@ -0,0 +1,16 @@ +{$layout} +{$template "menu"} + +
+ + + + + + +
应用名称 * + +

为该 HTTPDNS 应用设置一个便于识别的名称。

+
+ +
\ No newline at end of file diff --git a/EdgeUser/web/views/@default/httpdns/apps/create.js b/EdgeUser/web/views/@default/httpdns/apps/create.js new file mode 100644 index 0000000..79b655f Binary files /dev/null and b/EdgeUser/web/views/@default/httpdns/apps/create.js differ diff --git a/EdgeUser/web/views/@default/httpdns/apps/customRecords.html b/EdgeUser/web/views/@default/httpdns/apps/customRecords.html new file mode 100644 index 0000000..9a0763c --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/customRecords.html @@ -0,0 +1,55 @@ +{$layout} + + + + + {{app.name}} + » + 域名列表 + » +
{{domain.name}}
+ 创建规则 +
+ + + + + + + + + + + + + + + + + + + + + + +
线路规则名称解析记录TTL状态操作
{{record.lineText}}{{record.ruleName}}{{record.recordValueText}}{{record.ttl}}s + 已启用 + 已停用 + + 编辑  |  + {{record.isOn ? "停用" : "启用"}}  |  + 删除 +
+ +当前应用暂无可用域名,请先到域名管理中添加域名。 +当前域名还没有自定义解析规则。 diff --git a/EdgeUser/web/views/@default/httpdns/apps/customRecords.js b/EdgeUser/web/views/@default/httpdns/apps/customRecords.js new file mode 100644 index 0000000..cd65c73 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/customRecords.js @@ -0,0 +1,60 @@ +Tea.context(function () { + if (typeof this.records == "undefined") { + this.records = []; + } + + this.createRecord = function () { + if (!this.domain || !this.domain.id) { + return; + } + teaweb.popup("/httpdns/apps/customRecords/createPopup?appId=" + this.app.id + "&domainId=" + this.domain.id, { + width: "42em", + height: "33em", + title: "新增自定义解析规则", + callback: function () { + teaweb.success("保存成功", function () { + teaweb.reload(); + }); + } + }); + }; + + this.editRecord = function (recordId) { + if (!this.domain || !this.domain.id) { + return; + } + teaweb.popup("/httpdns/apps/customRecords/createPopup?appId=" + this.app.id + "&domainId=" + this.domain.id + "&recordId=" + recordId, { + width: "42em", + height: "33em", + title: "编辑自定义解析规则", + callback: function () { + teaweb.success("保存成功", function () { + teaweb.reload(); + }); + } + }); + }; + + this.deleteRecord = function (recordId) { + let that = this; + teaweb.confirm("确定要删除这条自定义解析规则吗?", function () { + that.$post("/httpdns/apps/customRecords/delete") + .params({ + appId: that.app.id, + recordId: recordId + }) + .refresh(); + }); + }; + + this.toggleRecord = function (record) { + let that = this; + that.$post("/httpdns/apps/customRecords/toggle") + .params({ + appId: that.app.id, + recordId: record.id, + isOn: record.isOn ? 0 : 1 + }) + .refresh(); + }; +}); diff --git a/EdgeUser/web/views/@default/httpdns/apps/customRecordsCreatePopup.html b/EdgeUser/web/views/@default/httpdns/apps/customRecordsCreatePopup.html new file mode 100644 index 0000000..c286ddc --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/customRecordsCreatePopup.html @@ -0,0 +1,160 @@ +{$layout "layout_popup"} + + + +

编辑自定义解析规则

+

新增自定义解析规则

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
域名 *{{record.domain}}
规则名称 * + +

例如:上海电信灰度-v2

+
线路 +
+ + + + + + + +
+
解析记录值 * +
+
+ + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ + 添加记录值 + + {{recordItems.length}}/10 +
+
TTL * +
+ + +
+
状态 +
+ + +
+
+ + +
diff --git a/EdgeUser/web/views/@default/httpdns/apps/customRecordsCreatePopup.js b/EdgeUser/web/views/@default/httpdns/apps/customRecordsCreatePopup.js new file mode 100644 index 0000000..edfd5a7 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/customRecordsCreatePopup.js @@ -0,0 +1,155 @@ +Tea.context(function () { + var vm = this; + + if (typeof vm.record == "undefined" || vm.record == null) { + vm.record = {}; + } + + vm.chinaCarriers = ["默认", "电信", "联通", "移动", "教育网", "鹏博士", "广电"]; + vm.chinaRegions = ["默认", "东北", "华北", "华东", "华南", "华中", "西北", "西南"]; + vm.chinaRegionProvinces = { + "默认": ["默认"], + "东北": ["默认", "辽宁", "吉林", "黑龙江"], + "华北": ["默认", "北京", "天津", "河北", "山西", "内蒙古"], + "华东": ["默认", "上海", "江苏", "浙江", "安徽", "福建", "江西", "山东"], + "华南": ["默认", "广东", "广西", "海南"], + "华中": ["默认", "河南", "湖北", "湖南"], + "西北": ["默认", "陕西", "甘肃", "青海", "宁夏", "新疆"], + "西南": ["默认", "重庆", "四川", "贵州", "云南", "西藏"] + }; + + vm.continents = ["默认", "非洲", "南极洲", "亚洲", "欧洲", "北美洲", "南美洲", "大洋洲"]; + vm.continentCountries = { + "默认": ["默认"], + "非洲": ["默认", "南非", "埃及", "尼日利亚", "肯尼亚", "摩洛哥"], + "南极洲": ["默认"], + "亚洲": ["默认", "中国香港", "中国澳门", "中国台湾", "日本", "韩国", "新加坡", "印度", "泰国", "越南"], + "欧洲": ["默认", "德国", "英国", "法国", "荷兰", "西班牙", "意大利", "俄罗斯"], + "北美洲": ["默认", "美国", "加拿大", "墨西哥"], + "南美洲": ["默认", "巴西", "阿根廷", "智利", "哥伦比亚"], + "大洋洲": ["默认", "澳大利亚", "新西兰"] + }; + + vm.parseJSONList = function (raw) { + if (typeof raw == "undefined" || raw == null || raw == "") { + return []; + } + + if (Array.isArray(raw)) { + return raw; + } + + try { + var list = JSON.parse(raw); + if (Array.isArray(list)) { + return list; + } + } catch (e) { + } + + return []; + }; + + vm.normalizeBoolean = function (value, defaultValue) { + if (typeof value == "boolean") { + return value; + } + if (typeof value == "number") { + return value > 0; + } + if (typeof value == "string") { + value = value.toLowerCase(); + return value == "1" || value == "true" || value == "yes" || value == "on"; + } + return defaultValue; + }; + + vm.record.lineScope = vm.record.lineScope == "overseas" ? "overseas" : "china"; + vm.record.lineCarrier = vm.record.lineCarrier || "默认"; + vm.record.lineRegion = vm.record.lineRegion || "默认"; + vm.record.lineProvince = vm.record.lineProvince || "默认"; + vm.record.lineContinent = vm.record.lineContinent || "默认"; + vm.record.lineCountry = vm.record.lineCountry || "默认"; + vm.record.ruleName = vm.record.ruleName || ""; + vm.record.ttl = vm.record.ttl || 30; + vm.record.weightEnabled = vm.normalizeBoolean(vm.record.weightEnabled, false); + vm.record.isOn = vm.normalizeBoolean(vm.record.isOn, true); + + vm.recordItems = vm.parseJSONList(vm.record.recordItemsJson); + if (vm.recordItems.length == 0) { + vm.recordItems.push({type: "A", value: "", weight: 100}); + } else { + for (var i = 0; i < vm.recordItems.length; i++) { + var item = vm.recordItems[i]; + if (item.type != "A" && item.type != "AAAA") { + item.type = "A"; + } + if (typeof item.weight == "undefined" || item.weight == null || item.weight === "") { + item.weight = 100; + } + } + } + + vm.provinceOptions = ["默认"]; + vm.countryOptions = ["默认"]; + + vm.refreshProvinceOptions = function () { + var provinces = vm.chinaRegionProvinces[vm.record.lineRegion]; + if (!Array.isArray(provinces) || provinces.length == 0) { + provinces = ["默认"]; + } + vm.provinceOptions = provinces; + if (vm.provinceOptions.indexOf(vm.record.lineProvince) < 0) { + vm.record.lineProvince = vm.provinceOptions[0]; + } + }; + + vm.refreshCountryOptions = function () { + var countries = vm.continentCountries[vm.record.lineContinent]; + if (!Array.isArray(countries) || countries.length == 0) { + countries = ["默认"]; + } + vm.countryOptions = countries; + if (vm.countryOptions.indexOf(vm.record.lineCountry) < 0) { + vm.record.lineCountry = vm.countryOptions[0]; + } + }; + + vm.onChinaRegionChange = function () { + vm.refreshProvinceOptions(); + }; + + vm.onContinentChange = function () { + vm.refreshCountryOptions(); + }; + + vm.onLineScopeChange = function () { + if (vm.record.lineScope == "overseas") { + vm.record.lineContinent = vm.record.lineContinent || "默认"; + vm.refreshCountryOptions(); + } else { + vm.record.lineCarrier = vm.record.lineCarrier || "默认"; + vm.record.lineRegion = vm.record.lineRegion || "默认"; + vm.refreshProvinceOptions(); + } + }; + + vm.addRecordItem = function () { + if (vm.recordItems.length >= 10) { + return; + } + vm.recordItems.push({type: "A", value: "", weight: 100}); + }; + + vm.removeRecordItem = function (index) { + if (index < 0 || index >= vm.recordItems.length) { + return; + } + vm.recordItems.splice(index, 1); + if (vm.recordItems.length == 0) { + vm.recordItems.push({type: "A", value: "", weight: 100}); + } + }; + + vm.onLineScopeChange(); +}); diff --git a/EdgeUser/web/views/@default/httpdns/apps/delete.html b/EdgeUser/web/views/@default/httpdns/apps/delete.html new file mode 100644 index 0000000..b374ce3 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/delete.html @@ -0,0 +1,12 @@ +{$layout} + + + {{app.name}} + » +
删除应用
+
+ +
+ +

包含{{domainCount}}域名

+
diff --git a/EdgeUser/web/views/@default/httpdns/apps/delete.js b/EdgeUser/web/views/@default/httpdns/apps/delete.js new file mode 100644 index 0000000..6c30c8e --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/delete.js @@ -0,0 +1,16 @@ +Tea.context(function () { + this.deleteApp = function (appId) { + let that = this; + teaweb.confirm("确定要删除此应用吗?", function () { + that.$post("/httpdns/apps/delete") + .params({ + appId: appId + }) + .success(function () { + teaweb.success("删除成功", function () { + window.location = "/httpdns/apps"; + }); + }); + }); + }; +}); diff --git a/EdgeUser/web/views/@default/httpdns/apps/docs/android.md b/EdgeUser/web/views/@default/httpdns/apps/docs/android.md new file mode 100644 index 0000000..795d558 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/docs/android.md @@ -0,0 +1,36 @@ +# Android SDK + +## 初始化 + +```java +new InitConfig.Builder() + .setContext(context) + .setPrimaryServiceHost("httpdns-a.example.com") + .setBackupServiceHost("httpdns-b.example.com") + .setServicePort(443) + .setSecretKey("your-sign-secret") + .setEnableHttps(true) + .buildFor("app1f1ndpo9"); +``` + +## 解析 + +```java +HTTPDNSResult result = httpDnsService.getHttpDnsResultForHostSyncNonBlocking( + "api.business.com", + RequestIpType.auto, + null, + null +); +``` + +## 官方业务适配器 + +```java +HttpDnsHttpAdapter adapter = HttpDns.buildHttpClientAdapter(httpDnsService); +HttpDnsAdapterResponse resp = adapter.execute( + new HttpDnsAdapterRequest("GET", "https://api.business.com/v1/ping") +); +``` + +固定策略:IP 直连 + 空 SNI + Host=真实域名,不回退到带 SNI。 diff --git a/EdgeUser/web/views/@default/httpdns/apps/docs/flutter.md b/EdgeUser/web/views/@default/httpdns/apps/docs/flutter.md new file mode 100644 index 0000000..7a1b112 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/docs/flutter.md @@ -0,0 +1,35 @@ +# Flutter SDK + +## 初始化 + +```dart +await AliyunHttpdns.init( + appId: 'app1f1ndpo9', + primaryServiceHost: 'httpdns-a.example.com', + backupServiceHost: 'httpdns-b.example.com', + servicePort: 443, + secretKey: 'your-sign-secret', +); +await AliyunHttpdns.build(); +``` + +## 解析 + +```dart +final result = await AliyunHttpdns.resolveHostSyncNonBlocking( + 'api.business.com', + ipType: 'both', +); +``` + +## 官方业务适配器 + +```dart +final adapter = AliyunHttpdns.createHttpAdapter(); +final resp = await adapter.request( + Uri.parse('https://api.business.com/v1/ping'), + method: 'GET', +); +``` + +固定策略:IP 直连 + 空 SNI + Host=真实域名,不回退到带 SNI。 diff --git a/EdgeUser/web/views/@default/httpdns/apps/docs/ios.md b/EdgeUser/web/views/@default/httpdns/apps/docs/ios.md new file mode 100644 index 0000000..a90381e --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/docs/ios.md @@ -0,0 +1,31 @@ +# iOS SDK + +## 初始化 + +```objc +HttpdnsEdgeService *service = [[HttpdnsEdgeService alloc] + initWithAppId:@"app1f1ndpo9" +primaryServiceHost:@"httpdns-a.example.com" + backupServiceHost:@"httpdns-b.example.com" + servicePort:443 + signSecret:@"your-sign-secret"]; +``` + +## 解析 + +```objc +[service resolveHost:@"api.business.com" queryType:@"A" completion:^(HttpdnsEdgeResolveResult * _Nullable result, NSError * _Nullable error) { + // result.ipv4s / result.ipv6s +}]; +``` + +## 官方业务适配器 + +```objc +NSURL *url = [NSURL URLWithString:@"https://api.business.com/v1/ping"]; +[service requestURL:url method:@"GET" headers:nil body:nil completion:^(NSData * _Nullable data, NSHTTPURLResponse * _Nullable response, NSError * _Nullable error) { + // handle +}]; +``` + +固定策略:IP 直连 + 空 SNI + Host=真实域名,不回退到带 SNI。 diff --git a/EdgeUser/web/views/@default/httpdns/apps/domains.html b/EdgeUser/web/views/@default/httpdns/apps/domains.html new file mode 100644 index 0000000..dc0d770 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/domains.html @@ -0,0 +1,62 @@ +{$layout} + +
+ + + + {{app.name}} + » +
域名列表
+ 创建域名 +
+ +
+
+
+ +
+
+ +   + [清除条件] +
+
+
+ + + + + + + + + + + + + + + + + + + + + +
服务域名规则策略操作
+
{{domain.name}}
+
+ {{domain.customRecordCount}} + + 自定义解析 +  |  + 解绑 +
+ +当前应用尚未绑定域名。 +没有匹配的域名。 diff --git a/EdgeUser/web/views/@default/httpdns/apps/domains.js b/EdgeUser/web/views/@default/httpdns/apps/domains.js new file mode 100644 index 0000000..b73b035 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/domains.js @@ -0,0 +1,72 @@ +Tea.context(function () { + if (typeof this.keywordInput == "undefined" || this.keywordInput == null) { + this.keywordInput = ""; + } + if (typeof this.keyword == "undefined" || this.keyword == null) { + this.keyword = ""; + } + + if (typeof this.domains == "undefined" || this.domains == null) { + this.domains = []; + } + + this.keywordInput = String(this.keyword); + + this.doSearch = function () { + this.keyword = String(this.keywordInput || "").trim(); + }; + + this.clearSearch = function () { + this.keywordInput = ""; + this.keyword = ""; + }; + + this.filteredDomains = function () { + let domains = Array.isArray(this.domains) ? this.domains : []; + let keyword = String(this.keyword || "").trim().toLowerCase(); + if (keyword.length == 0) { + return domains; + } + return domains.filter(function (domain) { + let name = (domain.name || "").toLowerCase(); + return name.indexOf(keyword) >= 0; + }); + }; + + this.bindDomain = function () { + teaweb.popup("/httpdns/apps/domains/createPopup?appId=" + this.app.id, { + height: "24em", + width: "46em", + title: "添加域名", + callback: function () { + teaweb.success("保存成功", function () { + teaweb.reload(); + }); + } + }); + }; + + this.deleteApp = function () { + let that = this; + teaweb.confirm("确定要删除当前应用吗?", function () { + that.$post("/httpdns/apps/delete") + .params({ + appId: that.app.id + }) + .success(function () { + window.location = "/httpdns/apps"; + }); + }); + }; + + this.deleteDomain = function (domainId) { + let that = this; + teaweb.confirm("确定要解绑这个域名吗?", function () { + that.$post("/httpdns/apps/domains/delete") + .params({ + domainId: domainId + }) + .refresh(); + }); + }; +}); diff --git a/EdgeUser/web/views/@default/httpdns/apps/domainsCreatePopup.html b/EdgeUser/web/views/@default/httpdns/apps/domainsCreatePopup.html new file mode 100644 index 0000000..f55fd69 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/domainsCreatePopup.html @@ -0,0 +1,18 @@ +{$layout "layout_popup"} + +

添加域名

+ +
+ + + + + + + +
域名 * + +

请输入完整 FQDN,例如 api.example.com

+
+ +
diff --git a/EdgeUser/web/views/@default/httpdns/apps/index.html b/EdgeUser/web/views/@default/httpdns/apps/index.html new file mode 100644 index 0000000..0d9bc35 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/index.html @@ -0,0 +1,71 @@ +{$layout} +{$template "menu"} + +
+ + + +
+
+
+
+ +
+
+ + [清除条件] +
+
+
+ +

暂时没有符合条件的 HTTPDNS 应用。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
应用名称AppID绑定域名数状态操作
+ + + {{app.name}} + + + + {{app.appId}} + + {{app.domainCount}} + + + 域名管理  |  + 应用设置  |  + SDK集成 +
+ +
+
\ No newline at end of file diff --git a/EdgeUser/web/views/@default/httpdns/apps/index.js b/EdgeUser/web/views/@default/httpdns/apps/index.js new file mode 100644 index 0000000..a415a1d --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/index.js @@ -0,0 +1,9 @@ +Tea.context(function () { + if (typeof this.apps == "undefined") { + this.apps = []; + } + + this.createApp = function () { + window.location = "/httpdns/apps/create"; + }; +}); diff --git a/EdgeUser/web/views/@default/httpdns/apps/policies.html b/EdgeUser/web/views/@default/httpdns/apps/policies.html new file mode 100644 index 0000000..0471258 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/policies.html @@ -0,0 +1,78 @@ +{$layout} +{$template "menu"} + +
+ +

HTTPDNS 鍏ㄥ眬绛栫暐

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
鍏ㄥ眬榛樿瑙f瀽 TTL 绉?/td> +
鍏ㄥ眬榛樿 SNI 绛夌骇 + +
+ level1 浠呬娇鐢ㄥ浐瀹?SNI锛屼笉鍚敤 ECS 鍜岃瘉涔︽牎楠岀瓥鐣ャ€?
+
+ level2 浠呭惎鐢ㄩ殣鍖?SNI锛屼笉瑕佹眰閰嶇疆 ECS 涓庤瘉涔︾瓥鐣ャ€?
+
+ level3 鍚敤 ECH锛屽缓璁悓鏃堕厤缃?ECS 涓庤瘉涔︽牎楠岀瓥鐣ャ€?
+
鍏ㄥ眬闄嶇骇瓒呮椂 姣
全局 ECS 掩码策略 + + + IPv4 / + + IPv6 / + + + 仅在“自定义”模式下配置掩码。 + + + +
鍏ㄥ眬璇佷功鏍¢獙绛栫暐 + 证书指纹校验(Pinning) + + 证书 SAN 域名校验 + +
+ + +
+ diff --git a/EdgeUser/web/views/@default/httpdns/apps/policies.js b/EdgeUser/web/views/@default/httpdns/apps/policies.js new file mode 100644 index 0000000..dc96d3c --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/policies.js @@ -0,0 +1,40 @@ +Tea.context(function () { + this.success = NotifyReloadSuccess("保存成功"); + + this.$delay(function () { + this.$watch("policies.defaultSniPolicy", function (level) { + if (level == "level1" || level == "level2") { + this.policies.ecsMode = "off"; + this.policies.pinningMode = "off"; + this.policies.sanMode = "off"; + return; + } + + if (level == "level3") { + if (this.policies.ecsMode == "off") { + this.policies.ecsMode = "auto"; + } + if (this.policies.pinningMode == "off") { + this.policies.pinningMode = "report"; + } + if (this.policies.sanMode == "off") { + this.policies.sanMode = "strict"; + } + } + }); + + this.$watch("policies.ecsMode", function (mode) { + if (this.policies.defaultSniPolicy != "level3") { + return; + } + if (mode == "custom") { + if (!this.policies.ecsIPv4Prefix || this.policies.ecsIPv4Prefix <= 0) { + this.policies.ecsIPv4Prefix = 24; + } + if (!this.policies.ecsIPv6Prefix || this.policies.ecsIPv6Prefix <= 0) { + this.policies.ecsIPv6Prefix = 56; + } + } + }); + }); +}); diff --git a/EdgeUser/web/views/@default/httpdns/apps/sdk.html b/EdgeUser/web/views/@default/httpdns/apps/sdk.html new file mode 100644 index 0000000..c4b7e85 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/sdk.html @@ -0,0 +1,79 @@ +{$layout} + + + + + {{app.name}} + » +
SDK 集成
+
+ +
+
+
+
Android SDK
+
Java / Kotlin
+
适用于 Android 客户端接入。
+
+ +
+ +
+
+
iOS SDK
+
Objective-C / Swift
+
适用于 iOS 客户端接入。
+
+ +
+ +
+
+
Flutter SDK
+
Dart / Plugin
+
适用于 Flutter 跨平台接入。
+
+ +
+
diff --git a/EdgeUser/web/views/@default/httpdns/apps/sdk.js b/EdgeUser/web/views/@default/httpdns/apps/sdk.js new file mode 100644 index 0000000..fcf5fd4 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/apps/sdk.js @@ -0,0 +1,123 @@ +Tea.context(function () { + this.downloadSDK = function (platform, event) { + this.checkAndDownload(platform, "sdk", event) + } + + this.downloadDoc = function (platform, event) { + this.checkAndDownload(platform, "doc", event) + } + + this.checkAndDownload = function (platform, type, event) { + if (event != null && typeof event.preventDefault == "function") { + event.preventDefault() + } + + this.$get("/httpdns/apps/sdk/check") + .params({ + platform: platform, + type: type + }) + .success(function (resp) { + let data = (resp != null && resp.data != null) ? resp.data : {} + if (!data.exists) { + teaweb.warn(data.message || "当前暂无可下载文件") + return + } + if (typeof data.url == "string" && data.url.length > 0) { + this.downloadByBlob(data.url, platform, type) + return + } + teaweb.warn("下载地址生成失败,请稍后重试") + }.bind(this)) + } + + this.downloadByBlob = function (url, platform, type) { + let defaultFileName = "httpdns-sdk-" + platform + (type == "doc" ? ".md" : ".zip") + + let xhr = new XMLHttpRequest() + xhr.open("GET", url, true) + xhr.responseType = "blob" + + xhr.onload = function () { + if (xhr.status < 200 || xhr.status >= 300) { + teaweb.warn("下载失败(HTTP " + xhr.status + ")") + return + } + if (xhr.status == 204) { + teaweb.warn("下载被浏览器扩展或下载工具拦截,请暂时关闭相关扩展后重试") + return + } + + let contentType = (xhr.getResponseHeader("Content-Type") || "").toLowerCase() + if (contentType.indexOf("application/json") >= 0) { + let reader = new FileReader() + reader.onload = function () { + try { + let json = JSON.parse(reader.result) + teaweb.warn((json && json.message) ? json.message : "下载失败,请稍后重试") + } catch (_e) { + teaweb.warn("下载失败,请稍后重试") + } + } + reader.readAsText(xhr.response) + return + } + + let disposition = xhr.getResponseHeader("Content-Disposition") || "" + let fileName = xhr.getResponseHeader("X-SDK-Filename") || this.parseFileName(disposition) || defaultFileName + if (xhr.response == null || xhr.response.size <= 0) { + teaweb.warn("下载文件为空,请检查已上传 SDK 包是否完整") + return + } + this.saveBlob(xhr.response, fileName) + }.bind(this) + + xhr.onerror = function () { + teaweb.warn("下载失败,请检查网络后重试") + } + + xhr.send() + } + + this.parseFileName = function (disposition) { + if (typeof disposition != "string" || disposition.length == 0) { + return "" + } + + let utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i) + if (utf8Match != null && utf8Match.length > 1) { + try { + return decodeURIComponent(utf8Match[1]) + } catch (_e) { + } + } + + let plainMatch = disposition.match(/filename="?([^";]+)"?/i) + if (plainMatch != null && plainMatch.length > 1) { + return plainMatch[1] + } + + return "" + } + + this.saveBlob = function (blob, fileName) { + if (window.navigator != null && typeof window.navigator.msSaveOrOpenBlob == "function") { + window.navigator.msSaveOrOpenBlob(blob, fileName) + return + } + + let objectURL = window.URL.createObjectURL(blob) + let a = document.createElement("a") + a.style.display = "none" + a.href = objectURL + a.download = fileName + document.body.appendChild(a) + a.click() + setTimeout(function () { + window.URL.revokeObjectURL(objectURL) + if (a.parentNode != null) { + a.parentNode.removeChild(a) + } + }, 30000) + } +}) diff --git a/EdgeUser/web/views/@default/httpdns/resolveLogs/@menu.html b/EdgeUser/web/views/@default/httpdns/resolveLogs/@menu.html new file mode 100644 index 0000000..72927ed --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/resolveLogs/@menu.html @@ -0,0 +1,3 @@ + + 访问日志 + diff --git a/EdgeUser/web/views/@default/httpdns/resolveLogs/index.html b/EdgeUser/web/views/@default/httpdns/resolveLogs/index.html new file mode 100644 index 0000000..4332cdd --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/resolveLogs/index.html @@ -0,0 +1,94 @@ +{$layout} + +
+ + + +
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +
+
+
+ +
+ +暂时还没有访问日志。 + +
+
+ + + + + + + + + + + + + + + + + +
HTTPDNS服务域名域名类型概要
{{log.serviceDomain}}{{log.domain}}{{log.query}} +
+ {{log.time}} + | {{log.appName}} ({{log.appId}}) + | {{log.clientIp}} + | {{log.os}}/{{log.sdkVersion}} + | {{log.query}} {{log.domain}} -> + {{log.ips}} + [无记录] + | + 成功 + 失败 + ({{log.errorCode}}) + | {{log.costMs}}ms +
+
+
+
diff --git a/EdgeUser/web/views/@default/httpdns/sandbox/@menu.html b/EdgeUser/web/views/@default/httpdns/sandbox/@menu.html new file mode 100644 index 0000000..397eae3 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/sandbox/@menu.html @@ -0,0 +1,4 @@ + + + 解析测试 + \ No newline at end of file diff --git a/EdgeUser/web/views/@default/httpdns/sandbox/index.html b/EdgeUser/web/views/@default/httpdns/sandbox/index.html new file mode 100644 index 0000000..b21b89d --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/sandbox/index.html @@ -0,0 +1,147 @@ +{$layout} + +
+ +
+
+ +
+
+

解析测试

+
+
+ + +
+
+ + +
+
+ + +
+
+ + +

用于测试 ECS 掩码与区域调度效果。

+
+
+ +
+ + +
+
+ +
+ + + +
+
+
+ + +
+ +
+

请在左侧配置参数后点击「在线解析」。

+
+ + +
+
+
解析中...
+
+
+ + +
+ +
+
+ 解析成功 + 解析失败 ({{response.code}}) +
+

{{response.message}}

+

Request ID: {{response.requestId}}

+
+ + +
+
解析结果
+
+
请求URL
+
+ {{response.data.request_url || '-'}} +
+
+ +
解析结果详情
+
+
+
+
客户端 IP
+
+ {{response.data.client_ip || request.clientIp || '-'}}
+
+
+
+
+
地区
+
{{response.data.client_region || '-'}}
+
+
+
+
+
线路
+
{{response.data.line_name || '-'}}
+
+
+
+ + +
解析记录
+ + + + + + + + + + + + + + + + + + + + + +
解析域名解析类型IP地址TTL地区线路
{{row.domain || + request.domain}}{{row.type || request.qtype}}{{row.ip}}{{row.ttl}}s{{row.region || '-'}}{{row.line || '-'}}
+
+
+
+
+
diff --git a/EdgeUser/web/views/@default/httpdns/sandbox/index.js b/EdgeUser/web/views/@default/httpdns/sandbox/index.js new file mode 100644 index 0000000..5fe7260 --- /dev/null +++ b/EdgeUser/web/views/@default/httpdns/sandbox/index.js @@ -0,0 +1,161 @@ +Tea.context(function () { + this.newRequest = function () { + return { + appId: "", + clusterId: "", + domain: "", + clientIp: "", + qtype: "A" + } + } + + this.request = this.newRequest() + + this.response = { + hasResult: false, + code: -1, + message: "", + data: null, + requestId: "", + resultRows: [] + } + + this.isRequesting = false + this.currentDomains = [] + this.currentClusters = [] + + if (typeof this.apps === "undefined" || this.apps == null) { + this.apps = [] + } + if (typeof this.clusters === "undefined" || this.clusters == null) { + this.clusters = [] + } + + this.onAppChanged = function () { + let selectedApp = null + for (let i = 0; i < this.apps.length; i++) { + if (this.apps[i].appId === this.request.appId) { + selectedApp = this.apps[i] + break + } + } + + if (selectedApp == null) { + this.currentDomains = [] + this.currentClusters = [] + this.request.domain = "" + this.request.clusterId = "" + return + } + + this.currentDomains = Array.isArray(selectedApp.domains) ? selectedApp.domains : [] + + if (this.currentDomains.length > 0) { + if (this.currentDomains.indexOf(this.request.domain) < 0) { + this.request.domain = this.currentDomains[0] + } + } else { + this.request.domain = "" + } + + let primaryClusterId = (typeof selectedApp.primaryClusterId !== "undefined" && selectedApp.primaryClusterId !== null) ? Number(selectedApp.primaryClusterId) : 0 + let backupClusterId = (typeof selectedApp.backupClusterId !== "undefined" && selectedApp.backupClusterId !== null) ? Number(selectedApp.backupClusterId) : 0 + + let allowed = [] + for (let i = 0; i < this.clusters.length; i++) { + let cluster = this.clusters[i] + let clusterId = Number(cluster.id) + if (clusterId <= 0) { + continue + } + if (clusterId === primaryClusterId || clusterId === backupClusterId) { + allowed.push(cluster) + } + } + this.currentClusters = allowed + + if (allowed.length > 0) { + if (!allowed.some((c) => String(c.id) === String(this.request.clusterId))) { + this.request.clusterId = String(allowed[0].id) + } + } else { + this.request.clusterId = "" + } + } + + this.normalizeResultRows = function (data) { + if (typeof data === "undefined" || data == null) { + return [] + } + + if (Array.isArray(data.records) && data.records.length > 0) { + return data.records + } + + let rows = [] + let ips = Array.isArray(data.ips) ? data.ips : [] + let domain = this.request.domain + let qtype = this.request.qtype + let ttl = data.ttl || 0 + let region = data.client_region || "-" + let line = data.line_name || "-" + + ips.forEach(function (ip) { + rows.push({ + domain: domain, + type: qtype, + ip: ip, + ttl: ttl, + region: region, + line: line + }) + }) + + return rows + } + + this.sendTestRequest = function () { + if (this.request.appId.length === 0) { + teaweb.warn("请选择目标应用") + return + } + if (this.request.clusterId.length === 0) { + teaweb.warn("当前应用未绑定可用的 HTTPDNS 服务域名,请先在应用设置中配置主/备集群") + return + } + if (this.request.domain.length === 0) { + teaweb.warn("请选择要解析的域名") + return + } + + this.isRequesting = true + this.response.hasResult = false + + let payload = Object.assign({}, this.request) + + this.$post("/httpdns/sandbox/test") + .params(payload) + .success(function (resp) { + this.response = resp.data.result + this.response.hasResult = true + this.response.resultRows = this.normalizeResultRows(this.response.data) + }) + .done(function () { + this.isRequesting = false + }) + } + + this.resetForm = function () { + this.request = this.newRequest() + this.currentDomains = [] + this.currentClusters = [] + this.response = { + hasResult: false, + code: -1, + message: "", + data: null, + requestId: "", + resultRows: [] + } + } +}) diff --git a/data/httpdns/sdk/httpdns-sdk-android-v1.0.0.md b/data/httpdns/sdk/httpdns-sdk-android-v1.0.0.md new file mode 100644 index 0000000..129d04d --- /dev/null +++ b/data/httpdns/sdk/httpdns-sdk-android-v1.0.0.md @@ -0,0 +1,204 @@ +# DeepAudit 安全审计报告 + +--- + +## 报告信息 + +| 属性 | 内容 | +|----------|-------| +| **项目名称** | cloudwaf | +| **任务 ID** | `b3b752be...` | +| **生成时间** | 2026-01-18 04:30:22 | +| **任务状态** | COMPLETED | +| **耗时** | 21.7 分钟 | + +## 执行摘要 + +**安全评分: 0/100** [未通过] +*严重 - 需要立即进行修复* + +### 漏洞发现概览 + +| 严重程度 | 数量 | 已验证 | +|----------|-------|----------| +| **高危 (HIGH)** | 7 | 0 | +| **中危 (MEDIUM)** | 1 | 0 | +| **总计** | 8 | 0 | + +### 审计指标 + +- **分析文件数:** 9265 / 9265 +- **Agent 迭代次数:** 5 +- **工具调用次数:** 3 +- **Token 消耗:** 11,437 + +## 高危 (High) 漏洞 + +### HIGH-1: 安装过程中敏感信息泄露 + +**[未验证]** | 类型: `hardcoded_secret` + +**AI 置信度:** 95% + +**漏洞描述:** + +setup() 函数将生成的 adminNodeSecret 明文输出到标准输出,攻击者可以通过查看安装日志或控制台输出来获取该敏感信息。 + +**漏洞代码:** + +```python +fmt.Println("Admin Node Secret:", adminNodeSecret) +``` + +**修复建议:** + +1. 不要将敏感信息输出到标准输出;2. 将秘密安全地存储到配置文件中;3. 使用安全的秘密分发机制。 + +--- + +### HIGH-2: Socket通信缺乏认证机制 + +**[未验证]** | 类型: `auth_bypass` + +**AI 置信度:** 90% + +**漏洞描述:** + +gosock.NewSock 创建的 Unix domain socket 没有认证机制,任何能访问 /tmp/edge-api.sock 文件的进程都可以发送 stop 和 restart 命令,导致未授权服务停止或重启。 + +**漏洞代码:** + +```python +sock := gosock.NewSock("/tmp/edge-api.sock") +``` + +**修复建议:** + +1. 为 socket 通信添加认证令牌;2. 限制 socket 文件的权限(如仅限特定用户或组访问);3. 验证命令来源。 + +--- + +### HIGH-3: EdgeAPI/cmd/edge-api/main.go:148 - 读取issues.log文件,可能存在路径遍历风险 + +**[未验证]** | 类型: `path_traversal` + +**AI 置信度:** 60% + +**漏洞描述:** + +EdgeAPI/cmd/edge-api/main.go:148 - 读取issues.log文件,可能存在路径遍历风险 + +--- + +### HIGH-4: EdgeAPI/cmd/edge-api/main.go:92-102 - 使用socket通信,可能存在未授权访问风险 + +**[未验证]** | 类型: `other` + +**AI 置信度:** 60% + +**漏洞描述:** + +EdgeAPI/cmd/edge-api/main.go:92-102 - 使用socket通信,可能存在未授权访问风险 + +--- + +### HIGH-5: SQL注入漏洞 + +**[未验证]** | 类型: `sql_injection` + +**AI 置信度:** 95% + +**漏洞描述:** + +使用 fmt.Sprintf 将用户输入的 name 直接拼接到 SQL 查询中,攻击者可以注入恶意 SQL 代码。 + +**漏洞代码:** + +```python +query := fmt.Sprintf("SELECT * FROM users WHERE name='%s'", name) +``` + +**修复建议:** + +使用参数化查询:db.Query("SELECT * FROM users WHERE name=?", name) + +--- + +### HIGH-6: 服务器端请求伪造(SSRF) + +**[未验证]** | 类型: `ssrf` + +**AI 置信度:** 90% + +**漏洞描述:** + +http.Get(url) 直接使用用户提供的 URL,没有进行验证或过滤,攻击者可以请求内部网络资源。 + +**漏洞代码:** + +```python +resp, err := http.Get(url) +``` + +**修复建议:** + +1. 验证 URL 的协议(仅允许 http/https);2. 使用白名单验证域名;3. 禁用对内部 IP 地址的请求。 + +--- + +### HIGH-7: 硬编码密钥泄露 + +**[未验证]** | 类型: `hardcoded_secret` + +**AI 置信度:** 100% + +**漏洞描述:** + +配置文件中包含硬编码的 AWS 访问密钥、通用密钥和 JWT 密钥,这些密钥可能被泄露。 + +**漏洞代码:** + +```python +AKIAIOSFODNN7EXAMPLE +``` + +**修复建议:** + +1. 从配置文件中移除硬编码密钥;2. 使用环境变量或密钥管理服务(如 AWS Secrets Manager);3. 定期轮换密钥。 + +--- + +## 中危 (Medium) 漏洞 + +### MEDIUM-1: 跨站脚本(XSS)漏洞 + +**[未验证]** | 类型: `xss` + +**AI 置信度:** 85% + +**漏洞描述:** + +username 直接通过 fmt.Fprintf 输出到 HTTP 响应,没有进行 HTML 编码,可能导致反射型 XSS。 + +**漏洞代码:** + +```python +fmt.Fprintf(w, "Welcome, %s!", username) +``` + +**修复建议:** + +对输出进行 HTML 编码:html.EscapeString(username) + +--- + +## 修复优先级建议 + +基于已发现的漏洞,我们建议按以下优先级进行修复: + +1. **高优先级:** 在 1 周内修复 7 个高危漏洞 +2. **中优先级:** 在 2-4 周内修复 1 个中危漏洞 + +--- + +*本报告由 DeepAudit - AI 驱动的安全分析系统生成* diff --git a/data/httpdns/sdk/httpdns-sdk-android-v1.0.0.zip b/data/httpdns/sdk/httpdns-sdk-android-v1.0.0.zip new file mode 100644 index 0000000..d1df992 Binary files /dev/null and b/data/httpdns/sdk/httpdns-sdk-android-v1.0.0.zip differ diff --git a/data/httpdns/sdk/httpdns-sdk-android-v1.0.1.zip b/data/httpdns/sdk/httpdns-sdk-android-v1.0.1.zip new file mode 100644 index 0000000..d1df992 Binary files /dev/null and b/data/httpdns/sdk/httpdns-sdk-android-v1.0.1.zip differ diff --git a/data/httpdns/sdk/httpdns-sdk-ios-v1.0.0.zip b/data/httpdns/sdk/httpdns-sdk-ios-v1.0.0.zip new file mode 100644 index 0000000..8cd661b Binary files /dev/null and b/data/httpdns/sdk/httpdns-sdk-ios-v1.0.0.zip differ diff --git a/~$Edge HTTPDNS 技术需求文档v2.5(1).docx b/~$Edge HTTPDNS 技术需求文档v2.5(1).docx deleted file mode 100644 index 6863381..0000000 Binary files a/~$Edge HTTPDNS 技术需求文档v2.5(1).docx and /dev/null differ