fix(companion): isolate caption cache keys

This commit is contained in:
XZH 2026-08-28 18:06:40 -07:00
parent 93ab8c4a0a
commit 06828d2e82
3 changed files with 12 additions and 1 deletions

View File

@ -81,6 +81,13 @@ Spectator.describe Invidious::SubtitleCache do
expect(cache.get("video:123|label:Chinese|lang:zh|tlang:").try &.body).to eq(vtt_zh) expect(cache.get("video:123|label:Chinese|lang:zh|tlang:").try &.body).to eq(vtt_zh)
end end
it "builds cache keys that isolate delimiter-containing values" do
key_a = Invidious::SubtitleCache.caption_cache_key("video", "English|lang:x", "en", "")
key_b = Invidious::SubtitleCache.caption_cache_key("video", "English", "lang:x", "")
expect(key_a).not_to eq(key_b)
end
it "returns miss on first fetch and hit on subsequent fetch" do it "returns miss on first fetch and hit on subsequent fetch" do
cache = Invidious::SubtitleCache.new cache = Invidious::SubtitleCache.new
fetch_count = 0 fetch_count = 0

View File

@ -72,6 +72,10 @@ module Invidious
header_end == trimmed.size || " \t\r\n".includes?(trimmed[header_end]) header_end == trimmed.size || " \t\r\n".includes?(trimmed[header_end])
end end
def self.caption_cache_key(video_id : String, label : String, lang : String, tlang : String) : String
[video_id, label, lang, tlang].map { |value| Base64.urlsafe_encode(value) }.join('|')
end
def self.read_limited_body(input : IO, limit : Int32 = MAX_ENTRY_BYTES) : LimitedBody def self.read_limited_body(input : IO, limit : Int32 = MAX_ENTRY_BYTES) : LimitedBody
output = IO::Memory.new output = IO::Memory.new
buffer = Bytes.new(READ_CHUNK_BYTES) buffer = Bytes.new(READ_CHUNK_BYTES)

View File

@ -80,7 +80,7 @@ module Invidious::Routes::Companion
return return
end end
cache_key = "video:#{video_id}|label:#{label}|lang:#{lang}|tlang:#{tlang}" cache_key = Invidious::SubtitleCache.caption_cache_key(video_id, label, lang, tlang)
result = SUBTITLE_CACHE.get_or_fetch(cache_key) do result = SUBTITLE_CACHE.get_or_fetch(cache_key) do
fetch_from_companion(url, env.request.headers) fetch_from_companion(url, env.request.headers)