A platform for community discussion. Free, open, simple.
PERF: Batch voice room directory state (#43156)
Sam6802427901db
diff --git a/plugins/voice/app/controllers/voice/rooms_controller.rb b/plugins/voice/app/controllers/voice/rooms_controller.rbindex 89512ecfde3..832d0a6f314 100644--- a/plugins/voice/app/controllers/voice/rooms_controller.rb+++ b/plugins/voice/app/controllers/voice/rooms_controller.rb@@ -44,22 +44,35 @@ module Voicedef indexVoice::DefaultRoomSeeder.ensure!+ # Capture before the room snapshot so a concurrent event is replayed rather than skipped.+ index_message_bus_last_id = MessageBus.last_id(Voice.room_index_channel)rooms =Voice::Room- .persistent+ .visible_to(guardian).includes(:room_memberships)- .order(:created_at)+ .order(:created_at, :id).select { |room| guardian.can_see_voice_room?(room) }-- # Captured before serializing so clients subscribing from this position- # never miss a directory event published while the response was built.- index_message_bus_last_id = MessageBus.last_id(Voice.room_index_channel)-- render json: {- rooms: serialize_data(rooms, Voice::RoomSerializer),- can_create_room: guardian.can_create_voice_room?,- index_message_bus_last_id: index_message_bus_last_id,- }+ directory_entries = Voice::RoomDirectoryPreloader.preload(rooms)+ chat_rooms =+ rooms.select do |room|+ entry = directory_entries[room.id]+ guardian.can_manage_voice_room?(room) ||+ entry&.participant_users&.any? { |participant| participant.id == current_user&.id }+ end+ chat_availability = rooms.to_h { |room| [room.id, false] }+ chat_availability.merge!(Voice::ChatSession.available_for_rooms(chat_rooms, guardian))++ render_json_dump(+ rooms:+ serialize_data(+ rooms,+ Voice::RoomSerializer,+ directory_entries: directory_entries,+ chat_availability: chat_availability,+ ),+ can_create_room: guardian.can_create_voice_room?,+ index_message_bus_last_id: index_message_bus_last_id,+ )enddef showdiff --git a/plugins/voice/app/models/voice/room.rb b/plugins/voice/app/models/voice/room.rbindex a69f04e4907..50f679a2ac9 100644--- a/plugins/voice/app/models/voice/room.rb+++ b/plugins/voice/app/models/voice/room.rb@@ -46,6 +46,28 @@ module Voicescope :persistent, -> { where(ephemeral: false) }scope :ephemeral, -> { where(ephemeral: true) }+ def self.visible_to(guardian)+ rooms = persistent+ return rooms.none unless SiteSetting.voice_enabled?++ unless guardian.can_access_voice?+ return guardian.voice_public_access? ? rooms.public_rooms : rooms.none+ end++ return rooms if guardian.is_staff?++ rooms.where(<<~SQL, user_id: guardian.user.id)+ "voice_rooms"."public"+ OR "voice_rooms"."creator_id" = :user_id+ OR EXISTS (+ SELECT 1+ FROM "voice_room_memberships"+ WHERE "voice_room_memberships"."room_id" = "voice_rooms"."id"+ AND "voice_room_memberships"."user_id" = :user_id+ )+ SQL+ end+# Strict by design: the column is an integer, so letting an unknown name# through means AR casts it with to_i and silently produces an open room.def self.room_type_from_name!(name)@@ -80,12 +102,38 @@ module VoiceSiteSetting.voice_video_enabled && video_enabledend+ def membership_for(user)+ return if user.blank?++ if room_memberships.loaded?+ room_memberships.find { |membership| membership.user_id == user.id }+ else+ room_memberships.find_by(user_id: user.id)+ end+ end++ def member?(user)+ membership_for(user).present?+ end++ def moderator?(user)+ membership_for(user)&.moderator? || false+ end+def moderator_ids- room_memberships.moderator.pluck(:user_id)+ if room_memberships.loaded?+ room_memberships.select(&:moderator?).map(&:user_id)+ else+ room_memberships.moderator.pluck(:user_id)+ endenddef member_ids- room_memberships.pluck(:user_id)+ if room_memberships.loaded?+ room_memberships.map(&:user_id)+ else+ room_memberships.pluck(:user_id)+ endenddef message_bus_targets@@ -108,6 +156,11 @@ module Voice@chat_channelend+ def preload_chat_channel(channel)+ @chat_channel_for_id = chat_channel_id+ @chat_channel = channel+ end+def reload(...)@chat_channel_for_id = @chat_channel = nilsuperdiff --git a/plugins/voice/app/serializers/voice/room_serializer.rb b/plugins/voice/app/serializers/voice/room_serializer.rbindex 7a7ee0fc210..0ad1deda2cd 100644--- a/plugins/voice/app/serializers/voice/room_serializer.rb+++ b/plugins/voice/app/serializers/voice/room_serializer.rb@@ -64,10 +64,11 @@ module Voiceobject.room_memberships.sizeend- # Read before active_participants (attributes serialize in declaration- # order) so clients subscribing from this position replay, at worst,- # broadcasts already reflected in the snapshot — never a gap.+ # The directory captures every room position before its live state. Other+ # callers rely on attribute order so concurrent broadcasts replay instead of being missed.def message_bus_last_id+ return directory_entry.message_bus_last_id if directory_entry+MessageBus.last_id(Voice.room_channel(object.id))end@@ -115,7 +116,13 @@ module Voicedef chat_availablereturn @chat_available if defined?(@chat_available)- @chat_available = Voice::ChatSession.available_for?(object, scope)++ @chat_available =+ if @options[:chat_availability]&.key?(object.id)+ @options[:chat_availability][object.id]+ else+ Voice::ChatSession.available_for?(object, scope)+ endend# The room's chat wiring isn't for general consumption: whether chat is@@ -148,15 +155,27 @@ module Voice# warn about mesh's IP exposure before joining, and a race that flips# mesh → livekit only makes the warning over-cautious.def expected_transport- Voice::ParticipantTracker.pinned_transport(object.id) ||- (Voice::Livekit.available_for?(object) ? "livekit" : "mesh")+ pinned_transport =+ if directory_entry+ directory_entry.pinned_transport+ else+ Voice::ParticipantTracker.pinned_transport(object.id)+ end++ pinned_transport || (Voice::Livekit.available_for?(object) ? "livekit" : "mesh")end# Not gated per user: an active recording is something everyone who can# see the room is entitled to know about.def recordingreturn @recording if defined?(@recording)- @recording = Voice::RecordingManager.status(object.id)++ @recording =+ if directory_entry+ directory_entry.recording+ else+ Voice::RecordingManager.status(object.id)+ endenddef include_recording?@@ -165,12 +184,32 @@ module Voiceprivate+ def directory_entry+ return @directory_entry if defined?(@directory_entry)++ @directory_entry = @options[:directory_entries]&.[](object.id)+ end+def tracked_participants- @tracked_participants ||= Voice::ParticipantTracker.list(object.id)+ return @tracked_participants if defined?(@tracked_participants)++ @tracked_participants =+ if directory_entry+ directory_entry.participant_users+ else+ Voice::ParticipantTracker.list(object.id)+ endenddef participant_metadata- @participant_metadata ||= Voice::ParticipantTracker.get_all_metadata(object.id)+ return @participant_metadata if defined?(@participant_metadata)++ @participant_metadata =+ if directory_entry+ directory_entry.participant_metadata+ else+ Voice::ParticipantTracker.get_all_metadata(object.id)+ endenddef participating?diff --git a/plugins/voice/app/services/voice/chat_session.rb b/plugins/voice/app/services/voice/chat_session.rbindex 7d9d3b530a8..75662b61829 100644--- a/plugins/voice/app/services/voice/chat_session.rb+++ b/plugins/voice/app/services/voice/chat_session.rb@@ -45,6 +45,51 @@ module Voiceguardian.can_chat? && guardian.can_join_chat_channel?(channel)end+ def available_for_rooms(rooms, guardian)+ availability = rooms.to_h { |room| [room.id, false] }+ return availability unless chat_available?+ return availability if guardian.anonymous? || !guardian.can_chat?++ channel_ids = rooms.filter_map(&:chat_channel_id).uniq+ return availability if channel_ids.empty?++ channels = ::Chat::Channel.includes(:chatable).where(id: channel_ids).index_by(&:id)+ direct_messages =+ channels.values.filter_map do |channel|+ channel.chatable if channel.direct_message_channel?+ end+ if direct_messages.present?+ ActiveRecord::Associations::Preloader.new(+ records: direct_messages,+ associations: :users,+ ).call+ end++ category_ids =+ channels.values.filter_map { |channel| channel.chatable_id if channel.category_channel? }+ post_allowed_category_ids =+ if !guardian.is_anonymous? && category_ids.present?+ Category.post_create_allowed(guardian).where(id: category_ids).pluck(:id)+ end++ rooms.each do |room|+ channel = channels[room.chat_channel_id]+ room.preload_chat_channel(channel)+ next unless channel++ availability[room.id] = if post_allowed_category_ids+ guardian.can_join_chat_channel?(+ channel,+ post_allowed_category_ids: post_allowed_category_ids,+ )+ else+ guardian.can_join_chat_channel?(channel)+ end+ end++ availability+ end+# A snapshot of the room's live chat session for the client: the linked# channel and the active thread (if any). Never creates anything.def state(room)diff --git a/plugins/voice/app/services/voice/default_room_seeder.rb b/plugins/voice/app/services/voice/default_room_seeder.rbindex 98b5408106e..2d98dd5f302 100644--- a/plugins/voice/app/services/voice/default_room_seeder.rb+++ b/plugins/voice/app/services/voice/default_room_seeder.rb@@ -7,7 +7,9 @@ module Voicedef self.ensure!return unless SiteSetting.voice_enabled?- return unless ActiveRecord::Base.connection.table_exists?(:voice_rooms)+ return unless schema_ready?+ return if Voice::Room.persistent.exists?+# Runs at plugin activation, which can precede pending migrations (dev# DBs, rake db:migrate itself) — and Room queries the newest columns.# DatabaseTasks.migrations_paths is the set that includes plugin paths;@@ -32,5 +34,16 @@ module VoiceVoice::DirectoryBroadcaster.broadcast(action: :created, room: room)endend++ def self.schema_ready?+ @schema_ready ||= {}+ site = RailsMultisite::ConnectionManagement.current_db+ return true if @schema_ready[site]++ connection = ActiveRecord::Base.connection+ @schema_ready[site] = connection.table_exists?(:voice_rooms) &&+ connection.column_exists?(:voice_rooms, :ephemeral)+ end+ private_class_method :schema_ready?endenddiff --git a/plugins/voice/app/services/voice/participant_tracker.rb b/plugins/voice/app/services/voice/participant_tracker.rbindex 1f7a9c673d4..8b464e66fe1 100644--- a/plugins/voice/app/services/voice/participant_tracker.rb+++ b/plugins/voice/app/services/voice/participant_tracker.rb@@ -5,6 +5,8 @@ module VoiceKEY_NAMESPACE = "voice:room"RECENTLY_ACTIVE_ROOMS_KEY = "voice:recently_active_rooms"SAFETY_TTL = 30.minutes.to_i+ RoomState =+ Data.define(:participant_ids, :participant_metadata, :pinned_transport, :recording_info)# Must outlive one client heartbeat interval (10s) plus request latency,# so a beat already in flight when the user leaves can't resurrect them.LEFT_TOMBSTONE_TTL = 15@@ -184,6 +186,49 @@ module VoiceUser.where(id: ids)end+ def room_states(room_ids)+ room_ids = room_ids.map(&:to_i).uniq+ return {} if room_ids.empty?++ cutoff = Time.now.to_f - SiteSetting.voice_participant_ttl_seconds+ participant_futures = {}+ metadata_futures = {}+ scalar_future = nil++ pipeline_result =+ redis.pipelined do |pipeline|+ room_ids.each do |room_id|+ participant_futures[room_id] = pipeline.zrangebyscore(key(room_id), cutoff, "+inf")+ metadata_futures[room_id] = pipeline.hgetall(metadata_key(room_id))+ end++ scalar_future =+ pipeline.mget(+ *room_ids.flat_map { |room_id| [transport_key(room_id), recording_key(room_id)] },+ )+ end++ return room_states_individually(room_ids) if pipeline_result.nil?++ scalar_values = scalar_future.value.each_slice(2).to_a+ room_ids.each_with_index.to_h do |room_id, index|+ transport, raw_recording = scalar_values[index]+ [+ room_id,+ RoomState.new(+ participant_ids: participant_futures[room_id].value.map(&:to_i).select(&:positive?),+ participant_metadata: deserialize_all_metadata(metadata_futures[room_id].value),+ pinned_transport: transport,+ recording_info: deserialize_recording(raw_recording),+ ),+ ]+ end+ rescue Redis::CommandError => error+ raise if error.message.exclude?("WRONGTYPE")++ room_states_individually(room_ids)+ end+def user_ids(room_id, migrated: false)cutoff = Time.now.to_f - SiteSetting.voice_participant_ttl_secondsredis.zrangebyscore(key(room_id), cutoff, "+inf").map(&:to_i).select(&:positive?)@@ -239,10 +284,7 @@ module Voiceenddef get_all_metadata(room_id)- raw = redis.hgetall(metadata_key(room_id))- raw- .transform_keys(&:to_i)- .transform_values { |value| JSON.parse(value, symbolize_names: true) }+ deserialize_all_metadata(redis.hgetall(metadata_key(room_id)))end# A stable hash of the live (TTL-filtered) membership plus the metadata@@ -307,8 +349,7 @@ module Voiceenddef recording(room_id)- raw = redis.get(recording_key(room_id))- raw.present? ? JSON.parse(raw, symbolize_names: true) : nil+ deserialize_recording(redis.get(recording_key(room_id)))enddef clear_recording(room_id)@@ -335,6 +376,27 @@ module Voiceprivate+ def deserialize_all_metadata(raw)+ raw+ .transform_keys(&:to_i)+ .transform_values { |value| JSON.parse(value, symbolize_names: true) }+ end++ def deserialize_recording(raw)+ raw.present? ? JSON.parse(raw, symbolize_names: true) : nil+ end++ def room_states_individually(room_ids)+ room_ids.index_with do |room_id|+ RoomState.new(+ participant_ids: user_ids(room_id),+ participant_metadata: get_all_metadata(room_id),+ pinned_transport: pinned_transport(room_id),+ recording_info: recording(room_id),+ )+ end+ end+def redis@redis ||= Discourse.redisenddiff --git a/plugins/voice/app/services/voice/recording_manager.rb b/plugins/voice/app/services/voice/recording_manager.rbindex 9ed4967ee5c..120d6be9c91 100644--- a/plugins/voice/app/services/voice/recording_manager.rb+++ b/plugins/voice/app/services/voice/recording_manager.rb@@ -36,7 +36,10 @@ module Voice# Public shape shared by the serializer, the broadcasts, and the# start endpoint's response.def status(room_id)- info = Voice::ParticipantTracker.recording(room_id)+ status_from_info(Voice::ParticipantTracker.recording(room_id))+ end++ def status_from_info(info)return nil if info.nil?{diff --git a/plugins/voice/app/services/voice/room_directory_preloader.rb b/plugins/voice/app/services/voice/room_directory_preloader.rbnew file mode 100644index 00000000000..32c05bc5cf8--- /dev/null+++ b/plugins/voice/app/services/voice/room_directory_preloader.rb@@ -0,0 +1,48 @@+# frozen_string_literal: true++module Voice+ class RoomDirectoryPreloader+ Entry =+ Data.define(+ :message_bus_last_id,+ :participant_users,+ :participant_metadata,+ :pinned_transport,+ :recording,+ )++ def self.preload(rooms)+ new(rooms).preload+ end++ def initialize(rooms)+ @rooms = rooms+ end++ def preload+ room_ids = @rooms.map(&:id)+ return {} if room_ids.empty?++ channels_by_room_id = room_ids.to_h { |room_id| [room_id, Voice.room_channel(room_id)] }+ last_ids = MessageBus.last_ids(*channels_by_room_id.values)+ room_states = Voice::ParticipantTracker.room_states(room_ids)+ users_by_id =+ User.where(id: room_states.values.flat_map(&:participant_ids).uniq).index_by(&:id)++ room_ids.to_h do |room_id|+ state = room_states.fetch(room_id)+ channel = channels_by_room_id.fetch(room_id)+ [+ room_id,+ Entry.new(+ message_bus_last_id: last_ids.fetch(channel),+ participant_users: state.participant_ids.filter_map { |user_id| users_by_id[user_id] },+ participant_metadata: state.participant_metadata,+ pinned_transport: state.pinned_transport,+ recording: Voice::RecordingManager.status_from_info(state.recording_info),+ ),+ ]+ end+ end+ end+enddiff --git a/plugins/voice/lib/voice/guardian_extension.rb b/plugins/voice/lib/voice/guardian_extension.rbindex b0e95d51fde..d28b4dd6ee7 100644--- a/plugins/voice/lib/voice/guardian_extension.rb+++ b/plugins/voice/lib/voice/guardian_extension.rb@@ -54,7 +54,7 @@ module Voicereturn false unless can_access_voice?return false unless room- is_staff? || room.creator_id == user.id || room.moderator_ids.include?(user.id)+ is_staff? || room.creator_id == user.id || room.moderator?(user)enddef ensure_can_manage_voice_room!(room)@@ -73,7 +73,7 @@ module Voicereturn false unless can_access_voice?return false unless room- room.public? || room.member_ids.include?(user.id) || can_manage_voice_room?(room)+ room.public? || room.member?(user) || can_manage_voice_room?(room)enddef ensure_can_join_voice_room!(room)@@ -128,7 +128,7 @@ module Voicedef can_speak_in_voice_room?(room)return true if room.open?return true if user&.admin?- membership = room.room_memberships.find { |m| m.user_id == user&.id }+ membership = room.membership_for(user)membership&.can_speak? || falseenddiff --git a/plugins/voice/lib/voice/room_hashtag_data_source.rb b/plugins/voice/lib/voice/room_hashtag_data_source.rbindex db84c90ed08..5625a4b3b10 100644--- a/plugins/voice/lib/voice/room_hashtag_data_source.rb+++ b/plugins/voice/lib/voice/room_hashtag_data_source.rb@@ -68,14 +68,9 @@ module Voicevisible_rooms(guardian, Voice::Room.all).take(limit).map { |room| room_to_hashtag_item(room) }end- # Visibility is a per-room Guardian question (membership, public flag,- # manager status), so it can't be expressed as a SQL scope; room counts- # are small, so filtering loaded records matches RoomsController#index.def self.visible_rooms(guardian, scope)- return [] unless guardian.can_access_voice? || guardian.voice_public_access?-scope- .persistent+ .merge(Voice::Room.visible_to(guardian)).includes(:room_memberships).order(:name).select { |room| guardian.can_see_voice_room?(room) }diff --git a/plugins/voice/spec/models/voice/room_spec.rb b/plugins/voice/spec/models/voice/room_spec.rbindex 308c4fafc1b..ac0d64ce8e8 100644--- a/plugins/voice/spec/models/voice/room_spec.rb+++ b/plugins/voice/spec/models/voice/room_spec.rb@@ -29,6 +29,51 @@ RSpec.describe Voice::Room dofab!(:room, :voice_room)+ describe ".visible_to" do+ def visible_room_ids(guardian, room_ids)+ described_class.visible_to(guardian).where(id: room_ids).pluck(:id)+ end++ it "matches room visibility for public access, members, creators, and staff" do+ SiteSetting.voice_enabled = true+ SiteSetting.voice_allowed_groups =+ "#{Group::AUTO_GROUPS[:anonymous_users]}|#{Group::AUTO_GROUPS[:logged_in_users]}"+ owner = Fabricate(:user)+ member = Fabricate(:user)+ staff = Fabricate(:admin)+ public_room = Fabricate(:voice_room, creator: owner, public: true)+ private_room = Fabricate(:voice_room, creator: owner, public: false)+ private_room.room_memberships.create!(user: member)+ creator_only_room = Fabricate(:voice_room, creator: owner, public: false)+ creator_only_room.room_memberships.delete_all+ ephemeral_room = Fabricate(:voice_ephemeral_room, creator: owner, public: true)+ room_ids = [public_room, private_room, creator_only_room, ephemeral_room].map(&:id)++ expect(visible_room_ids(Guardian.new(nil), room_ids)).to contain_exactly(public_room.id)+ expect(visible_room_ids(member.guardian, room_ids)).to contain_exactly(+ public_room.id,+ private_room.id,+ )+ expect(visible_room_ids(owner.guardian, room_ids)).to contain_exactly(+ public_room.id,+ private_room.id,+ creator_only_room.id,+ )+ expect(visible_room_ids(staff.guardian, room_ids)).to contain_exactly(+ public_room.id,+ private_room.id,+ creator_only_room.id,+ )++ SiteSetting.voice_allowed_groups = Group::AUTO_GROUPS[:anonymous_users].to_s+ expect(visible_room_ids(member.guardian, room_ids)).to contain_exactly(public_room.id)+ expect(visible_room_ids(staff.guardian, room_ids)).to contain_exactly(public_room.id)++ SiteSetting.voice_enabled = false+ expect(visible_room_ids(Guardian.new(nil), room_ids)).to be_empty+ end+ end+describe "slug generation" doit "appends a random suffix for ephemeral rooms so generic names never collide" dopersistent = Fabricate(:voice_room, name: "Call")@@ -93,6 +138,23 @@ RSpec.describe Voice::Room doendend+ describe "membership predicates" do+ it "reuses loaded memberships" do+ creator = room.creator+ room.room_memberships.load++ queries =+ track_sql_queries do+ expect(room.member?(creator)).to eq(true)+ expect(room.moderator?(creator)).to eq(true)+ expect(room.member_ids).to contain_exactly(room.creator_id)+ expect(room.moderator_ids).to contain_exactly(room.creator_id)+ end++ expect(queries).to be_empty+ end+ end+describe "chat_idle_minutes validation" doit "rejects a value below the 2 minute floor" doroom.chat_idle_minutes = 1diff --git a/plugins/voice/spec/requests/voice/rooms_controller_spec.rb b/plugins/voice/spec/requests/voice/rooms_controller_spec.rbindex ebf03d1d9bd..8f97e61141a 100644--- a/plugins/voice/spec/requests/voice/rooms_controller_spec.rb+++ b/plugins/voice/spec/requests/voice/rooms_controller_spec.rb@@ -70,6 +70,69 @@ RSpec.describe Voice::RoomsController doexpect(response.parsed_body["rooms"].first["message_bus_last_id"]).to be_a(Integer)end+ it "returns preloaded participant and recording state" do+ sign_in(user)+ Voice::ParticipantTracker.add(room.id, other_participant.id)+ Voice::ParticipantTracker.update_metadata(room.id, other_participant.id, muted: true)+ Voice::ParticipantTracker.set_recording(+ room.id,+ egress_id: "EG_1",+ user_id: staff.id,+ username: staff.username,+ started_at: 123.0,+ )++ get "/voice/rooms.json"++ listed_room = response.parsed_body["rooms"].find { |candidate| candidate["id"] == room.id }+ expect(listed_room["active_participants"]).to contain_exactly(+ include("id" => other_participant.id, "muted" => true),+ )+ expect(listed_room["recording"]).to eq(+ "started_at" => 123.0,+ "started_by" => {+ "id" => staff.id,+ "username" => staff.username,+ },+ )+ ensure+ Voice::ParticipantTracker.clear(room.id)+ end++ it "does not add membership queries as the directory grows" do+ sign_in(user)+ get "/voice/rooms.json"++ initial_queries =+ track_sql_queries { get "/voice/rooms.json" }.grep(/voice_room_memberships/).size++ 4.times { Fabricate(:voice_room, creator: Fabricate(:user), public: true) }+ expanded_queries =+ track_sql_queries { get "/voice/rooms.json" }.grep(/voice_room_memberships/).size++ expect(expanded_queries).to eq(initial_queries)+ end++ it "does not add chat channel queries as the directory grows" do+ SiteSetting.voice_chat_enabled = true+ SiteSetting.chat_enabled = true+ room.update!(chat_channel_id: Fabricate(:chat_channel, threading_enabled: true).id)+ sign_in(staff)++ initial_queries =+ track_sql_queries { get "/voice/rooms.json" }.grep(/FROM "chat_channels"/).size++ 4.times do+ channel = Fabricate(:chat_channel, threading_enabled: true)+ Fabricate(:voice_room, creator: Fabricate(:user), public: true, chat_channel_id: channel.id)+ end+ expanded_queries =+ track_sql_queries { get "/voice/rooms.json" }.grep(/FROM "chat_channels"/).size++ expect(initial_queries).to eq(1)+ expect(expanded_queries).to eq(initial_queries)+ end+it "hides non-public rooms from non-members who can create rooms" dosign_in(user)diff --git a/plugins/voice/spec/services/voice/chat_session_spec.rb b/plugins/voice/spec/services/voice/chat_session_spec.rbindex 079a5224cab..c6f19d8d918 100644--- a/plugins/voice/spec/services/voice/chat_session_spec.rb+++ b/plugins/voice/spec/services/voice/chat_session_spec.rb@@ -73,6 +73,34 @@ RSpec.describe Voice::ChatSession doendend+ describe ".available_for_rooms" do+ it "loads linked channels once and returns availability by room" do+ other_channel = Fabricate(:chat_channel, threading_enabled: true)+ other_room = Fabricate(:voice_room, public: true, chat_channel_id: other_channel.id)+ unlinked_room = Fabricate(:voice_room, public: true)++ availability = nil+ queries =+ track_sql_queries do+ availability =+ described_class.available_for_rooms([room, other_room, unlinked_room], user.guardian)+ end++ expect(availability).to eq(room.id => true, other_room.id => true, unlinked_room.id => false)+ expect(queries.grep(/FROM "chat_channels"/).size).to eq(1)+ end++ it "denies a channel in a category the user cannot access" do+ restricted_channel =+ Fabricate(:private_category_channel, group: Fabricate(:group), threading_enabled: true)+ restricted_room = Fabricate(:voice_room, public: true, chat_channel_id: restricted_channel.id)++ availability = described_class.available_for_rooms([room, restricted_room], user.guardian)++ expect(availability).to eq(room.id => true, restricted_room.id => false)+ end+ end+describe ".state" doit "returns the channel with no thread before a session starts" doexpect(described_class.state(room)).to eq({ channel_id: channel.id, thread_id: nil })diff --git a/plugins/voice/spec/services/voice/default_room_seeder_multisite_spec.rb b/plugins/voice/spec/services/voice/default_room_seeder_multisite_spec.rbnew file mode 100644index 00000000000..f524e83000f--- /dev/null+++ b/plugins/voice/spec/services/voice/default_room_seeder_multisite_spec.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++RSpec.describe Voice::DefaultRoomSeeder, type: :multisite do+ it "keeps schema readiness isolated by site" do+ described_class.instance_variable_set(:@schema_ready, nil)+ SiteSetting.voice_enabled = true+ described_class.ensure!++ test_multisite_connection("second") do+ SiteSetting.voice_enabled = true+ ActiveRecord::Base.connection.remove_column(:voice_rooms, :ephemeral)++ expect { described_class.ensure! }.not_to raise_error+ end+ ensure+ described_class.instance_variable_set(:@schema_ready, nil)+ test_multisite_connection("second") do+ ActiveRecord::Base.connection.schema_cache.clear_data_source_cache!("voice_rooms")+ end+ Voice::Room.reset_column_information+ end+enddiff --git a/plugins/voice/spec/services/voice/default_room_seeder_spec.rb b/plugins/voice/spec/services/voice/default_room_seeder_spec.rbindex 78cdfdb9ef3..0dc9ee5bf5e 100644--- a/plugins/voice/spec/services/voice/default_room_seeder_spec.rb+++ b/plugins/voice/spec/services/voice/default_room_seeder_spec.rb@@ -36,12 +36,16 @@ RSpec.describe Voice::DefaultRoomSeeder doexpect { described_class.ensure! }.to change { Voice::Room.persistent.count }.by(1)end- it "does nothing if rooms already exist" do+ it "does nothing if rooms already exist without checking pending migrations" doSiteSetting.voice_enabled = truewipe_rooms!Fabricate(:voice_room, name: "Existing", creator: Fabricate(:admin))- expect { described_class.ensure! }.not_to change { Voice::Room.count }+ described_class.ensure!+ queries = track_sql_queries { described_class.ensure! }++ expect(Voice::Room.count).to eq(1)+ expect(queries.grep(/pg_class|schema_migrations/)).to be_emptyenddef wipe_rooms!diff --git a/plugins/voice/spec/services/voice/participant_tracker_spec.rb b/plugins/voice/spec/services/voice/participant_tracker_spec.rbindex 845ca5bcfaf..9f85be11396 100644--- a/plugins/voice/spec/services/voice/participant_tracker_spec.rb+++ b/plugins/voice/spec/services/voice/participant_tracker_spec.rb@@ -296,6 +296,69 @@ RSpec.describe Voice::ParticipantTracker doendend+ describe ".room_states" do+ fab!(:other_room, :voice_room)++ after { described_class.clear(other_room.id) }++ it "loads participant, metadata, transport, and recording state for several rooms" do+ described_class.add(room.id, user1.id)+ described_class.update_metadata(room.id, user1.id, role: "moderator")+ described_class.pin_transport!(room.id, "livekit")+ described_class.set_recording(+ room.id,+ egress_id: "EG_1",+ user_id: user1.id,+ username: user1.username,+ started_at: 123.0,+ )+ described_class.add(other_room.id, user2.id)++ states = described_class.room_states([room.id, other_room.id])++ expect(states[room.id].to_h).to eq(+ participant_ids: [user1.id],+ participant_metadata: {+ user1.id => {+ role: "moderator",+ },+ },+ pinned_transport: "livekit",+ recording_info: {+ egress_id: "EG_1",+ user_id: user1.id,+ username: user1.username,+ started_at: 123.0,+ },+ )+ expect(states[other_room.id].to_h).to eq(+ participant_ids: [user2.id],+ participant_metadata: {+ },+ pinned_transport: nil,+ recording_info: nil,+ )+ end++ it "filters expired participants and repairs legacy participant keys" do+ participant_key = "#{described_class::KEY_NAMESPACE}:#{room.id}:participants"+ Discourse.redis.set(participant_key, user1.id)+ described_class.add(other_room.id, user2.id)+ Discourse.redis.zadd(+ "#{described_class::KEY_NAMESPACE}:#{other_room.id}:participants",+ 1.hour.ago.to_f,+ user1.id,+ )++ states = described_class.room_states([room.id, other_room.id])++ expect(states.transform_values(&:participant_ids)).to eq(+ room.id => [],+ other_room.id => [user2.id],+ )+ end+ end+describe ".participants_fingerprint" doit "is stable across calls and independent of insertion order" dodescribed_class.add(room.id, user1.id)diff --git a/plugins/voice/spec/services/voice/room_directory_preloader_multisite_spec.rb b/plugins/voice/spec/services/voice/room_directory_preloader_multisite_spec.rbnew file mode 100644index 00000000000..a0617b674b3--- /dev/null+++ b/plugins/voice/spec/services/voice/room_directory_preloader_multisite_spec.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++RSpec.describe Voice::RoomDirectoryPreloader, type: :multisite do+ let(:room_id) { 9_000_000 + SecureRandom.random_number(100_000) }++ after do+ %w[default second].each do |site|+ RailsMultisite::ConnectionManagement.with_connection(site) do+ Voice::ParticipantTracker.clear(room_id)+ end+ end+ end++ it "keeps batched Redis and MessageBus room state isolated by site" do+ channel = Voice.room_channel(room_id)+ Voice::ParticipantTracker.add(room_id, 101)+ Voice::ParticipantTracker.update_metadata(room_id, 101, muted: true)+ Voice::ParticipantTracker.pin_transport!(room_id, "mesh")+ default_message_id = MessageBus.publish(channel, type: "participants")++ test_multisite_connection("second") do+ second_state = Voice::ParticipantTracker.room_states([room_id]).fetch(room_id)++ expect(second_state.participant_ids).to be_empty+ expect(second_state.participant_metadata).to be_empty+ expect(second_state.pinned_transport).to be_nil+ expect(MessageBus.last_ids(channel).fetch(channel)).to eq(0)++ Voice::ParticipantTracker.add(room_id, 202)+ Voice::ParticipantTracker.pin_transport!(room_id, "livekit")+ MessageBus.publish(channel, type: "participants")+ end++ default_state = Voice::ParticipantTracker.room_states([room_id]).fetch(room_id)+ expect(default_state.participant_ids).to eq([101])+ expect(default_state.participant_metadata).to eq(101 => { muted: true })+ expect(default_state.pinned_transport).to eq("mesh")+ expect(MessageBus.last_ids(channel).fetch(channel)).to eq(default_message_id)+ end+enddiff --git a/plugins/voice/spec/services/voice/room_directory_preloader_spec.rb b/plugins/voice/spec/services/voice/room_directory_preloader_spec.rbnew file mode 100644index 00000000000..c62f2809a05--- /dev/null+++ b/plugins/voice/spec/services/voice/room_directory_preloader_spec.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++RSpec.describe Voice::RoomDirectoryPreloader do+ fab!(:first_room, :voice_room)+ fab!(:second_room, :voice_room)+ fab!(:first_user, :user)+ fab!(:second_user, :user)++ before do+ SiteSetting.voice_enabled = true+ Voice::ParticipantTracker.add(first_room.id, first_user.id)+ Voice::ParticipantTracker.add(first_room.id, second_user.id)+ Voice::ParticipantTracker.add(second_room.id, first_user.id)+ Voice::ParticipantTracker.update_metadata(first_room.id, first_user.id, muted: true)+ Voice::ParticipantTracker.pin_transport!(first_room.id, "livekit")+ Voice::ParticipantTracker.set_recording(+ first_room.id,+ egress_id: "EG_1",+ user_id: first_user.id,+ username: first_user.username,+ started_at: 123.0,+ )+ end++ after do+ Voice::ParticipantTracker.clear(first_room.id)+ Voice::ParticipantTracker.clear(second_room.id)+ end++ it "preloads live room state and participant users for the directory" do+ entries = described_class.preload([first_room, second_room])++ expect(entries[first_room.id].message_bus_last_id).to be_a(Integer)+ expect(entries[first_room.id].participant_users).to eq([first_user, second_user])+ expect(entries[first_room.id].participant_metadata).to eq(first_user.id => { muted: true })+ expect(entries[first_room.id].pinned_transport).to eq("livekit")+ expect(entries[first_room.id].recording).to eq(+ started_at: 123.0,+ started_by: {+ id: first_user.id,+ username: first_user.username,+ },+ )+ expect(entries[second_room.id].participant_users).to eq([first_user])+ expect(entries[second_room.id].recording).to be_nil+ end++ it "loads participant users in one query regardless of room count" do+ user_queries =+ track_sql_queries { described_class.preload([first_room, second_room]) }.grep(/FROM "users"/)++ expect(user_queries.size).to eq(1)+ end++ it "pipelines live room state in one Redis round trip" do+ MethodProfiler.ensure_discourse_instrumentation!+ MethodProfiler.start++ described_class.preload([first_room, second_room])+ profile = MethodProfiler.stop++ expect(profile.dig(:redis, :calls)).to eq(1)+ ensure+ MethodProfiler.clear+ end++ it "does no work for an empty directory" do+ expect(track_sql_queries { described_class.preload([]) }).to be_empty+ expect(described_class.preload([])).to eq({})+ end+end