Skip to content

Commit 75b71a5

Browse files
committed
Add Duel performance regression guards
Duel (https://github.com/sferik/duel-ruby) runs the benchmarks in duel/ on the branch a pull request targets and on the pull request, side by side, and fails the Perf workflow when the pull request is slower or allocates more. It's the memory check on every pull request that #2442 asks for, and it measures CPU time too. The 39 benchmarks send requests through an API's Rack interface in memory, with YJIT on, in a bundle of their own (gemfiles/duel.gemfile, which pins Duel to an exact version). The Perf workflow runs on pull requests that touch the code or the benchmarks, calls Duel's reusable workflow at the commit Duel 0.3.0's tag names, and only reads. A second workflow comments on the pull request with the report, running none of its code. Closes #2442
1 parent 0057bf2 commit 75b71a5

18 files changed

Lines changed: 851 additions & 0 deletions

‎.duel.rb‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# frozen_string_literal: true
2+
3+
# Duel's configuration: https://github.com/sferik/duel-ruby/blob/main/docs/configuration.md
4+
#
5+
# Duel follows conventions, so set only what differs: benchmarks are in
6+
# duel/**/*_duel.rb, each version's lib/ is first on the load path, a
7+
# change is compared when it touches lib/ or ext/ (or the benchmarks, or
8+
# this file), and releases are tagged v*.
9+
Duel.configure do |c|
10+
# The library each version's workers require (from the gemspec, unless
11+
# this says otherwise).
12+
# c.library = 'grape'
13+
14+
# When the workflow comments on a pull request with the report: :always,
15+
# :results (passed or failed), :failures (failed, or couldn't compare),
16+
# or :never.
17+
# c.comment = :failures
18+
19+
# Each benchmark warms up for 2 seconds before it's measured, rather
20+
# than until it's steady (for up to 10): Grape's requests take tens of
21+
# microseconds, so YJIT has compiled them long before.
22+
c.warm = 2
23+
24+
# A label that accepts a regression in a pull request, for a change
25+
# that's slower on purpose (nil for none).
26+
# c.accept_label = 'duel: accept'
27+
end

‎.github/workflows/perf-comment.yml‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
name: Perf comment
2+
3+
# Duel's report, as a new comment on the pull request, when Duel says
4+
# to, by Duel's reusable workflow (see Duel's docs/ci.md), which this
5+
# one calls once the Perf workflow has run, with a token that can write,
6+
# so a pull request from a fork gets a comment too. It checks nothing
7+
# out and runs none of the pull request's code, only `duel comment`.
8+
#
9+
# And when the label that accepts a regression (c.accept_label in
10+
# .duel.rb) is added to a pull request, or taken off, it runs the Duel
11+
# job again.
12+
#
13+
# (The workflow must be on the default branch before it runs at all.)
14+
on:
15+
workflow_run:
16+
workflows: ["Perf"]
17+
types: [completed]
18+
pull_request_target:
19+
types: [labeled, unlabeled]
20+
21+
permissions: {}
22+
23+
jobs:
24+
comment:
25+
# At the commit Duel's release was tagged at, as a tag can be moved.
26+
uses: sferik/duel-ruby/.github/workflows/duel-comment.yml@14e3fd0c230d19872715e4e3ecd30955825f1233 # v0.3.0
27+
permissions:
28+
actions: write # to get the report from the Perf run, and run its Duel job again
29+
pull-requests: write # to comment on the pull request with the report
30+
with:
31+
accept-label: "duel: accept"

‎.github/workflows/perf.yml‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
name: Perf
2+
3+
# Duel's performance regression guards, run by Duel's reusable workflow
4+
# (see Duel's docs/ci.md), which this one calls with what .duel.rb sets
5+
# that it needs. On pull requests only, and only those that change what
6+
# the benchmarks measure (or the benchmarks, or how they run): a squash
7+
# merge's push would mostly repeat its pull request's run. Run by hand
8+
# (on a fork, say), it compares the code with itself, which checks the
9+
# setup.
10+
on:
11+
pull_request:
12+
paths:
13+
- lib/**
14+
- duel/**
15+
- .duel.rb
16+
- grape.gemspec
17+
- gemfiles/duel.gemfile
18+
- .github/workflows/perf.yml
19+
workflow_dispatch:
20+
21+
# A pull request's newer push cancels its run, if that's still going, as
22+
# only its newest commit's result counts.
23+
concurrency:
24+
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }}
25+
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
26+
27+
permissions: {}
28+
29+
jobs:
30+
duel:
31+
# At the commit Duel's release was tagged at, as a tag can be moved.
32+
uses: sferik/duel-ruby/.github/workflows/duel.yml@14e3fd0c230d19872715e4e3ecd30955825f1233 # v0.3.0
33+
# (It runs the branch's code, so it only reads. The jobs that write,
34+
# for a push, are a workflow of Duel's own, which this one, for pull
35+
# requests alone, doesn't call.)
36+
permissions:
37+
contents: read
38+
pull-requests: read # for the pull request's labels (see c.accept_label)
39+
with:
40+
# The newest Ruby, which those who care most about speed run.
41+
ruby-version: "4.0"
42+
# With YJIT, as Rails turns it on, and some changes to Grape are
43+
# faster or slower with it than without.
44+
jit: yjit
45+
# Duel's own bundle, so Duel and StackProf stay out of the one every
46+
# other Gemfile evaluates.
47+
gemfile: gemfiles/duel.gemfile

‎.rubocop.yml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,18 @@ AllCops:
22
NewCops: enable
33
TargetRubyVersion: 3.3
44
SuggestExtensions: false
5+
Include:
6+
- .duel.rb
57
Exclude:
68
- vendor/**/*
79
- bin/**/*
810
- benchmark/**/*
911
- tmp/**/*
1012

13+
inherit_mode:
14+
merge:
15+
- Include
16+
1117
plugins:
1218
- rubocop-exception_messages
1319
- rubocop-performance
@@ -32,6 +38,10 @@ Style/MultilineIfModifier:
3238
Style/MutableConstant:
3339
Recursive: true
3440

41+
Style/OneClassPerFile:
42+
Exclude:
43+
- duel/**/*.rb
44+
3545
Style/RaiseArgs:
3646
Enabled: false
3747

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
* [#3056](https://github.com/ruby-grape/grape/pull/3056): Drop support for Rails 7.2 and require ActiveSupport 8.0 - [@ericproulx](https://github.com/ericproulx).
1010
* [#3062](https://github.com/ruby-grape/grape/pull/3062): Use the reusable Danger workflow with a separate Gemfile - [@dblock](https://github.com/dblock).
1111
* [#3063](https://github.com/ruby-grape/grape/pull/3063): Drop support for Rack 2.2 and 3.0 and require Rack 3.1 - [@ericproulx](https://github.com/ericproulx).
12+
* [#3077](https://github.com/ruby-grape/grape/pull/3077): Add benchmarks that fail a pull request that makes Grape slower or allocate more, with [Duel](https://github.com/sferik/duel-ruby) - [@sferik](https://github.com/sferik).
1213
* [#3088](https://github.com/ruby-grape/grape/pull/3088): Pin workflow actions to commits and grant their tokens only what they need - [@ericproulx](https://github.com/ericproulx).
1314
* [#3090](https://github.com/ruby-grape/grape/pull/3090): Call Danger's workflows from danger/danger-pr-comment, where they moved - [@ericproulx](https://github.com/ericproulx).
1415
* Your contribution here.

‎CONTRIBUTING.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,17 @@ raise ArgumentError, 'A block is required.'
9090

9191
This does not apply to `Grape::Exceptions::*` messages meant to be rendered in an API response body, which are already lowercase and unpunctuated by convention and typically come from locale YAML rather than inline strings.
9292

93+
#### Benchmark
94+
95+
Grape has two kinds of benchmarks. Those in [duel](duel) guard each pull request that changes `lib`: the Perf workflow runs them with [Duel](https://github.com/sferik/duel-ruby) on the pull request and on the branch it targets, side by side, and fails a pull request that makes them slower or allocate more. A scenario on a hot path, which a change to Grape could slow down, goes there, as a `duel/*_duel.rb` file. To run them, on Ruby 3.4 or later:
96+
97+
```
98+
BUNDLE_GEMFILE=gemfiles/duel.gemfile bundle install
99+
BUNDLE_GEMFILE=gemfiles/duel.gemfile bundle exec duel
100+
```
101+
102+
Those in [benchmark](benchmark) are run by hand, for what a pull request's check doesn't ask: [version_throughput](benchmark/version_throughput) compares Grape's releases with each other, and [grape_on_rack](benchmark/grape_on_rack) profiles memory under a live server.
103+
93104
#### Write Documentation
94105

95106
Document any external behavior in the [README](README.md).

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
[![Gem Version](https://badge.fury.io/rb/grape.svg)](http://badge.fury.io/rb/grape)
44
[![test](https://github.com/ruby-grape/grape/actions/workflows/test.yml/badge.svg)](https://github.com/ruby-grape/grape/actions/workflows/test.yml)
55
[![Coverage Status](https://coveralls.io/repos/github/ruby-grape/grape/badge.svg?branch=master)](https://coveralls.io/github/ruby-grape/grape?branch=master)
6+
[![Duel](https://raw.githubusercontent.com/sferik/duel-ruby/main/assets/badge.svg)](https://github.com/ruby-grape/grape/actions/workflows/perf.yml)
67

78
## What is Grape?
89

‎Rakefile‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,11 @@ require('rubocop/rake_task')
2525
RuboCop::RakeTask.new
2626

2727
task(default: %i[rubocop spec])
28+
29+
# Duel's tasks, in its own bundle (gemfiles/duel.gemfile).
30+
begin
31+
require('duel/rake_task')
32+
Duel::RakeTask.new
33+
rescue LoadError
34+
# (Any other bundle, which hasn't got Duel.)
35+
end

‎duel/callbacks_duel.rb‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# frozen_string_literal: true
2+
3+
require_relative 'duel_helper'
4+
5+
# Callbacks and helpers: an endpoint runs the before, validation, after
6+
# and finally callbacks of every namespace it's in, and its block calls
7+
# helpers, reads headers, and sets the status, headers and cookies.
8+
9+
module AuthHelpers
10+
def current_user
11+
@current_user ||= { id: 1, name: 'Ada', token: headers['Authorization'].to_s.delete_prefix('Bearer ') }
12+
end
13+
14+
def authenticate!
15+
error!('Unauthorized', 401) unless current_user[:token] == 's3cret'
16+
end
17+
end
18+
19+
class CallbacksAPI < Grape::API
20+
format :json
21+
helpers AuthHelpers
22+
23+
helpers do
24+
def request_id
25+
headers['X-Request-Id'] || 'none'
26+
end
27+
28+
params :pagination do
29+
optional :page, type: Integer, default: 1
30+
optional :per_page, type: Integer, default: 25
31+
end
32+
end
33+
34+
before { header 'X-Request-Id', request_id }
35+
before { authenticate! }
36+
after { header 'X-Runtime', '0.001' }
37+
finally { @finished = true }
38+
39+
namespace :admin do
40+
before { header 'X-Admin', 'true' }
41+
before_validation { @validating = true }
42+
after_validation { @validated = true }
43+
after { header 'Cache-Control', 'no-store' }
44+
45+
params do
46+
use :pagination
47+
end
48+
get :reports do
49+
status 200
50+
header 'X-Total-Count', '3'
51+
cookies[:last_seen] = { value: 'reports', path: '/admin', httponly: true }
52+
{ user: current_user[:name], page: params[:page], request_id: }
53+
end
54+
end
55+
end
56+
57+
AUTHORIZED = { 'Authorization' => 'Bearer s3cret', 'X-Request-Id' => '0f8fad5b-d9cb-469f-a165-70867728950e' }.freeze
58+
59+
duel 'callbacks: before, validation, after and finally callbacks, with helpers' do |n|
60+
once { prepare(CallbacksAPI, rack_env('/admin/reports?page=2', headers: AUTHORIZED), 200, 'Ada') }
61+
serve(@app, @env, n)
62+
end
63+
64+
duel 'callbacks: a before callback that halts with error!' do |n|
65+
once { prepare(CallbacksAPI, rack_env('/admin/reports', headers: { 'Authorization' => 'Bearer wrong' }), 401, 'Unauthorized') }
66+
serve(@app, @env, n)
67+
end

‎duel/compile_duel.rb‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# frozen_string_literal: true
2+
3+
require_relative 'duel_helper'
4+
5+
# Compiling an API, which its first request does (or a boot that compiles
6+
# it ahead): building each endpoint's middleware stack and the router's
7+
# unions, buckets and table of static paths. change! discards the
8+
# compiled instance, so that the next compile! builds it again.
9+
10+
# 4 resources, each with the five REST routes, and params.
11+
class CompiledAPI < Grape::API
12+
format :json
13+
prefix :api
14+
version 'v1', using: :path
15+
16+
4.times do |i|
17+
resource "resource#{i}" do
18+
params do
19+
optional :page, type: Integer, default: 1
20+
end
21+
get { [] }
22+
params do
23+
requires :name, type: String
24+
end
25+
post { {} }
26+
route_param :id, type: Integer do
27+
get { {} }
28+
put { {} }
29+
delete { {} }
30+
end
31+
end
32+
end
33+
end
34+
35+
class PostsAPI < Grape::API
36+
helpers { def page = params[:page] }
37+
before { header 'X-Posts', 'true' }
38+
39+
get { [] }
40+
route_param :id do
41+
get { { id: params[:id] } }
42+
namespace(:comments) { get { [] } }
43+
end
44+
end
45+
46+
class CommentsAPI < Grape::API
47+
get { [] }
48+
get(':id') { { id: params[:id] } }
49+
end
50+
51+
class MountedAPI < Grape::API
52+
format :json
53+
rescue_from :all
54+
55+
mount PostsAPI => '/posts'
56+
mount CommentsAPI => '/comments'
57+
namespace :admin do
58+
mount PostsAPI
59+
end
60+
end
61+
62+
duel 'compile: an API of 20 routes' do
63+
CompiledAPI.change!
64+
CompiledAPI.compile!
65+
end
66+
67+
duel 'compile: an API that mounts others' do
68+
MountedAPI.change!
69+
MountedAPI.compile!
70+
end
71+
72+
duel 'mount: GET a route of a mounted API' do |n|
73+
once { prepare(MountedAPI, rack_env('/admin/42/comments'), 200) }
74+
serve(@app, @env, n)
75+
end

0 commit comments

Comments
 (0)