Skip to content

A platform for community discussion. Free, open, simple.

PERF: Reduce Markdown endpoint cache retention (#45423)

Penar Musarajab757c428914
diff --git a/lib/markdown_endpoint/topic_renderer.rb b/lib/markdown_endpoint/topic_renderer.rb
index 0d2d8b5ba8c..0a6ddb6e5cc 100644
--- a/lib/markdown_endpoint/topic_renderer.rb
+++ b/lib/markdown_endpoint/topic_renderer.rb
@@ -4,6 +4,12 @@ require "digest"
module MarkdownEndpoint
class TopicRenderer
+ # Edits create new cache keys, so bound how long obsolete entries linger.
+ # Recent posts are more likely to be fetched again, so cache them for longer.
+ CACHE_TTL = 1.hour
+ RECENT_CACHE_TTL = 1.day
+ RECENT_POST_WINDOW = 1.month
+
def initialize(topic_view, guardian:, post_number: nil, query: {})
@topic_view = topic_view
@topic = topic_view.topic
@@ -98,7 +104,7 @@ module MarkdownEndpoint
if (description = action_description(post)).present?
lines.concat([description, ""])
end
- lines << cached_body(cooked, post_url: post.full_url)
+ lines << cached_body(cooked, post)
lines.join("\n")
end
@@ -123,7 +129,8 @@ module MarkdownEndpoint
escape_text(Nokogiri::HTML5.fragment(description).text.strip)
end
- def cached_body(cooked, post_url:)
+ def cached_body(cooked, post)
+ post_url = post.full_url
context = [
CookedProcessor::VERSION,
Discourse.base_url,
@@ -135,11 +142,15 @@ module MarkdownEndpoint
digest = Digest::SHA256.hexdigest(context)
Discourse
.cache
- .fetch("markdown-endpoint:cooked:#{digest}", expires_in: 1.week) do
+ .fetch("markdown-endpoint:cooked:#{digest}", expires_in: cache_ttl(post)) do
CookedProcessor.to_markdown(cooked, post_url:)
end
end
+ def cache_ttl(post)
+ post.created_at >= RECENT_POST_WINDOW.ago ? RECENT_CACHE_TTL : CACHE_TTL
+ end
+
def escape_text(text)
text
.to_s
diff --git a/spec/requests/markdown_endpoints_spec.rb b/spec/requests/markdown_endpoints_spec.rb
index 838dc3df034..119737556ce 100644
--- a/spec/requests/markdown_endpoints_spec.rb
+++ b/spec/requests/markdown_endpoints_spec.rb
@@ -1011,6 +1011,20 @@ RSpec.describe "Markdown endpoints" do
expect(response.body).not_to eq(anonymous_body)
end
+ it "caches recent post bodies for a day and older bodies for an hour" do
+ old_post = Fabricate(:post, topic: topic, user: user, raw: "Older body")
+ old_post.update_columns(created_at: 2.months.ago, updated_at: 2.months.ago)
+
+ get "/t/#{topic.slug}/#{topic.id}.md"
+ expect(response.body).to include(post.raw, old_post.raw)
+
+ ttls = Discourse.cache.keys("markdown-endpoint:cooked:*").map { |key| Discourse.redis.ttl(key) }
+ expect(ttls.size).to eq(2)
+ expect(ttls.min).to be <= 1.hour.to_i
+ expect(ttls.max).to be > 1.hour.to_i
+ expect(ttls.max).to be <= 1.day.to_i
+ end
+
it "uses visible tags and excludes deleted posts from anonymous output" do
visible_tag = Fabricate(:tag, name: "visible-markdown-tag")
restricted_tag = Fabricate(:tag, name: "restricted-markdown-tag")