# frozen_string_literal: true require "rails_helper" RSpec.describe Sessions::Create, "capacity / autoscaler kick" do def with_env(vars) previous = vars.keys.index_with { |k| ENV[k] } vars.each { |k, v| ENV[k] = v } yield ensure previous.each { |k, v| v.nil? ? ENV.delete(k) : ENV[k] = v } end let(:redis) { Redis.new(url: ENV.fetch("REDIS_URL", "redis://redis:6379/0")) } let(:user) { User.create!(email: "cap@example.com", name: "C", password: "Password123", role: "coach") } let(:club) { Club.create!(name: "Cap Club", sport: "volleyball") } let(:team) { club.teams.create!(name: "Cap Team", sport: "volleyball", slug: "cap-team") } let(:match) { team.matches.create!(opponent_name: "Opp", scheduled_at: 1.hour.from_now) } before do redis.del(Streams::AutoscalerJob::KICK_DEBOUNCE_KEY) Billing::AssignPlan.call(club: club, plan_slug: "premium_full") end it "kicks AutoscalerJob and raises stream_capacity_scaling when autoscaler is on" do with_env("STREAM_AUTOSCALE_ENABLED" => "1") do allow(Streams::NodeRegistry).to receive(:allocate!).and_raise(Streams::NodeRegistry::NoCapacityError, "full") expect(Streams::AutoscalerJob).to receive(:kick!).and_return(true) expect { described_class.new(user: user, match: match, params: { platform: "matchlivetv" }).call }.to raise_error(Teams::EntitlementError) { |e| expect(e.code).to eq("stream_capacity_scaling") } end end it "raises stream_capacity_exhausted when autoscaler is off" do with_env("STREAM_AUTOSCALE_ENABLED" => "0") do allow(Streams::NodeRegistry).to receive(:allocate!).and_raise(Streams::NodeRegistry::NoCapacityError, "full") expect(Streams::AutoscalerJob).not_to receive(:kick!) expect { described_class.new(user: user, match: match, params: { platform: "matchlivetv" }).call }.to raise_error(Teams::EntitlementError) { |e| expect(e.code).to eq("stream_capacity_exhausted") } end end end