Skip to content

Commit e38f92f

Browse files
Gargronhiyuki2578
authored andcommitted
Add (back) rails-level JSON caching (mastodon#11333)
1 parent b4f382a commit e38f92f

10 files changed

Lines changed: 64 additions & 50 deletions

app/controllers/accounts_controller.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def show
4141

4242
format.json do
4343
expires_in 3.minutes, public: !(authorized_fetch_mode? && signed_request_account.present?)
44-
render json: @account, content_type: 'application/activity+json', serializer: ActivityPub::ActorSerializer, adapter: ActivityPub::Adapter, fields: restrict_fields_to
44+
render_with_cache json: @account, content_type: 'application/activity+json', serializer: ActivityPub::ActorSerializer, adapter: ActivityPub::Adapter, fields: restrict_fields_to
4545
end
4646
end
4747
end

app/controllers/activitypub/collections_controller.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class ActivityPub::CollectionsController < ActivityPub::BaseController
1111

1212
def show
1313
expires_in 3.minutes, public: public_fetch_mode?
14-
render json: collection_presenter, content_type: 'application/activity+json', serializer: ActivityPub::CollectionSerializer, adapter: ActivityPub::Adapter, skip_activities: true
14+
render_with_cache json: collection_presenter, content_type: 'application/activity+json', serializer: ActivityPub::CollectionSerializer, adapter: ActivityPub::Adapter, skip_activities: true
1515
end
1616

1717
private

app/controllers/api/v1/custom_emojis_controller.rb

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ class Api::V1::CustomEmojisController < Api::BaseController
66
skip_before_action :set_cache_headers
77

88
def index
9-
render_cached_json('api:v1:custom_emojis', expires_in: 1.minute) do
10-
ActiveModelSerializers::SerializableResource.new(CustomEmoji.local.where(disabled: false).includes(:category), each_serializer: REST::CustomEmojiSerializer)
11-
end
9+
expires_in 3.minutes, public: true
10+
render_with_cache(each_serializer: REST::CustomEmojiSerializer) { CustomEmoji.local.where(disabled: false).includes(:category) }
1211
end
1312
end

app/controllers/api/v1/instances/activity_controller.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ class Api::V1::Instances::ActivityController < Api::BaseController
77
respond_to :json
88

99
def show
10-
render_cached_json('api:v1:instances:activity:show', expires_in: 1.day) { activity }
10+
expires_in 1.day, public: true
11+
render_with_cache json: :activity, expires_in: 1.day
1112
end
1213

1314
private

app/controllers/api/v1/instances/peers_controller.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ class Api::V1::Instances::PeersController < Api::BaseController
77
respond_to :json
88

99
def index
10-
render_cached_json('api:v1:instances:peers:index', expires_in: 1.day) { Account.remote.domains }
10+
expires_in 1.day, public: true
11+
render_with_cache(expires_in: 1.day) { Account.remote.domains }
1112
end
1213

1314
private

app/controllers/api/v1/instances_controller.rb

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@ class Api::V1::InstancesController < Api::BaseController
55
skip_before_action :set_cache_headers
66

77
def show
8-
render_cached_json('api:v1:instances', expires_in: 5.minutes) do
9-
ActiveModelSerializers::SerializableResource.new({}, serializer: REST::InstanceSerializer)
10-
end
8+
expires_in 3.minutes, public: true
9+
render_with_cache json: {}, serializer: REST::InstanceSerializer
1110
end
1211
end

app/controllers/application_controller.rb

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ class ApplicationController < ActionController::Base
1010
include Localized
1111
include UserTrackingConcern
1212
include SessionTrackingConcern
13+
include CacheConcern
1314

1415
helper_method :current_account
1516
helper_method :current_session
@@ -115,47 +116,10 @@ def current_theme
115116
current_user.setting_theme
116117
end
117118

118-
def cache_collection(raw, klass)
119-
return raw unless klass.respond_to?(:with_includes)
120-
121-
raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
122-
cached_keys_with_value = Rails.cache.read_multi(*raw).transform_keys(&:id)
123-
uncached_ids = raw.map(&:id) - cached_keys_with_value.keys
124-
125-
klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
126-
127-
unless uncached_ids.empty?
128-
uncached = klass.where(id: uncached_ids).with_includes.each_with_object({}) { |item, h| h[item.id] = item }
129-
130-
uncached.each_value do |item|
131-
Rails.cache.write(item, item)
132-
end
133-
end
134-
135-
raw.map { |item| cached_keys_with_value[item.id] || uncached[item.id] }.compact
136-
end
137-
138119
def respond_with_error(code)
139120
respond_to do |format|
140121
format.any { head code }
141122
format.html { render "errors/#{code}", layout: 'error', status: code }
142123
end
143124
end
144-
145-
def render_cached_json(cache_key, **options)
146-
options[:expires_in] ||= 3.minutes
147-
cache_public = options.key?(:public) ? options.delete(:public) : true
148-
content_type = options.delete(:content_type) || 'application/json'
149-
150-
data = Rails.cache.fetch(cache_key, { raw: true }.merge(options)) do
151-
yield.to_json
152-
end
153-
154-
expires_in options[:expires_in], public: cache_public
155-
render json: data, content_type: content_type
156-
end
157-
158-
def set_cache_headers
159-
response.headers['Vary'] = public_fetch_mode? ? 'Accept' : 'Accept, Signature'
160-
end
161125
end
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# frozen_string_literal: true
2+
3+
module CacheConcern
4+
extend ActiveSupport::Concern
5+
6+
def render_with_cache(**options)
7+
raise ArgumentError, 'only JSON render calls are supported' unless options.key?(:json) || block_given?
8+
9+
key = options.delete(:key) || [[params[:controller], params[:action]].join('/'), options[:json].respond_to?(:cache_key) ? options[:json].cache_key : nil, options[:fields].nil? ? nil : options[:fields].join(',')].compact.join(':')
10+
expires_in = options.delete(:expires_in) || 3.minutes
11+
body = Rails.cache.read(key, raw: true)
12+
13+
if body
14+
render(options.except(:json, :serializer, :each_serializer, :adapter, :fields).merge(json: body))
15+
else
16+
if block_given?
17+
options[:json] = yield
18+
elsif options[:json].is_a?(Symbol)
19+
options[:json] = send(options[:json])
20+
end
21+
22+
render(options)
23+
Rails.cache.write(key, response.body, expires_in: expires_in, raw: true)
24+
end
25+
end
26+
27+
def set_cache_headers
28+
response.headers['Vary'] = public_fetch_mode? ? 'Accept' : 'Accept, Signature'
29+
end
30+
31+
def cache_collection(raw, klass)
32+
return raw unless klass.respond_to?(:with_includes)
33+
34+
raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
35+
cached_keys_with_value = Rails.cache.read_multi(*raw).transform_keys(&:id)
36+
uncached_ids = raw.map(&:id) - cached_keys_with_value.keys
37+
38+
klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
39+
40+
unless uncached_ids.empty?
41+
uncached = klass.where(id: uncached_ids).with_includes.each_with_object({}) { |item, h| h[item.id] = item }
42+
43+
uncached.each_value do |item|
44+
Rails.cache.write(item, item)
45+
end
46+
end
47+
48+
raw.map { |item| cached_keys_with_value[item.id] || uncached[item.id] }.compact
49+
end
50+
end

app/controllers/emojis_controller.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def show
88
respond_to do |format|
99
format.json do
1010
expires_in 3.minutes, public: true
11-
render json: @emoji, content_type: 'application/activity+json', serializer: ActivityPub::EmojiSerializer, adapter: ActivityPub::Adapter
11+
render_with_cache json: @emoji, content_type: 'application/activity+json', serializer: ActivityPub::EmojiSerializer, adapter: ActivityPub::Adapter
1212
end
1313
end
1414
end

app/controllers/statuses_controller.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,14 @@ def show
3232

3333
format.json do
3434
expires_in 3.minutes, public: @status.distributable? && public_fetch_mode?
35-
render json: @status, content_type: 'application/activity+json', serializer: ActivityPub::NoteSerializer, adapter: ActivityPub::Adapter
35+
render_with_cache json: @status, content_type: 'application/activity+json', serializer: ActivityPub::NoteSerializer, adapter: ActivityPub::Adapter
3636
end
3737
end
3838
end
3939

4040
def activity
4141
expires_in 3.minutes, public: @status.distributable? && public_fetch_mode?
42-
render json: @status, content_type: 'application/activity+json', serializer: ActivityPub::ActivitySerializer, adapter: ActivityPub::Adapter
42+
render_with_cache json: @status, content_type: 'application/activity+json', serializer: ActivityPub::ActivitySerializer, adapter: ActivityPub::Adapter
4343
end
4444

4545
def embed

0 commit comments

Comments
 (0)