-
Notifications
You must be signed in to change notification settings - Fork 607
ratelimit clustering #2986
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
ratelimit clustering #2986
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c5528bd
ci: release agent
chronark 30b4f1b
perf: add permission and key caches
chronark 8f1abc9
Merge branch 'main' of https://github.com/unkeyed/unkey
chronark 57e5a78
test: run clustered ratelimit tests
chronark c1ff76a
[autofix.ci] apply automated fixes
autofix-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| package integration | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "net/http" | ||
| "os" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| "github.com/unkeyed/unkey/go/apps/api" | ||
| "github.com/unkeyed/unkey/go/pkg/db" | ||
| "github.com/unkeyed/unkey/go/pkg/otel/logging" | ||
| "github.com/unkeyed/unkey/go/pkg/port" | ||
| "github.com/unkeyed/unkey/go/pkg/testutil/containers" | ||
| "github.com/unkeyed/unkey/go/pkg/testutil/seed" | ||
| ) | ||
|
|
||
| // ClusterNode represents a running instance of the API server | ||
| type ClusterNode struct { | ||
| InstanceID string | ||
| HttpPort int | ||
| RPCPort int | ||
| GossipPort int | ||
| } | ||
|
|
||
| // Harness is a test harness for creating and managing a cluster of API nodes | ||
| type Harness struct { | ||
| t *testing.T | ||
| ctx context.Context | ||
| cancel context.CancelFunc | ||
| nodes []ClusterNode | ||
| ports *port.FreePort | ||
| containerMgr *containers.Containers | ||
| Seed *seed.Seeder | ||
| dbDSN string | ||
| DB db.Database | ||
| } | ||
|
|
||
| // Config contains configuration options for the test harness | ||
| type Config struct { | ||
| // NumNodes is the number of API nodes to create in the cluster | ||
| NumNodes int | ||
| } | ||
|
|
||
| // New creates a new cluster test harness | ||
| func New(t *testing.T, config Config) *Harness { | ||
| t.Helper() | ||
|
|
||
| require.Greater(t, config.NumNodes, 0) | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
|
|
||
| containerMgr := containers.New(t) | ||
|
|
||
| dbDSN := containerMgr.RunMySQL() | ||
| db, err := db.New(db.Config{ | ||
| Logger: logging.NewNoop(), | ||
| PrimaryDSN: dbDSN, | ||
| ReadOnlyDSN: "", | ||
| }) | ||
| require.NoError(t, err) | ||
|
|
||
| h := &Harness{ | ||
| t: t, | ||
| ctx: ctx, | ||
| cancel: cancel, | ||
| ports: port.New(), | ||
| containerMgr: containerMgr, | ||
| nodes: []ClusterNode{}, | ||
| Seed: seed.New(t, db), | ||
| dbDSN: dbDSN, | ||
| DB: db, | ||
| } | ||
|
|
||
| t.Cleanup(func() { | ||
| h.t.Log("Shutting down test cluster...") | ||
| h.cancel() | ||
| }) | ||
|
|
||
| h.Seed.Seed(ctx) | ||
|
|
||
| // Prepare data for gossip-based cluster discovery | ||
| var joinAddrs []string | ||
|
|
||
| // Create and start each node | ||
| for i := 0; i < config.NumNodes; i++ { | ||
| node := h.createNode(i, joinAddrs) | ||
|
|
||
| // Add this node's gossip address to the joinAddrs for subsequent nodes | ||
| joinAddrs = append(joinAddrs, fmt.Sprintf("localhost:%d", node.GossipPort)) | ||
| h.nodes = append(h.nodes, node) | ||
| } | ||
| return h | ||
| } | ||
|
|
||
| func (h *Harness) Resources() seed.Resources { | ||
| return h.Seed.Resources | ||
| } | ||
|
|
||
| // createNode creates and starts a single API node | ||
| func (h *Harness) createNode(index int, joinAddrs []string) ClusterNode { | ||
| h.t.Helper() | ||
|
|
||
| instanceID := fmt.Sprintf("i_%d", index) | ||
| httpPort := h.ports.Get() | ||
| rpcPort := h.ports.Get() | ||
| gossipPort := h.ports.Get() | ||
|
|
||
| nodeConfig := api.Config{ | ||
| Platform: "test", | ||
| Image: "test", | ||
| HttpPort: httpPort, | ||
| Region: "test-region", | ||
| Clock: nil, // Will use real clock | ||
| ClusterEnabled: true, | ||
| ClusterInstanceID: instanceID, | ||
| ClusterAdvertiseAddrStatic: "localhost", | ||
| ClusterRpcPort: rpcPort, | ||
| ClusterGossipPort: gossipPort, | ||
| ClusterDiscoveryStaticAddrs: joinAddrs, | ||
| ClusterDiscoveryRedisURL: "", | ||
| ClusterAdvertiseAddrAwsEcsMetadata: false, | ||
| DatabasePrimary: h.dbDSN, | ||
| DatabaseReadonlyReplica: "", | ||
| LogsColor: false, | ||
| ClickhouseURL: "", | ||
| OtelEnabled: os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "", | ||
| } | ||
|
|
||
| // Start the node in a separate goroutine | ||
| go func() { | ||
| if err := api.Run(h.ctx, nodeConfig); err != nil { | ||
| // If this is a planned shutdown (context canceled), don't fail the test | ||
| if h.ctx.Err() == nil { | ||
| h.t.Errorf("Node %s failed to run: %v", instanceID, err) | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| // Ensure the node is up and running | ||
| require.Eventually(h.t, func() bool { | ||
| res, err := http.Get(fmt.Sprintf("http://localhost:%d/v2/liveness", httpPort)) | ||
| if err != nil { | ||
| return false | ||
| } | ||
| defer res.Body.Close() | ||
| return res.StatusCode == http.StatusOK | ||
| }, 15*time.Second, 100*time.Millisecond, "API node %s failed to start", instanceID) | ||
|
|
||
| h.t.Logf("Node %s started and healthy", instanceID) | ||
|
|
||
| return ClusterNode{ | ||
| InstanceID: instanceID, | ||
| HttpPort: httpPort, | ||
| RPCPort: rpcPort, | ||
| GossipPort: gossipPort, | ||
| } | ||
| } | ||
|
|
||
| // GetNodes returns all nodes in the cluster | ||
| func (h *Harness) GetNodes() []ClusterNode { | ||
| return h.nodes | ||
| } | ||
|
|
||
| // GetNode returns a specific node by index | ||
| func (h *Harness) GetNode(index int) ClusterNode { | ||
| if index < 0 || index >= len(h.nodes) { | ||
| h.t.Fatalf("Invalid node index: %d", index) | ||
| } | ||
| return h.nodes[index] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| package integration | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "math/rand/v2" | ||
| "net/http" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| type TestResponse[TBody any] struct { | ||
| Status int | ||
| Headers http.Header | ||
| Body TBody | ||
| RawBody string | ||
| } | ||
|
|
||
| func CallNode[Req any, Res any](h *Harness, node ClusterNode, method string, path string, headers http.Header, req Req) TestResponse[Res] { | ||
| h.t.Helper() | ||
|
|
||
| url := fmt.Sprintf("http://localhost:%d%s", node.HttpPort, path) | ||
|
|
||
| body := new(bytes.Buffer) | ||
| err := json.NewEncoder(body).Encode(req) | ||
| require.NoError(h.t, err) | ||
|
|
||
| httpReq, err := http.NewRequest(method, url, body) | ||
| require.NoError(h.t, err) | ||
|
|
||
| httpReq.Header = headers | ||
| if httpReq.Header == nil { | ||
| httpReq.Header = http.Header{} | ||
| } | ||
|
|
||
| httpRes, err := http.DefaultClient.Do(httpReq) | ||
| require.NoError(h.t, err) | ||
| defer httpRes.Body.Close() | ||
|
|
||
| resBody, err := io.ReadAll(httpRes.Body) | ||
| require.NoError(h.t, err) | ||
|
|
||
| var res Res | ||
| err = json.Unmarshal(resBody, &res) | ||
| require.NoError(h.t, err, fmt.Sprintf("failed to decode response body: %s", string(resBody))) | ||
|
|
||
| return TestResponse[Res]{ | ||
| Status: httpRes.StatusCode, | ||
| Headers: httpRes.Header, | ||
| Body: res, | ||
| RawBody: string(resBody), | ||
| } | ||
| } | ||
|
|
||
| func CallRandomNode[Req any, Res any](h *Harness, method string, path string, headers http.Header, req Req) TestResponse[Res] { | ||
| h.t.Helper() | ||
| // nolint:gosec | ||
| node := h.nodes[rand.IntN(len(h.nodes))] | ||
| return CallNode[Req, Res](h, node, method, path, headers, req) | ||
|
|
||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Handle non-200 status code responses.
Currently, the function decodes JSON and checks for errors only in I/O operations. If an endpoint returns an error status (e.g., HTTP 500), the JSON unmarshal still executes. Consider explicitly checking and handling unexpected status codes to provide clearer failure messages in your tests.
if httpRes.StatusCode < 200 || httpRes.StatusCode >= 300 { - // currently unhandled + require.FailNowf(h.t, "unexpected status code %d", httpRes.StatusCode) }