|
| 1 | +package internal |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "slices" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/cenkalti/backoff" |
| 13 | + "github.com/pkg/errors" |
| 14 | + "github.com/rs/zerolog/log" |
| 15 | +) |
| 16 | + |
| 17 | +var ( |
| 18 | + DevNetwork = "dev" |
| 19 | + QaNetwork = "qa" |
| 20 | + TestNetwork = "test" |
| 21 | + MainNetwork = "main" |
| 22 | + |
| 23 | + // GraphQlURLs for graphql urls |
| 24 | + GraphQlURLs = map[string][]string{ |
| 25 | + DevNetwork: { |
| 26 | + "https://graphql.dev.grid.tf/graphql", |
| 27 | + "https://graphql.02.dev.grid.tf/graphql", |
| 28 | + }, |
| 29 | + TestNetwork: { |
| 30 | + "https://graphql.test.grid.tf/graphql", |
| 31 | + "https://graphql.02.test.grid.tf/graphql", |
| 32 | + }, |
| 33 | + QaNetwork: { |
| 34 | + "https://graphql.qa.grid.tf/graphql", |
| 35 | + "https://graphql.02.qa.grid.tf/graphql", |
| 36 | + }, |
| 37 | + MainNetwork: { |
| 38 | + "https://graphql.grid.tf/graphql", |
| 39 | + "https://graphql.02.grid.tf/graphql", |
| 40 | + }, |
| 41 | + } |
| 42 | +) |
| 43 | + |
| 44 | +// GraphQl for tf graphql |
| 45 | +type GraphQl struct { |
| 46 | + urls []string |
| 47 | + activeStackIdx int |
| 48 | +} |
| 49 | + |
| 50 | +// NewGraphQl new tf graphql |
| 51 | +func NewGraphQl(network string) (GraphQl, error) { |
| 52 | + if len(network) == 0 { |
| 53 | + return GraphQl{}, errors.New("network is required") |
| 54 | + } |
| 55 | + |
| 56 | + return GraphQl{urls: GraphQlURLs[network], activeStackIdx: 0}, nil |
| 57 | +} |
| 58 | + |
| 59 | +// ListContractsByTwinID returns contracts for a twinID |
| 60 | +func (g *GraphQl) ListRegions() ([]string, error) { |
| 61 | + countriesCount, err := g.getItemTotalCount("countries", "(orderBy: region_ASC)") |
| 62 | + if err != nil { |
| 63 | + return nil, err |
| 64 | + } |
| 65 | + |
| 66 | + countriesData, err := g.query(`query getRegions($countriesCount: Int!){ |
| 67 | + countries(limit: $countriesCount) { |
| 68 | + region |
| 69 | + } |
| 70 | + }`, |
| 71 | + map[string]interface{}{ |
| 72 | + "countriesCount": countriesCount, |
| 73 | + }) |
| 74 | + if err != nil { |
| 75 | + return nil, err |
| 76 | + } |
| 77 | + |
| 78 | + countriesJSONData, err := json.Marshal(countriesData) |
| 79 | + if err != nil { |
| 80 | + return nil, err |
| 81 | + } |
| 82 | + |
| 83 | + var listCountries struct { |
| 84 | + Countries []struct { |
| 85 | + Region string |
| 86 | + } |
| 87 | + } |
| 88 | + err = json.Unmarshal(countriesJSONData, &listCountries) |
| 89 | + if err != nil { |
| 90 | + return nil, err |
| 91 | + } |
| 92 | + |
| 93 | + var regions []string |
| 94 | + for _, c := range listCountries.Countries { |
| 95 | + if !slices.Contains(regions, c.Region) { |
| 96 | + regions = append(regions, c.Region) |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + return regions, nil |
| 101 | +} |
| 102 | + |
| 103 | +// getItemTotalCount return count of items |
| 104 | +func (g *GraphQl) getItemTotalCount(itemName string, options string) (float64, error) { |
| 105 | + countBody := fmt.Sprintf(`query { items: %vConnection%v { count: totalCount } }`, itemName, options) |
| 106 | + requestBody := map[string]interface{}{"query": countBody} |
| 107 | + |
| 108 | + jsonBody, err := json.Marshal(requestBody) |
| 109 | + if err != nil { |
| 110 | + return 0, err |
| 111 | + } |
| 112 | + |
| 113 | + bodyReader := bytes.NewReader(jsonBody) |
| 114 | + |
| 115 | + countResponse, err := g.httpPost(bodyReader) |
| 116 | + if err != nil { |
| 117 | + return 0, err |
| 118 | + } |
| 119 | + |
| 120 | + queryData, err := parseHTTPResponse(countResponse) |
| 121 | + if err != nil { |
| 122 | + return 0, err |
| 123 | + } |
| 124 | + |
| 125 | + countMap := queryData["data"].(map[string]interface{}) |
| 126 | + countItems := countMap["items"].(map[string]interface{}) |
| 127 | + count := countItems["count"].(float64) |
| 128 | + |
| 129 | + return count, nil |
| 130 | +} |
| 131 | + |
| 132 | +// query queries graphql |
| 133 | +func (g *GraphQl) query(body string, variables map[string]interface{}) (map[string]interface{}, error) { |
| 134 | + result := make(map[string]interface{}) |
| 135 | + |
| 136 | + requestBody := map[string]interface{}{"query": body, "variables": variables} |
| 137 | + jsonBody, err := json.Marshal(requestBody) |
| 138 | + if err != nil { |
| 139 | + return result, err |
| 140 | + } |
| 141 | + |
| 142 | + bodyReader := bytes.NewReader(jsonBody) |
| 143 | + |
| 144 | + resp, err := g.httpPost(bodyReader) |
| 145 | + if err != nil { |
| 146 | + return result, err |
| 147 | + } |
| 148 | + |
| 149 | + queryData, err := parseHTTPResponse(resp) |
| 150 | + if err != nil { |
| 151 | + return result, err |
| 152 | + } |
| 153 | + |
| 154 | + result = queryData["data"].(map[string]interface{}) |
| 155 | + return result, nil |
| 156 | +} |
| 157 | + |
| 158 | +func parseHTTPResponse(resp *http.Response) (map[string]interface{}, error) { |
| 159 | + resBody, err := io.ReadAll(resp.Body) |
| 160 | + if err != nil { |
| 161 | + return map[string]interface{}{}, err |
| 162 | + } |
| 163 | + |
| 164 | + defer resp.Body.Close() |
| 165 | + |
| 166 | + var data map[string]interface{} |
| 167 | + err = json.Unmarshal(resBody, &data) |
| 168 | + if err != nil { |
| 169 | + return map[string]interface{}{}, err |
| 170 | + } |
| 171 | + |
| 172 | + if resp.StatusCode >= 400 { |
| 173 | + return map[string]interface{}{}, errors.Errorf("request failed with status code: %d with error %v", resp.StatusCode, data) |
| 174 | + } |
| 175 | + |
| 176 | + return data, nil |
| 177 | +} |
| 178 | + |
| 179 | +func (g *GraphQl) httpPost(body io.Reader) (*http.Response, error) { |
| 180 | + cl := &http.Client{ |
| 181 | + Timeout: 10 * time.Second, |
| 182 | + } |
| 183 | + |
| 184 | + var ( |
| 185 | + endpoint string |
| 186 | + reqErr error |
| 187 | + resp *http.Response |
| 188 | + ) |
| 189 | + |
| 190 | + backoffCfg := backoff.WithMaxRetries( |
| 191 | + backoff.NewConstantBackOff(1*time.Millisecond), |
| 192 | + 2, |
| 193 | + ) |
| 194 | + |
| 195 | + err := backoff.RetryNotify(func() error { |
| 196 | + endpoint = g.urls[g.activeStackIdx] |
| 197 | + log.Debug().Str("url", endpoint).Msg("checking") |
| 198 | + |
| 199 | + resp, reqErr = cl.Post(endpoint, "application/json", body) |
| 200 | + if reqErr != nil && |
| 201 | + (errors.Is(reqErr, http.ErrAbortHandler) || |
| 202 | + errors.Is(reqErr, http.ErrHandlerTimeout) || |
| 203 | + errors.Is(reqErr, http.ErrServerClosed)) { |
| 204 | + g.activeStackIdx = (g.activeStackIdx + 1) % len(g.urls) |
| 205 | + return reqErr |
| 206 | + } |
| 207 | + |
| 208 | + return nil |
| 209 | + }, backoffCfg, func(err error, _ time.Duration) { |
| 210 | + log.Error().Err(err).Msg("failed to connect to endpoint, retrying") |
| 211 | + }) |
| 212 | + |
| 213 | + if err != nil { |
| 214 | + log.Error().Err(err).Msg("failed to connect to endpoint") |
| 215 | + } |
| 216 | + |
| 217 | + return resp, reqErr |
| 218 | +} |
0 commit comments