func()

in internal/discovery/discover.go [84:143]


func (s *ServiceDiscover) queryActiveServer(groupId, appKey string) (string, error) {
	urlStr := fmt.Sprintf("http://%s%s?groupId=%s&appKey=%s", s.client.Domain(), ActiveServerQueryURI, groupId, url.QueryEscape(appKey))
	if len(s.client.Namespace()) > 0 {
		urlStr += "&namespace=" + s.client.Namespace()
	}
	if len(s.client.NamespaceSource()) > 0 {
		urlStr += "&namespaceSource=" + s.client.NamespaceSource()
	}
	urlStr += "&enableScale=true"

	resp, err := s.client.HttpClient().Get(urlStr)
	if err != nil {
		return "", fmt.Errorf("http.Get error %w", err)
	}
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("http.Get statusCode %d", resp.StatusCode)
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("read body error %w", err)
	}
	defer resp.Body.Close()
	var respData struct {
		Success   bool
		RequestId string
		Message   string
		Code      int
		Data      interface{}
	}
	err = json.Unmarshal(body, &respData)
	if err != nil {
		return "", fmt.Errorf("unmarshal resp body[%s] fail %w, url=%s", string(body), err, urlStr)
	}
	if !respData.Success {
		return "", fmt.Errorf("result is not success requestId:%s message:%s, url=%s", respData.RequestId, respData.Message, urlStr)
	}

	if respData.Code != GroupHasChild {
		return respData.Data.(string), nil
	}

	// This application group has enabled automatic scaling and has split child nodes, requiring the parsing of all groupIds, and register serverDiscovery.
	var groupResult struct {
		CurrentLeaderAddr string
		GroupIdMap        map[string]string // key=groupId, val=appKey
	}
	err = json.Unmarshal([]byte(respData.Data.(string)), &groupResult)
	if err != nil {
		return "", fmt.Errorf("unmarshal group result[%s] fail %w", respData.Data, err)
	}

	for childGroupId, childAppKey := range groupResult.GroupIdMap {
		triggerChan <- &TriggerEvent{
			ChildGroupId:  childGroupId,
			ChildAppKey:   childAppKey,
			ParentGroupId: groupId,
		}
	}
	return groupResult.CurrentLeaderAddr, nil
}