From ecf7a24480a81a26e4911976d1d38837cd880e29 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Wed, 11 Nov 2026 03:18:33 +0900 Subject: [PATCH] Match resource templates in linear time ## Motivation and Context `ResourceTemplate.match_uri` matched a URI with a pattern that gives each `{var}` the group `[^/]+`. Two or more variables in one path segment, as in `file:///{name}.{ext}`, leave a backtracking engine many ways to split a long run of the separator, and Ruby before 3.2, which the gem still supports, does not memoize the search. On Ruby 2.7, `file:///` followed by 40,000 dots and a `/` took 5 seconds to fail against that template, and 800 separators took 0.4 seconds against one with three variables, growing with the cube of the length. `match_uri` now finds the same match without a search. A literal that holds a `/` can sit in one place only, since no variable holds one, and inside a run of variables between two such places taking the last occurrence of each separator from the right gives the split the pattern gives. The cost is linear in the length of the URI on every Ruby. ## How Has This Been Tested? `test/mcp/resource_template_test.rb`, including a comparison with the previous pattern over generated templates and URIs. Checked by hand on Ruby 2.7.8: the two inputs above return at once, and 1,200,000 generated inputs give the result of the pattern. ## Breaking Changes None for a URI that is a valid String. `match_uri` returns `nil` for a String that is not valid in its encoding and for a value that is neither a String nor `nil`, where the pattern raised `ArgumentError` or `TypeError` or, for a Symbol, matched it. --- lib/mcp/resource_template.rb | 93 ++++++++++++++++++++++++++---- test/mcp/resource_template_test.rb | 70 ++++++++++++++++++++++ 2 files changed, 151 insertions(+), 12 deletions(-) diff --git a/lib/mcp/resource_template.rb b/lib/mcp/resource_template.rb index 9ede2247..8db5d0ab 100644 --- a/lib/mcp/resource_template.rb +++ b/lib/mcp/resource_template.rb @@ -5,10 +5,9 @@ class ResourceTemplate class << self NOT_SET = Object.new - # Applied after `Regexp.escape`, which turns `{` and `}` into `\{` and `\}`. - # Variable names are restricted to valid Regexp named-group names, - # so RFC 6570 operator expressions (e.g. `{?query}`) stay literal and never match. - VARIABLE_PATTERN = /\\\{([A-Za-z_]\w*)\\\}/.freeze + # Variable names are restricted to identifiers, so RFC 6570 operator expressions (e.g. `{?query}`) + # stay literal and never match. + VARIABLE_PATTERN = /\{([A-Za-z_]\w*)\}/.freeze attr_reader :uri_template_value attr_reader :title_value @@ -38,7 +37,7 @@ def to_h def inherited(subclass) super subclass.instance_variable_set(:@uri_template_value, nil) - subclass.instance_variable_set(:@uri_template_pattern, nil) + subclass.instance_variable_set(:@uri_template_parts, nil) subclass.instance_variable_set(:@name_value, nil) subclass.instance_variable_set(:@title_value, nil) subclass.instance_variable_set(:@description_value, nil) @@ -52,7 +51,7 @@ def uri_template(value = NOT_SET) if value == NOT_SET @uri_template_value else - @uri_template_pattern = nil + @uri_template_parts = nil @uri_template_value = value end end @@ -120,9 +119,50 @@ def meta(value = NOT_SET) # Matches a concrete URI against the template's simple RFC 6570 level-1 `{var}` expressions. # Returns a symbol-keyed Hash of variable values, or `nil` if the URI does not match. # Variables match one or more characters excluding `/`, and values are not percent-decoded. + # + # The match is the one the pattern `\A` + literals with `(?[^/]+)` for each variable + `\z` finds, each variable + # taking as much as it can from left to right, but it is computed without a backtracking search. Two variables in + # one path segment, as in `{name}.{ext}`, leave that search many ways to split a long run of the separator, and on + # Ruby before 3.2, whose engine does not memoize, a `resources/read` for such a URI kept the whole process busy + # for seconds to minutes. Here a literal that holds a `/` can sit in one place only, since no variable holds one, + # and inside a run of variables between two such places taking the last occurrence of each separator from + # the right gives the same split, so the cost is linear in the length of the URI. def match_uri(uri) - match = uri_template_pattern&.match(uri) - match&.named_captures&.transform_keys(&:to_sym) + parts = uri_template_parts + # A URI that is not a String, or not valid in its encoding, names no resource; the pattern raised on those. + return unless parts && uri.is_a?(String) && uri.valid_encoding? + + literals, names = parts + return unless uri.start_with?(literals.first) + + values = [] + position = literals.first.length + first = 0 + + while first < names.size + last = first + last += 1 while last < names.size - 1 && !literals[last + 1].include?("/") + + run_end, position_after = variable_run_bounds(uri, position, literals[last + 1]) + return unless run_end + + last.downto(first + 1) do |index| + separator = literals[index] + latest = run_end - 1 - separator.length + found = latest > position ? uri.rindex(separator, latest) : nil + return unless found && found > position + + values[index] = uri[(found + separator.length)...run_end] + run_end = found + end + values[first] = uri[position...run_end] + + first = last + 1 + position = position_after + end + + # A name used twice keeps the value of its last occurrence, as a named group does. + names.zip(values).to_h if position == uri.length end def define(uri_template: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, meta: nil, &block) @@ -141,12 +181,41 @@ def define(uri_template: nil, name: nil, title: nil, description: nil, icons: [] private - def uri_template_pattern + # The template as `[literals, names]`: the literal texts around the variables, one more than there are variables, + # and the variable names as symbols. + def uri_template_parts return if uri_template.nil? - @uri_template_pattern ||= begin - pattern = Regexp.escape(uri_template).gsub(VARIABLE_PATTERN) { "(?<#{Regexp.last_match(1)}>[^/]+)" } - Regexp.new("\\A#{pattern}\\z") + @uri_template_parts ||= begin + # Literals and names alternate, starting and ending with a literal; an empty template splits into nothing. + pieces = uri_template.split(VARIABLE_PATTERN, -1) + pieces = [""] if pieces.empty? + pairs = pieces.each_slice(2).to_a + + [pairs.map(&:first), pairs.map { |_literal, name| name }.compact.map(&:to_sym)] + end + end + + # Where a run of variables that starts at `position` ends, and where the literal closing it ends, + # as `[run_end, position_after]`; `nil` when the closing literal is not there or the run would be empty. + # A closing literal that holds a `/` starts where the first `/` of the rest of the URI puts it, since nothing in + # the run holds one. The literal that closes the last run of a template may hold none, and then it is + # the end of the URI, with no `/` left in the run. + def variable_run_bounds(uri, position, closing) + slash = closing.index("/") + if slash + first_slash = uri.index("/", position) + return unless first_slash + + run_end = first_slash - slash + return unless run_end > position && uri[run_end, closing.length] == closing + + [run_end, run_end + closing.length] + else + run_end = uri.length - closing.length + return unless run_end > position && uri.end_with?(closing) && !uri[position...run_end].include?("/") + + [run_end, uri.length] end end end diff --git a/test/mcp/resource_template_test.rb b/test/mcp/resource_template_test.rb index c028e934..46062603 100644 --- a/test/mcp/resource_template_test.rb +++ b/test/mcp/resource_template_test.rb @@ -176,6 +176,76 @@ def contents(user_id:) assert_nil UserProfileTemplate.match_uri("users://42/extra/profile") end + test ".match_uri gives each variable of one path segment as much as it can from left to right" do + template_class = Class.new(ResourceTemplate) do + uri_template "file:///{name}.{ext}" + end + adjacent = Class.new(ResourceTemplate) do + uri_template "x://{a}{b}-{c}/end" + end + + assert_equal({ name: "archive.tar", ext: "gz" }, template_class.match_uri("file:///archive.tar.gz")) + assert_nil template_class.match_uri("file:///archive") + assert_nil template_class.match_uri("file:///.gz") + assert_equal({ a: "p-q", b: "r", c: "s" }, adjacent.match_uri("x://p-qr-s/end")) + assert_nil adjacent.match_uri("x://p-s/end") + end + + test ".match_uri keeps the last value of a variable name used twice" do + template_class = Class.new(ResourceTemplate) do + uri_template "x://{id}/copy/{id}" + end + + assert_equal({ id: "2" }, template_class.match_uri("x://1/copy/2")) + end + + test ".match_uri agrees with the equivalent pattern on generated templates and URIs" do + # The pattern is what `match_uri` was implemented with; the generated inputs cover literals with and without `/`, + # adjacent variables, repeated names and text that only looks like a variable. + random = Random.new(20261111) + alphabet = ["a", "b", ".", "-", "/", "x", "{", "}"] + literals = ["", "a", ".", "-", "/", "a/", "/a", ".a", "//", "/x/", "{a", "{?q}", "a/b/a"] + + 2000.times do + template = +literals.sample(random: random) + random.rand(0..4).times { template << "{#{["a", "b", "c"].sample(random: random)}}" << literals.sample(random: random) } + template_class = Class.new(ResourceTemplate) { uri_template template } + groups = Regexp.escape(template).gsub(/\\\{([A-Za-z_]\w*)\\\}/) { "(?<#{Regexp.last_match(1)}>[^/]+)" } + pattern = /\A#{groups}\z/ + filled = template.gsub(/\{([A-Za-z_]\w*)\}/) { Array.new(random.rand(1..4)) { alphabet.sample(random: random) }.join } + scrambled = Array.new(random.rand(0..12)) { alphabet.sample(random: random) }.join + + [filled, scrambled].each do |uri| + expected = pattern.match(uri)&.named_captures&.transform_keys(&:to_sym) + + if expected.nil? + assert_nil(template_class.match_uri(uri), "#{template.inspect} on #{uri.inspect}") + else + assert_equal(expected, template_class.match_uri(uri), "#{template.inspect} on #{uri.inspect}") + end + end + end + end + + test ".match_uri answers a long run of separators without a backtracking search" do + # With the pattern, Ruby before 3.2 takes time cubic in the length of this URI: minutes at this size. + template_class = Class.new(ResourceTemplate) do + uri_template "x://{a}-{b}-{c}/end" + end + + assert_nil template_class.match_uri("x://#{"-" * 20_000}/") + assert_equal( + { a: "-" * 19_996, b: "-", c: "-" }, + template_class.match_uri("x://#{"-" * 20_000}/end"), + ) + end + + test ".match_uri returns nil for a URI that is not a String or not valid in its encoding" do + assert_nil UserProfileTemplate.match_uri(42) + assert_nil UserProfileTemplate.match_uri(nil) + assert_nil UserProfileTemplate.match_uri("users://4\xFF/profile".dup.force_encoding(Encoding::UTF_8)) + end + test ".match_uri returns nil when uri_template is not set" do template_class = Class.new(ResourceTemplate)