Skip to content
Merged
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
27 changes: 27 additions & 0 deletions .duel.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# frozen_string_literal: true

# Duel's configuration: https://github.com/sferik/duel-ruby/blob/main/docs/configuration.md
#
# Duel follows conventions, so set only what differs: benchmarks are in
# duel/**/*_duel.rb, each version's lib/ is first on the load path, a
# change is compared when it touches lib/ or ext/ (or the benchmarks, or
# this file), and releases are tagged v*.
Duel.configure do |c|
# The library each version's workers require (from the gemspec, unless
# this says otherwise).
# c.library = 'grape'

# When the workflow comments on a pull request with the report: :always,
# :results (passed or failed), :failures (failed, or couldn't compare),
# or :never.
# c.comment = :failures

# Each benchmark warms up for 2 seconds before it's measured, rather
# than until it's steady (for up to 10): Grape's requests take tens of
# microseconds, so YJIT has compiled them long before.
c.warm = 2

# A label that accepts a regression in a pull request, for a change
# that's slower on purpose (nil for none).
# c.accept_label = 'duel: accept'
end
31 changes: 31 additions & 0 deletions .github/workflows/perf-comment.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Perf comment

# Duel's report, as a new comment on the pull request, when Duel says
# to, by Duel's reusable workflow (see Duel's docs/ci.md), which this
# one calls once the Perf workflow has run, with a token that can write,
# so a pull request from a fork gets a comment too. It checks nothing
# out and runs none of the pull request's code, only `duel comment`.
#
# And when the label that accepts a regression (c.accept_label in
# .duel.rb) is added to a pull request, or taken off, it runs the Duel
# job again.
#
# (The workflow must be on the default branch before it runs at all.)
on:
workflow_run:
workflows: ["Perf"]
types: [completed]
pull_request_target:
types: [labeled, unlabeled]

permissions: {}

jobs:
comment:
# At the commit Duel's release was tagged at, as a tag can be moved.
uses: sferik/duel-ruby/.github/workflows/duel-comment.yml@14e3fd0c230d19872715e4e3ecd30955825f1233 # v0.3.0
permissions:
actions: write # to get the report from the Perf run, and run its Duel job again
pull-requests: write # to comment on the pull request with the report
with:
accept-label: "duel: accept"
47 changes: 47 additions & 0 deletions .github/workflows/perf.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Perf

# Duel's performance regression guards, run by Duel's reusable workflow
# (see Duel's docs/ci.md), which this one calls with what .duel.rb sets
# that it needs. On pull requests only, and only those that change what
# the benchmarks measure (or the benchmarks, or how they run): a squash
# merge's push would mostly repeat its pull request's run. Run by hand
# (on a fork, say), it compares the code with itself, which checks the
# setup.
on:
pull_request:
paths:
- lib/**
- duel/**
- .duel.rb
- grape.gemspec
- gemfiles/duel.gemfile
- .github/workflows/perf.yml
workflow_dispatch:

# A pull request's newer push cancels its run, if that's still going, as
# only its newest commit's result counts.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions: {}

jobs:
duel:
# At the commit Duel's release was tagged at, as a tag can be moved.
uses: sferik/duel-ruby/.github/workflows/duel.yml@14e3fd0c230d19872715e4e3ecd30955825f1233 # v0.3.0
# (It runs the branch's code, so it only reads. The jobs that write,
# for a push, are a workflow of Duel's own, which this one, for pull
# requests alone, doesn't call.)
permissions:
contents: read
pull-requests: read # for the pull request's labels (see c.accept_label)
with:
# The newest Ruby, which those who care most about speed run.
ruby-version: "4.0"
# With YJIT, as Rails turns it on, and some changes to Grape are
# faster or slower with it than without.
jit: yjit
# Duel's own bundle, so Duel and StackProf stay out of the one every
# other Gemfile evaluates.
gemfile: gemfiles/duel.gemfile
10 changes: 10 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@ AllCops:
NewCops: enable
TargetRubyVersion: 3.3
SuggestExtensions: false
Include:
- .duel.rb
Exclude:
- vendor/**/*
- bin/**/*
- benchmark/**/*
- tmp/**/*

inherit_mode:
merge:
- Include

plugins:
- rubocop-exception_messages
- rubocop-performance
Expand All @@ -32,6 +38,10 @@ Style/MultilineIfModifier:
Style/MutableConstant:
Recursive: true

Style/OneClassPerFile:
Exclude:
- duel/**/*.rb

Style/RaiseArgs:
Enabled: false

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* [#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).
* [#3062](https://github.com/ruby-grape/grape/pull/3062): Use the reusable Danger workflow with a separate Gemfile - [@dblock](https://github.com/dblock).
* [#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).
* [#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).
* [#3085](https://github.com/ruby-grape/grape/pull/3085): Report `endpoint_call.grape` around an endpoint's whole stack, with the response the client gets - [@ericproulx](https://github.com/ericproulx).
* [#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).
* [#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).
Expand Down
11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,17 @@ raise ArgumentError, 'A block is required.'

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.

#### Benchmark

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:

```
BUNDLE_GEMFILE=gemfiles/duel.gemfile bundle install
BUNDLE_GEMFILE=gemfiles/duel.gemfile bundle exec duel
```

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.

#### Write Documentation

Document any external behavior in the [README](README.md).
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
[![Gem Version](https://badge.fury.io/rb/grape.svg)](http://badge.fury.io/rb/grape)
[![test](https://github.com/ruby-grape/grape/actions/workflows/test.yml/badge.svg)](https://github.com/ruby-grape/grape/actions/workflows/test.yml)
[![Coverage Status](https://coveralls.io/repos/github/ruby-grape/grape/badge.svg?branch=master)](https://coveralls.io/github/ruby-grape/grape?branch=master)
[![Duel](https://raw.githubusercontent.com/sferik/duel-ruby/main/assets/badge.svg)](https://github.com/ruby-grape/grape/actions/workflows/perf.yml)

## What is Grape?

Expand Down
8 changes: 8 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,11 @@ require('rubocop/rake_task')
RuboCop::RakeTask.new

task(default: %i[rubocop spec])

# Duel's tasks, in its own bundle (gemfiles/duel.gemfile).
begin
require('duel/rake_task')
Duel::RakeTask.new
rescue LoadError
# (Any other bundle, which hasn't got Duel.)
end
67 changes: 67 additions & 0 deletions duel/callbacks_duel.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# frozen_string_literal: true

require_relative 'duel_helper'

# Callbacks and helpers: an endpoint runs the before, validation, after
# and finally callbacks of every namespace it's in, and its block calls
# helpers, reads headers, and sets the status, headers and cookies.

module AuthHelpers
def current_user
@current_user ||= { id: 1, name: 'Ada', token: headers['Authorization'].to_s.delete_prefix('Bearer ') }
end

def authenticate!
error!('Unauthorized', 401) unless current_user[:token] == 's3cret'
end
end

class CallbacksAPI < Grape::API
format :json
helpers AuthHelpers

helpers do
def request_id
headers['X-Request-Id'] || 'none'
end

params :pagination do
optional :page, type: Integer, default: 1
optional :per_page, type: Integer, default: 25
end
end

before { header 'X-Request-Id', request_id }
before { authenticate! }
after { header 'X-Runtime', '0.001' }
finally { @finished = true }

namespace :admin do
before { header 'X-Admin', 'true' }
before_validation { @validating = true }
after_validation { @validated = true }
after { header 'Cache-Control', 'no-store' }

params do
use :pagination
end
get :reports do
status 200
header 'X-Total-Count', '3'
cookies[:last_seen] = { value: 'reports', path: '/admin', httponly: true }
{ user: current_user[:name], page: params[:page], request_id: }
end
end
end

AUTHORIZED = { 'Authorization' => 'Bearer s3cret', 'X-Request-Id' => '0f8fad5b-d9cb-469f-a165-70867728950e' }.freeze

duel 'callbacks: before, validation, after and finally callbacks, with helpers' do |n|
once { prepare(CallbacksAPI, rack_env('/admin/reports?page=2', headers: AUTHORIZED), 200, 'Ada') }
serve(@app, @env, n)
end

duel 'callbacks: a before callback that halts with error!' do |n|
once { prepare(CallbacksAPI, rack_env('/admin/reports', headers: { 'Authorization' => 'Bearer wrong' }), 401, 'Unauthorized') }
serve(@app, @env, n)
end
75 changes: 75 additions & 0 deletions duel/compile_duel.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# frozen_string_literal: true

require_relative 'duel_helper'

# Compiling an API, which its first request does (or a boot that compiles
# it ahead): building each endpoint's middleware stack and the router's
# unions, buckets and table of static paths. change! discards the
# compiled instance, so that the next compile! builds it again.

# 4 resources, each with the five REST routes, and params.
class CompiledAPI < Grape::API
format :json
prefix :api
version 'v1', using: :path

4.times do |i|
resource "resource#{i}" do
params do
optional :page, type: Integer, default: 1
end
get { [] }
params do
requires :name, type: String
end
post { {} }
route_param :id, type: Integer do
get { {} }
put { {} }
delete { {} }
end
end
end
end

class PostsAPI < Grape::API
helpers { def page = params[:page] }
before { header 'X-Posts', 'true' }

get { [] }
route_param :id do
get { { id: params[:id] } }
namespace(:comments) { get { [] } }
end
end

class CommentsAPI < Grape::API
get { [] }
get(':id') { { id: params[:id] } }
end

class MountedAPI < Grape::API
format :json
rescue_from :all

mount PostsAPI => '/posts'
mount CommentsAPI => '/comments'
namespace :admin do
mount PostsAPI
end
end

duel 'compile: an API of 20 routes' do
CompiledAPI.change!
CompiledAPI.compile!
end

duel 'compile: an API that mounts others' do
MountedAPI.change!
MountedAPI.compile!
end

duel 'mount: GET a route of a mounted API' do |n|
once { prepare(MountedAPI, rack_env('/admin/42/comments'), 200) }
serve(@app, @env, n)
end
60 changes: 60 additions & 0 deletions duel/declared_duel.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# frozen_string_literal: true

require_relative 'duel_helper'

# declared(params), which endpoints call to take only the params they
# declared, walks the declarations against what the request sent.

class DeclaredAPI < Grape::API
format :json

params do
requires :name, type: String
optional :email, type: String
optional :bio, type: String
optional :role, type: String, values: %w[admin member guest], default: 'member'
optional :settings, type: Hash do
optional :theme, type: String
optional :locale, type: String
optional :notifications, type: Hash do
optional :email, type: Grape::API::Boolean
optional :push, type: Grape::API::Boolean
end
end
optional :links, type: Array do
requires :rel, type: String
requires :href, type: String
optional :title, type: String, as: :label
end
end
route_param :account_id, type: Integer do
post('profiles') { declared(params) }
put('profiles') { declared(params, include_missing: false) }
patch('profiles') { declared(params, stringify: true) }
end
end

def profile_json
{
name: 'Katherine Johnson',
email: 'katherine@example.com',
unknown: 'dropped',
settings: { theme: 'dark', notifications: { email: true } },
links: Array.new(10) { |i| { rel: "rel#{i}", href: "https://example.com/#{i}", title: "Link #{i}", extra: i } }
}
end

duel 'declared: all declared params, with missing ones as nil' do |n|
once { prepare(DeclaredAPI, rack_env('/7/profiles', method: Rack::POST, json: profile_json), 201, '"bio":null') }
serve(@app, @env, n)
end

duel 'declared: only the params sent' do |n|
once { prepare(DeclaredAPI, rack_env('/7/profiles', method: Rack::PUT, json: profile_json), 200, 'Katherine') }
serve(@app, @env, n)
end

duel 'declared: with string keys' do |n|
once { prepare(DeclaredAPI, rack_env('/7/profiles', method: Rack::PATCH, json: profile_json), 200, '"label":"Link 9"') }
serve(@app, @env, n)
end
Loading
Loading