DoRequests executes a list of requests in parallel. The limits parameters is used to limit parallelism per single request.
(ctx context.Context, downstream Handler, reqs []Request, limits Limits)
| 20 | |
| 21 | // DoRequests executes a list of requests in parallel. The limits parameters is used to limit parallelism per single request. |
| 22 | func DoRequests(ctx context.Context, downstream Handler, reqs []Request, limits Limits) ([]RequestResponse, error) { |
| 23 | tenantIDs, err := users.TenantIDs(ctx) |
| 24 | if err != nil { |
| 25 | return nil, httpgrpc.Errorf(http.StatusBadRequest, "%s", err.Error()) |
| 26 | } |
| 27 | |
| 28 | // If one of the requests fail, we want to be able to cancel the rest of them. |
| 29 | ctx, cancel := context.WithCancel(ctx) |
| 30 | defer cancel() |
| 31 | |
| 32 | // Feed all requests to a bounded intermediate channel to limit parallelism. |
| 33 | intermediate := make(chan Request) |
| 34 | go func() { |
| 35 | for _, req := range reqs { |
| 36 | intermediate <- req |
| 37 | } |
| 38 | close(intermediate) |
| 39 | }() |
| 40 | |
| 41 | respChan, errChan := make(chan RequestResponse), make(chan error) |
| 42 | parallelism := min(validation.SmallestPositiveIntPerTenant(tenantIDs, limits.MaxQueryParallelism), len(reqs)) |
| 43 | for range parallelism { |
| 44 | go func() { |
| 45 | for req := range intermediate { |
| 46 | resp, err := downstream.Do(ctx, req) |
| 47 | if err != nil { |
| 48 | errChan <- err |
| 49 | } else { |
| 50 | respChan <- RequestResponse{req, resp} |
| 51 | } |
| 52 | } |
| 53 | }() |
| 54 | } |
| 55 | |
| 56 | resps := make([]RequestResponse, 0, len(reqs)) |
| 57 | var firstErr error |
| 58 | for range reqs { |
| 59 | select { |
| 60 | case resp := <-respChan: |
| 61 | resps = append(resps, resp) |
| 62 | case err := <-errChan: |
| 63 | if firstErr == nil { |
| 64 | cancel() |
| 65 | firstErr = err |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | return resps, firstErr |
| 71 | } |
| 72 | |
| 73 | func SetQueryResponseStats(a *PrometheusResponse, queryStats *stats.QueryStats) { |
| 74 | if queryStats != nil { |