From cff7259b35d521b7530b786554491971d88f317c Mon Sep 17 00:00:00 2001 From: Tmwakalasya Date: Sun, 29 Nov 2026 13:34:48 -0500 Subject: [PATCH] fix(github): postpone GraphQL throttling until quota resets --- platform/consumer/BUILD.bazel | 1 + platform/consumer/README.md | 1 + platform/consumer/consumer.go | 16 +++ platform/consumer/cooldown_test.go | 92 +++++++++++++++ platform/errs/errs.go | 8 ++ platform/errs/github/BUILD.bazel | 12 ++ platform/errs/github/github.go | 34 ++++++ platform/githubapi/BUILD.bazel | 10 +- platform/githubapi/README.md | 4 + platform/githubapi/githubapi.go | 16 ++- platform/githubapi/ratelimit.go | 53 +++++++++ platform/githubapi/ratelimit_test.go | 95 ++++++++++++++++ platform/http/request.go | 15 ++- .../orchestrator/server/BUILD.bazel | 4 + .../submitqueue/orchestrator/server/main.go | 2 + .../orchestrator/server/ratelimit_test.go | 105 ++++++++++++++++++ 16 files changed, 460 insertions(+), 8 deletions(-) create mode 100644 platform/consumer/cooldown_test.go create mode 100644 platform/errs/github/BUILD.bazel create mode 100644 platform/errs/github/github.go create mode 100644 platform/githubapi/ratelimit.go create mode 100644 platform/githubapi/ratelimit_test.go create mode 100644 service/submitqueue/orchestrator/server/ratelimit_test.go diff --git a/platform/consumer/BUILD.bazel b/platform/consumer/BUILD.bazel index 5a04ed9fc..cba2215ad 100644 --- a/platform/consumer/BUILD.bazel +++ b/platform/consumer/BUILD.bazel @@ -25,6 +25,7 @@ go_test( name = "go_default_test", srcs = [ "consumer_test.go", + "cooldown_test.go", "registry_test.go", ], embed = [":go_default_library"], diff --git a/platform/consumer/README.md b/platform/consumer/README.md index 0c4678a46..9c569b11e 100644 --- a/platform/consumer/README.md +++ b/platform/consumer/README.md @@ -93,6 +93,7 @@ The consumer passes every non-nil controller error through the configured `errs. - **`return nil`** — success, message is acked. - **`delivery.Hold(delayMs)` then `return nil`** — success that chose to wait: the message is postponed instead of acked. It redelivers after the delay as a barrier its partition waits behind, and the redelivery does not count toward the retry limit (`Attempt()` restarts at 1). A hold is only honored on success — if `Process` returns an error, the failure outcome below wins and the recorded hold is discarded (logged, `hold_ignored` counter). Use hold for backoff loops (waiting for a budget slot, polling an external status) instead of acking and republishing to your own topic. +- **Retryable error carrying `errs.RetryDeadline`** — a future Unix-millisecond deadline postpones the delivery using the same durable partition barrier and retry-count reset as Hold. The processing result remains a classified failure for metrics. An expired deadline uses normal Nack behavior, and an explicit permanent classification still rejects. A failed postpone leaves the delivery in flight for visibility-timeout recovery. Repeated throttling can keep a partition waiting indefinitely; this is not a token-wide rate limiter, and already buffered deliveries or other partitions can still call the dependency. - **non-nil, retryable after processing** — message is nacked for redelivery (visibility timeout drives the retry delay). - **non-nil, non-retryable after processing** — message is rejected, which moves it to the DLQ if one is configured for the subscription, or simply acks-and-drops if not. diff --git a/platform/consumer/consumer.go b/platform/consumer/consumer.go index 8240f16c3..45c72c6c6 100644 --- a/platform/consumer/consumer.go +++ b/platform/consumer/consumer.go @@ -478,6 +478,22 @@ func (m *consumer) processDelivery(ctx context.Context, controller Controller, d // carried structure. controllerFailure := errs.Attribution(err) + var deadline errs.RetryDeadline + if errs.IsRetryable(err) && errors.As(err, &deadline) { + if now, retryAt := time.Now().UnixMilli(), deadline.RetryAtMs(); retryAt > now { + delayMs := retryAt - now + postponeOp := metrics.Begin(controllerScope, "postpone", metrics.StorageLatencyBuckets, metrics.TagsFromContext(ctx)...) + postponeErr := delivery.Postpone(ctx, delayMs) + postponeOp.Complete(postponeErr) + if postponeErr != nil { + m.logger.Errorw("failed to postpone dependency cooldown", "controller", controller.Name(), "message_id", msg.ID, "error", postponeErr) + } else { + m.logger.Warnw("dependency cooldown, postponed delivery", "controller", controller.Name(), "message_id", msg.ID, "delay_ms", delayMs, "error", err) + } + return + } + } + // Check if the error is non-retryable (poison pill message) if !errs.IsRetryable(err) { m.logger.Errorw("non-retryable controller error, rejecting message", diff --git a/platform/consumer/cooldown_test.go b/platform/consumer/cooldown_test.go new file mode 100644 index 000000000..87de58bb4 --- /dev/null +++ b/platform/consumer/cooldown_test.go @@ -0,0 +1,92 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package consumer + +import ( + "context" + "fmt" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/require" + "github.com/uber-go/tally" + entityqueue "github.com/uber/submitqueue/platform/base/messagequeue" + "github.com/uber/submitqueue/platform/errs" + consumergatenoop "github.com/uber/submitqueue/platform/extension/consumergate/noop" + queuemock "github.com/uber/submitqueue/platform/extension/messagequeue/mock" + "go.uber.org/mock/gomock" + "go.uber.org/zap" +) + +type cooldownError struct{ at int64 } + +func (e cooldownError) Error() string { return "dependency throttled" } +func (e cooldownError) RetryAtMs() int64 { return e.at } + +func TestConsumer_DependencyCooldown(t *testing.T) { + for _, tt := range []struct { + name string + delay time.Duration + permanent, postponeFails bool + }{ + {name: "wait then succeed", delay: time.Hour}, + {name: "expired deadline uses nack", delay: -time.Second}, + {name: "permanent override uses reject", delay: time.Hour, permanent: true}, + {name: "failed postpone leaves delivery in flight", delay: time.Hour, postponeFails: true}, + } { + t.Run(tt.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctrl := gomock.NewController(t) + c := New(zap.NewNop().Sugar(), tally.NoopScope, TopicRegistry{}, errs.NewClassifierProcessor(), consumergatenoop.New()).(*consumer) + deadline := time.Now().Add(tt.delay).UnixMilli() + cause := fmt.Errorf("provider: %w", cooldownError{at: deadline}) + processErr := errs.NewRetryableDependencyError(cause) + if tt.permanent { + processErr = errs.NewUserError(cause) + } + handler := &testController{} + setupController(handler, "test", testTopicKeyValidate, "group", func(context.Context, Delivery) error { return processErr }) + msg := entityqueue.NewMessage("cooldown", nil, "partition", nil) + msg.Tenant = testTenant + d := queuemock.NewMockDelivery(ctrl) + d.EXPECT().Message().Return(msg).AnyTimes() + d.EXPECT().Metadata().Return(nil).AnyTimes() + d.EXPECT().Attempt().Return(3).AnyTimes() + d.EXPECT().ReceivedAt().Return(time.Now().UnixMilli()).AnyTimes() + d.EXPECT().DeliveryID().Return(msg.ID).AnyTimes() + switch { + case tt.permanent: + d.EXPECT().Reject(gomock.Any(), gomock.Any()).Return(nil) + case tt.delay <= 0: + d.EXPECT().Nack(gomock.Any(), gomock.Any()).Return(nil) + case tt.postponeFails: + d.EXPECT().Postpone(gomock.Any(), tt.delay.Milliseconds()).Return(fmt.Errorf("storage unavailable")) + default: + d.EXPECT().Postpone(gomock.Any(), tt.delay.Milliseconds()).Return(nil) + } + c.processDelivery(context.Background(), handler, d, tally.NoopScope) + if tt.delay > 0 && !tt.permanent && !tt.postponeFails { + // Virtual time advances without wall-clock sleeping; model the queue's redelivery at the deadline. + time.Sleep(tt.delay) + require.Equal(t, deadline, time.Now().UnixMilli()) + processErr = nil + d.EXPECT().Ack(gomock.Any()).Return(nil) + c.processDelivery(context.Background(), handler, d, tally.NoopScope) + } + }) + }) + } +} diff --git a/platform/errs/errs.go b/platform/errs/errs.go index b4c40f984..c453b3899 100644 --- a/platform/errs/errs.go +++ b/platform/errs/errs.go @@ -153,6 +153,14 @@ type Classifier interface { Classify(err error) Verdict } +// RetryDeadline is an optional cooldown carried by a retryable error. Consumers +// postpone until RetryAtMs (Unix milliseconds) without spending retry budget. +// A future deadline blocks subsequent polling in that delivery's partition; +// expired deadlines use normal retries. Classification still controls retryability. +type RetryDeadline interface { + RetryAtMs() int64 +} + // IsUserError reports whether err is or wraps a user error, i.e. an error // produced by NewUserError. Inspects only the framework types in the chain. func IsUserError(err error) bool { diff --git a/platform/errs/github/BUILD.bazel b/platform/errs/github/BUILD.bazel new file mode 100644 index 000000000..58bb2cb69 --- /dev/null +++ b/platform/errs/github/BUILD.bazel @@ -0,0 +1,12 @@ +load("@rules_go//go:def.bzl", "go_library") + +go_library( + name = "go_default_library", + srcs = ["github.go"], + importpath = "github.com/uber/submitqueue/platform/errs/github", + visibility = ["//visibility:public"], + deps = [ + "//platform/errs:go_default_library", + "//platform/githubapi:go_default_library", + ], +) diff --git a/platform/errs/github/github.go b/platform/errs/github/github.go new file mode 100644 index 000000000..587cbb6aa --- /dev/null +++ b/platform/errs/github/github.go @@ -0,0 +1,34 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package github classifies GitHub-specific throttling before generic HTTP statuses. +package github + +import ( + "github.com/uber/submitqueue/platform/errs" + "github.com/uber/submitqueue/platform/githubapi" +) + +// Classifier recognizes rate limits, including GraphQL HTTP 200 and HTTP 403. +// Register it before the HTTP classifier; ordinary permission failures stay permanent. +var Classifier errs.Classifier = classifier{} + +type classifier struct{} + +func (classifier) Classify(err error) errs.Verdict { + if _, ok := err.(*githubapi.RateLimitError); ok { + return errs.InfraDependencyRetryable + } + return errs.Unknown +} diff --git a/platform/githubapi/BUILD.bazel b/platform/githubapi/BUILD.bazel index f50e6c5ab..da0eed75c 100644 --- a/platform/githubapi/BUILD.bazel +++ b/platform/githubapi/BUILD.bazel @@ -2,7 +2,10 @@ load("@rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", - srcs = ["githubapi.go"], + srcs = [ + "githubapi.go", + "ratelimit.go", + ], importpath = "github.com/uber/submitqueue/platform/githubapi", visibility = ["//visibility:public"], deps = ["//platform/http:go_default_library"], @@ -10,7 +13,10 @@ go_library( go_test( name = "go_default_test", - srcs = ["githubapi_test.go"], + srcs = [ + "githubapi_test.go", + "ratelimit_test.go", + ], embed = [":go_default_library"], deps = [ "//platform/http:go_default_library", diff --git a/platform/githubapi/README.md b/platform/githubapi/README.md index 028e4f6a6..66971e80e 100644 --- a/platform/githubapi/README.md +++ b/platform/githubapi/README.md @@ -7,6 +7,10 @@ The parts of a GitHub API request that every direct caller would otherwise repea This package is not a client. Each caller keeps its own `*http.Client` (API root from `platform/http.BaseURLTransport`, auth from a transport) and its own typed requests and responses, and decides what a missing resource means for it. +`QueryGraphQL` preserves recognized throttling as `RateLimitError`, including HTTP 200 GraphQL `RATE_LIMITED` errors, secondary-limit errors, and HTTP 429. HTTP 403 requires rate-limit evidence; ordinary permission failures remain HTTP errors. Its retry deadline honors `Retry-After` and, when remaining quota is zero, `X-RateLimit-Reset`, taking the later deadline when both apply. Missing, malformed, or expired deadlines use a one-minute cooldown, following [GitHub's guidance](https://docs.github.com/en/graphql/overview/rate-limits-and-query-limits-for-the-graphql-api#exceeding-the-rate-limit). The original error remains available through `Unwrap`. + +Hosts register `platform/errs/github.Classifier` before the generic HTTP classifier to classify these errors as retryable dependencies. SubmitQueue's orchestrator does this for its GitHub change provider and validator. REST clients are not changed by this GraphQL-specific handling. + Its Phabricator counterpart, `platform/conduit`, does hold a client, because Conduit reads the API token from the request body, where a transport cannot add it. ## Who uses it diff --git a/platform/githubapi/githubapi.go b/platform/githubapi/githubapi.go index 34e92e2f3..c1d97edd5 100644 --- a/platform/githubapi/githubapi.go +++ b/platform/githubapi/githubapi.go @@ -82,12 +82,19 @@ func QueryGraphQL(ctx context.Context, client *http.Client, req GraphQLRequest, return fmt.Errorf("marshal GraphQL request: %w", err) } // The path is relative: the client's transport roots it at the API. - status, respBody, err := phttp.SendRequest(ctx, client, http.MethodPost, "/graphql", body, setGraphQLHeaders) + status, respBody, headers, err := phttp.SendRequestWithHeaders(ctx, client, http.MethodPost, "/graphql", body, setGraphQLHeaders) if err != nil { return err } if status != http.StatusOK { - return phttp.NewStatusError(status, respBody) + cause := phttp.NewStatusError(status, respBody) + limited := headers.Get("X-RateLimit-Remaining") == "0" || + headers.Get("Retry-After") != "" || + strings.Contains(strings.ToLower(string(respBody)), "secondary rate limit") + if status == http.StatusTooManyRequests || (status == http.StatusForbidden && limited) { + return newRateLimitError(cause, headers) + } + return cause } var resp graphQLResponse @@ -95,6 +102,11 @@ func QueryGraphQL(ctx context.Context, client *http.Client, req GraphQLRequest, return fmt.Errorf("decode GraphQL response: %w", err) } if len(resp.Errors) > 0 { + for _, e := range resp.Errors { + if e.Type == "RATE_LIMITED" || strings.Contains(strings.ToLower(e.Message), "secondary rate limit") { + return newRateLimitError(resp.Errors, headers) + } + } return resp.Errors } if len(resp.Data) == 0 { diff --git a/platform/githubapi/ratelimit.go b/platform/githubapi/ratelimit.go new file mode 100644 index 000000000..b946d5cf8 --- /dev/null +++ b/platform/githubapi/ratelimit.go @@ -0,0 +1,53 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package githubapi + +import ( + "math" + "net/http" + "strconv" + "time" +) + +// RateLimitError preserves a GitHub throttle response and its earliest retry +// time. It does not classify the failure; hosts opt into the GitHub classifier. +type RateLimitError struct { + cause error + retryAtMs int64 +} + +func (e *RateLimitError) Error() string { return e.cause.Error() } +func (e *RateLimitError) Unwrap() error { return e.cause } +func (e *RateLimitError) RetryAtMs() int64 { return e.retryAtMs } + +func newRateLimitError(cause error, headers http.Header) *RateLimitError { + now := time.Now().UnixMilli() + deadline := int64(0) + if seconds, err := strconv.ParseInt(headers.Get("Retry-After"), 10, 64); err == nil && seconds > 0 && seconds <= (math.MaxInt64-now)/1000 { + deadline = now + seconds*1000 + } else if date, err := http.ParseTime(headers.Get("Retry-After")); err == nil { + deadline = date.UnixMilli() + } + if headers.Get("X-RateLimit-Remaining") == "0" { + if seconds, err := strconv.ParseInt(headers.Get("X-RateLimit-Reset"), 10, 64); err == nil && seconds > 0 && seconds <= math.MaxInt64/1000 { + deadline = max(deadline, seconds*1000) + } + } + if deadline <= now { + // GitHub prescribes at least one minute when a secondary limit has no usable deadline. + deadline = now + time.Minute.Milliseconds() + } + return &RateLimitError{cause: cause, retryAtMs: deadline} +} diff --git a/platform/githubapi/ratelimit_test.go b/platform/githubapi/ratelimit_test.go new file mode 100644 index 000000000..41d7f71d1 --- /dev/null +++ b/platform/githubapi/ratelimit_test.go @@ -0,0 +1,95 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package githubapi + +import ( + "context" + "errors" + "io" + "net/http" + "strconv" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + phttp "github.com/uber/submitqueue/platform/http" +) + +type rateLimitTransport func(*http.Request) (*http.Response, error) + +func (f rateLimitTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestQueryGraphQL_RateLimit(t *testing.T) { + for _, tt := range []struct { + name string + status int + body string + headers http.Header + delay time.Duration + }{ + {"primary limit", 200, `{"errors":[{"type":"RATE_LIMITED","message":"API rate limit exceeded"}]}`, http.Header{"X-Ratelimit-Remaining": {"0"}, "X-Ratelimit-Reset": {"future"}}, time.Hour}, + {"secondary limit", 403, `{"message":"You have exceeded a secondary rate limit."}`, http.Header{"Retry-After": {"120"}}, 2 * time.Minute}, + {"secondary GraphQL", 200, `{"errors":[{"message":"You have exceeded a secondary rate limit."}]}`, nil, time.Minute}, + {"429", 429, `{}`, http.Header{"Retry-After": {"90"}}, 90 * time.Second}, + {"later reset wins", 403, `{}`, http.Header{"Retry-After": {"60"}, "X-Ratelimit-Remaining": {"0"}, "X-Ratelimit-Reset": {"future"}}, time.Hour}, + {"reset ignored with remaining quota", 403, `{"message":"secondary rate limit"}`, http.Header{"Retry-After": {"120"}, "X-Ratelimit-Remaining": {"5"}, "X-Ratelimit-Reset": {"future"}}, 2 * time.Minute}, + {"HTTP date", 429, `{}`, http.Header{"Retry-After": {"date"}}, 2 * time.Minute}, + {"missing deadline", 429, `{}`, nil, time.Minute}, + {"malformed deadline", 429, `{}`, http.Header{"Retry-After": {"invalid"}, "X-Ratelimit-Remaining": {"0"}, "X-Ratelimit-Reset": {"invalid"}}, time.Minute}, + {"overflow deadline", 429, `{}`, http.Header{"Retry-After": {"9223372036854775807"}, "X-Ratelimit-Remaining": {"0"}, "X-Ratelimit-Reset": {"9223372036854775807"}}, time.Minute}, + {"past deadline", 429, `{}`, http.Header{"Retry-After": {"-1"}, "X-Ratelimit-Remaining": {"0"}, "X-Ratelimit-Reset": {"past"}}, time.Minute}, + {"permission denied", 403, `{"message":"Resource not accessible"}`, nil, 0}, + {"GraphQL forbidden", 200, `{"errors":[{"type":"FORBIDDEN","message":"Resource not accessible"}]}`, nil, 0}, + } { + t.Run(tt.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + now := time.Now() + if reset := tt.headers.Get("X-RateLimit-Reset"); reset == "future" || reset == "past" { + delta := time.Hour + if reset == "past" { + delta = -time.Minute + } + tt.headers.Set("X-RateLimit-Reset", strconv.FormatInt(now.Add(delta).Unix(), 10)) + } + if tt.headers.Get("Retry-After") == "date" { + tt.headers.Set("Retry-After", now.Add(2*time.Minute).UTC().Format(http.TimeFormat)) + } + client := &http.Client{Transport: rateLimitTransport(func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: tt.status, Header: tt.headers, Body: io.NopCloser(strings.NewReader(tt.body)), Request: r}, nil + })} + var data any + err := QueryGraphQL(context.Background(), client, GraphQLRequest{}, &data) + require.Error(t, err) + var limited *RateLimitError + require.Equal(t, tt.delay > 0, errors.As(err, &limited)) + if tt.delay > 0 { + assert.Equal(t, now.Add(tt.delay).UnixMilli(), limited.RetryAtMs()) + } + if tt.status != 200 { + var statusErr *phttp.StatusError + require.ErrorAs(t, err, &statusErr) + assert.Equal(t, tt.status, statusErr.StatusCode) + assert.Equal(t, tt.body, statusErr.Body) + } else { + var gqlErr graphQLErrors + require.ErrorAs(t, err, &gqlErr) + } + }) + }) + } +} diff --git a/platform/http/request.go b/platform/http/request.go index 16643596a..1bd8c8eef 100644 --- a/platform/http/request.go +++ b/platform/http/request.go @@ -28,6 +28,13 @@ import ( // or decode the body — success, retry, and not-found semantics vary by API, // so that judgment stays with the caller. func SendRequest(ctx context.Context, client *nethttp.Client, method, rawURL string, body []byte, setHeaders func(*nethttp.Request)) (statusCode int, respBody []byte, err error) { + statusCode, respBody, _, err = SendRequestWithHeaders(ctx, client, method, rawURL, body, setHeaders) + return +} + +// SendRequestWithHeaders is SendRequest with response headers retained for +// callers that interpret server-directed cooldowns. +func SendRequestWithHeaders(ctx context.Context, client *nethttp.Client, method, rawURL string, body []byte, setHeaders func(*nethttp.Request)) (statusCode int, respBody []byte, headers nethttp.Header, err error) { var bodyReader io.Reader if body != nil { bodyReader = bytes.NewReader(body) @@ -35,7 +42,7 @@ func SendRequest(ctx context.Context, client *nethttp.Client, method, rawURL str req, err := nethttp.NewRequestWithContext(ctx, method, rawURL, bodyReader) if err != nil { - return 0, nil, fmt.Errorf("create request: %w", err) + return 0, nil, nil, fmt.Errorf("create request: %w", err) } if setHeaders != nil { setHeaders(req) @@ -43,13 +50,13 @@ func SendRequest(ctx context.Context, client *nethttp.Client, method, rawURL str resp, err := client.Do(req) if err != nil { - return 0, nil, fmt.Errorf("send request: %w", err) + return 0, nil, nil, fmt.Errorf("send request: %w", err) } defer resp.Body.Close() respBody, err = io.ReadAll(resp.Body) if err != nil { - return 0, nil, fmt.Errorf("read response: %w", err) + return 0, nil, nil, fmt.Errorf("read response: %w", err) } - return resp.StatusCode, respBody, nil + return resp.StatusCode, respBody, resp.Header, nil } diff --git a/service/submitqueue/orchestrator/server/BUILD.bazel b/service/submitqueue/orchestrator/server/BUILD.bazel index 156161059..9a1d10c6b 100644 --- a/service/submitqueue/orchestrator/server/BUILD.bazel +++ b/service/submitqueue/orchestrator/server/BUILD.bazel @@ -24,6 +24,7 @@ go_library( "//platform/errs:go_default_library", "//platform/errs/generic:go_default_library", "//platform/errs/git:go_default_library", + "//platform/errs/github:go_default_library", "//platform/errs/http:go_default_library", "//platform/errs/mysql:go_default_library", "//platform/extension/consumergate:go_default_library", @@ -130,6 +131,7 @@ go_test( "main_test.go", "profiles_test.go", "queuepausegate_test.go", + "ratelimit_test.go", ], # The pinned git, for the tests that resolve a git change provider against a # real repository. @@ -153,6 +155,7 @@ go_test( "//submitqueue/entity:go_default_library", "//submitqueue/extension/buildrunner:go_default_library", "//submitqueue/extension/changeprovider:go_default_library", + "//submitqueue/extension/changeprovider/github:go_default_library", "//submitqueue/extension/conflict:go_default_library", "//submitqueue/extension/conflict/tango:go_default_library", "//submitqueue/extension/conflict/tango/tangoclient:go_default_library", @@ -160,6 +163,7 @@ go_test( "//submitqueue/extension/speculation/scorer:go_default_library", "//submitqueue/extension/speculation/speculator:go_default_library", "//submitqueue/extension/validator:go_default_library", + "//submitqueue/extension/validator/github:go_default_library", "//submitqueue/orchestrator/extension/storage:go_default_library", "@com_github_data_dog_go_sqlmock//:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", diff --git a/service/submitqueue/orchestrator/server/main.go b/service/submitqueue/orchestrator/server/main.go index 86474a0bf..00c37b8dd 100644 --- a/service/submitqueue/orchestrator/server/main.go +++ b/service/submitqueue/orchestrator/server/main.go @@ -36,6 +36,7 @@ import ( "github.com/uber/submitqueue/platform/errs" genericerrs "github.com/uber/submitqueue/platform/errs/generic" giterrs "github.com/uber/submitqueue/platform/errs/git" + githuberrs "github.com/uber/submitqueue/platform/errs/github" httperrs "github.com/uber/submitqueue/platform/errs/http" mysqlerrs "github.com/uber/submitqueue/platform/errs/mysql" "github.com/uber/submitqueue/platform/extension/consumergate" @@ -452,6 +453,7 @@ func primaryErrorClassifiers() []errs.Classifier { return []errs.Classifier{ genericerrs.Classifier, giterrs.Classifier, + githuberrs.Classifier, // HTTP must precede MySQL's broad net.Error match to retain dependency attribution. httperrs.Classifier, mysqlerrs.Classifier, diff --git a/service/submitqueue/orchestrator/server/ratelimit_test.go b/service/submitqueue/orchestrator/server/ratelimit_test.go new file mode 100644 index 000000000..5e5e8c876 --- /dev/null +++ b/service/submitqueue/orchestrator/server/ratelimit_test.go @@ -0,0 +1,105 @@ +// Copyright (c) 2026 Uber Technologies, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/uber-go/tally" + "go.uber.org/zap" + + "github.com/uber/submitqueue/platform/base/change" + "github.com/uber/submitqueue/platform/errs" + "github.com/uber/submitqueue/submitqueue/entity" + githubprovider "github.com/uber/submitqueue/submitqueue/extension/changeprovider/github" + githubvalidator "github.com/uber/submitqueue/submitqueue/extension/validator/github" +) + +type fixtureTransport func(*http.Request) (*http.Response, error) + +func (f fixtureTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestPrimaryErrorClassifiers_GraphQLRateLimits(t *testing.T) { + // Exercise both public callers with the production classifier wiring. + processor := errs.NewClassifierProcessor(primaryErrorClassifiers()...) + request := entity.Request{Change: change.Change{URIs: []string{ + "github://github.com/uber/submitqueue/pull/123/abcdef0123456789abcdef0123456789abcdef01", + }}} + for _, tt := range []struct { + name string + status int + body string + limited bool + wantError bool + wantRetry bool + }{ + {"graphql_primary_limit", 200, `{"data":null,"errors":[{"type":"RATE_LIMITED","message":"API rate limit exceeded"}]}`, true, true, true}, + {"graphql_secondary_limit", 403, `{"message":"You have exceeded a secondary rate limit."}`, true, true, true}, + {"http_429_control", 429, `{"message":"rate limited"}`, true, true, true}, + {"http_503_control", 503, `{"message":"unavailable"}`, false, true, true}, + {"graphql_forbidden_control", 200, `{"errors":[{"type":"FORBIDDEN","message":"Resource not accessible"}]}`, false, true, false}, + {"http_403_permission_control", 403, `{"message":"Resource not accessible"}`, false, true, false}, + {"valid_data_control", 200, `{"data":{"repository":{"pullRequest":{"number":123,"headRefOid":"abcdef0123456789abcdef0123456789abcdef01","reviewDecision":"APPROVED","mergeStateStatus":"CLEAN","files":{"nodes":[{"path":"main.go"}],"pageInfo":{"hasNextPage":false}}}}}}`, false, false, false}, + } { + t.Run(tt.name, func(t *testing.T) { + calls := 0 + client := &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) { + calls++ + assert.Equal(t, "/graphql", r.URL.Path) + headers := http.Header{} + if tt.limited { + headers.Set("X-RateLimit-Remaining", "0") + headers.Set("X-RateLimit-Reset", "2000000000") + headers.Set("Retry-After", "60") + } + return &http.Response{StatusCode: tt.status, Header: headers, Body: io.NopCloser(strings.NewReader(tt.body)), Request: r}, nil + })} + provider := githubprovider.NewProvider(githubprovider.Params{HTTPClient: client, Logger: zap.NewNop().Sugar(), MetricsScope: tally.NoopScope}) + validator, err := githubvalidator.New(githubvalidator.Params{HTTPClient: client, Host: "github.com", Logger: zap.NewNop().Sugar(), MetricsScope: tally.NoopScope}) + require.NoError(t, err) + for _, caller := range []struct { + name string + call func() error + }{ + {"provider", func() error { _, err := provider.Get(context.Background(), request); return err }}, + {"validator", func() error { return validator.Validate(context.Background(), request) }}, + } { + t.Run(caller.name, func(t *testing.T) { + err := caller.call() + if !tt.wantError { + require.NoError(t, err) + return + } + require.Error(t, err) + classified := processor.Process(err) + t.Logf("retryable=%t dependency=%t error=%v", errs.IsRetryable(classified), errs.IsDependencyError(classified), classified) + assert.Equal(t, tt.wantRetry, errs.IsRetryable(classified)) + if tt.limited { + var deadline errs.RetryDeadline + require.ErrorAs(t, classified, &deadline) + assert.Equal(t, int64(2000000000000), deadline.RetryAtMs()) + } + }) + } + assert.Equal(t, 2, calls) + }) + } +}