Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions platform/consumer/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ go_test(
name = "go_default_test",
srcs = [
"consumer_test.go",
"cooldown_test.go",
"registry_test.go",
],
embed = [":go_default_library"],
Expand Down
1 change: 1 addition & 0 deletions platform/consumer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
16 changes: 16 additions & 0 deletions platform/consumer/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
92 changes: 92 additions & 0 deletions platform/consumer/cooldown_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
})
}
}
8 changes: 8 additions & 0 deletions platform/errs/errs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
12 changes: 12 additions & 0 deletions platform/errs/github/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -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",
],
)
34 changes: 34 additions & 0 deletions platform/errs/github/github.go
Original file line number Diff line number Diff line change
@@ -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
}
10 changes: 8 additions & 2 deletions platform/githubapi/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@ 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"],
)

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",
Expand Down
4 changes: 4 additions & 0 deletions platform/githubapi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 14 additions & 2 deletions platform/githubapi/githubapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,19 +82,31 @@ 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
if err := json.Unmarshal(respBody, &resp); err != nil {
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 {
Expand Down
53 changes: 53 additions & 0 deletions platform/githubapi/ratelimit.go
Original file line number Diff line number Diff line change
@@ -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}
}
Loading