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.rbindex 0d2d8b5ba8c..0a6ddb6e5cc 100644--- a/lib/markdown_endpoint/topic_renderer.rb+++ b/lib/markdown_endpoint/topic_renderer.rb@@ -4,6 +4,12 @@ require "digest"module MarkdownEndpointclass 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 MarkdownEndpointif (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 MarkdownEndpointescape_text(Nokogiri::HTML5.fragment(description).text.strip)end- def cached_body(cooked, post_url:)+ def cached_body(cooked, post)+ post_url = post.full_urlcontext = [CookedProcessor::VERSION,Discourse.base_url,@@ -135,11 +142,15 @@ module MarkdownEndpointdigest = 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)) doCookedProcessor.to_markdown(cooked, post_url:)endend+ def cache_ttl(post)+ post.created_at >= RECENT_POST_WINDOW.ago ? RECENT_CACHE_TTL : CACHE_TTL+ end+def escape_text(text)text.to_sdiff --git a/spec/requests/markdown_endpoints_spec.rb b/spec/requests/markdown_endpoints_spec.rbindex 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" doexpect(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" dovisible_tag = Fabricate(:tag, name: "visible-markdown-tag")restricted_tag = Fabricate(:tag, name: "restricted-markdown-tag")