MCPcopy Create free account
hub / github.com/QuantumNous/new-api / fetchJSON

Function fetchJSON

controller/model_sync.go:127–230  ·  view source on GitHub ↗
(ctx context.Context, url string, out *upstreamEnvelope[T])

Source from the content-addressed store, hash-verified

125}
126
127func fetchJSON[T any](ctx context.Context, url string, out *upstreamEnvelope[T]) error {
128 var lastErr error
129 attempts := max(common.GetEnvOrDefault("SYNC_HTTP_RETRY", 3), 1)
130 baseDelay := 200 * time.Millisecond
131 maxMB := common.GetEnvOrDefault("SYNC_HTTP_MAX_MB", 10)
132 maxBytes := int64(maxMB) << 20
133 for attempt := 0; attempt < attempts; attempt++ {
134 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
135 if err != nil {
136 return err
137 }
138 // ETag conditional request
139 cacheMutex.RLock()
140 if et := etagCache[url]; et != "" {
141 req.Header.Set("If-None-Match", et)
142 }
143 cacheMutex.RUnlock()
144
145 resp, err := getHTTPClient().Do(req)
146 if err != nil {
147 lastErr = err
148 // backoff with jitter
149 sleep := baseDelay * time.Duration(1<<attempt)
150 jitter := time.Duration(rand.Intn(150)) * time.Millisecond
151 time.Sleep(sleep + jitter)
152 continue
153 }
154 func() {
155 defer resp.Body.Close()
156 switch resp.StatusCode {
157 case http.StatusOK:
158 // read body into buffer for caching and flexible decode
159 limited := io.LimitReader(resp.Body, maxBytes+1)
160 buf, err := io.ReadAll(limited)
161 if err != nil {
162 lastErr = err
163 return
164 }
165 if int64(len(buf)) > maxBytes {
166 lastErr = errors.New("upstream metadata exceeds size limit")
167 return
168 }
169 // cache body and ETag
170 cacheMutex.Lock()
171 if et := resp.Header.Get("ETag"); et != "" {
172 etagCache[url] = et
173 }
174 bodyCache[url] = buf
175 cacheMutex.Unlock()
176
177 // Try decode as envelope first
178 if err := common.Unmarshal(buf, out); err != nil {
179 // Try decode as pure array
180 var arr []T
181 if err2 := common.Unmarshal(buf, &arr); err2 != nil {
182 lastErr = err
183 return
184 }

Callers 1

fetchMetadataCatalogFunction · 0.85

Calls 9

GetEnvOrDefaultFunction · 0.92
UnmarshalFunction · 0.92
getHTTPClientFunction · 0.85
SetMethod · 0.80
ReadAllMethod · 0.80
UnlockMethod · 0.80
DoMethod · 0.65
CloseMethod · 0.45
GetMethod · 0.45

Tested by

no test coverage detected