From 63731425130b6b4ca96753348a6edf0d0b094648 Mon Sep 17 00:00:00 2001 From: Frederick Cheung Date: Fri, 10 Jul 2020 12:56:40 +0100 Subject: [PATCH] Fix memory leak caused by caching all unique paths seen This optimisation was introduced in #2002. If an api's paths include an id in the path then this cache can grow in an unbounded manner. --- CHANGELOG.md | 1 + lib/grape/router.rb | 18 +++++------------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c50d10928d..6af761ee6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ * [#2060](https://github.com/ruby-grape/grape/pull/2060): Drop support for Ruby 2.4 - [@dblock](https://github.com/dblock). * [#2060](https://github.com/ruby-grape/grape/pull/2060): Upgraded Rubocop to 0.84.0 - [@dblock](https://github.com/dblock). * [#2077](https://github.com/ruby-grape/grape/pull/2077): Simplify logic for defining declared params - [@dnesteryuk](https://github.com/dnesteryuk). +* [#2084](https://github.com/ruby-grape/grape/pull/2084): Fix memory leak in path normalization- [@fcheung](https://github.com/fcheung). * Your contribution here. #### Fixes diff --git a/lib/grape/router.rb b/lib/grape/router.rb index f2b8cf2416..c5d9e96422 100644 --- a/lib/grape/router.rb +++ b/lib/grape/router.rb @@ -7,20 +7,12 @@ module Grape class Router attr_reader :map, :compiled - class NormalizePathCache < Grape::Util::Cache - def initialize - @cache = Hash.new do |h, path| - normalized_path = +"/#{path}" - normalized_path.squeeze!('/') - normalized_path.sub!(%r{/+\Z}, '') - normalized_path = '/' if normalized_path.empty? - h[path] = -normalized_path - end - end - end - def self.normalize_path(path) - NormalizePathCache[path] + path = +"/#{path}" + path.squeeze!('/') + path.sub!(%r{/+\Z}, '') + path = '/' if path == '' + path end def self.supported_methods