Skip to content

Commit

Permalink
Merge pull request #5882 from avalonmediasystem/session_overflow
Browse files Browse the repository at this point in the history
Limit the number of stream tokens in a user session to avoid SessionOverflow errors
  • Loading branch information
cjcolvar authored Jun 25, 2024
2 parents 8842a38 + 0809dbd commit 28fd378
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 2 deletions.
4 changes: 3 additions & 1 deletion app/models/stream_token.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ class StreamToken < ActiveRecord::Base
class Unauthorized < Exception; end

# attr_accessible :token, :target, :expires
class_attribute :max_tokens_per_user
self.max_tokens_per_user = 2000

def self.media_token(session)
session[:hash_tokens] ||= []
Expand Down Expand Up @@ -75,7 +77,7 @@ def self.logout!(session)

def self.purge_expired!(session)
purged = expired.delete_all
session[:hash_tokens] = StreamToken.where(token: Array(session[:hash_tokens])).pluck(:token)
session[:hash_tokens] = StreamToken.where(token: Array(session[:hash_tokens])).order(expires: :desc).limit(max_tokens_per_user).pluck(:token)
purged
end

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class ChangeSessionsDataToMediumText < ActiveRecord::Migration[7.0]
def change
change_column :sessions, :data, :text, limit: 16777215
end
end
2 changes: 1 addition & 1 deletion db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema[7.0].define(version: 2024_05_31_201828) do
ActiveRecord::Schema[7.0].define(version: 2024_06_24_204921) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

Expand Down
15 changes: 15 additions & 0 deletions spec/models/stream_token_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,5 +131,20 @@
expect(session[:hash_tokens]).not_to include(token)
end
end

context 'with custom max_tokens_per_user' do
before do
allow(StreamToken).to receive(:max_tokens_per_user).and_return(10)
end

it 'limits the number of tokens in the session' do
(1..10).each { |i| StreamToken.find_or_create_session_token(session, i.to_s) }
expect(session[:hash_tokens].size).to eq 11
expect(session[:hash_tokens]).to include(token)
StreamToken.purge_expired!(session)
expect(session[:hash_tokens].size).to eq 10
expect(session[:hash_tokens]).not_to include(token)
end
end
end
end

0 comments on commit 28fd378

Please sign in to comment.