Clean up live websocket style

This commit is contained in:
Daniel Schädler 2026-04-24 15:49:45 +02:00
parent a282f63b56
commit 3dcc9727a5
8 changed files with 113 additions and 59 deletions

View File

@ -5,7 +5,7 @@ class TournamentMatchesChannel < ApplicationCable::Channel
tournament = Tournament.find(params[:tournament_id]) tournament = Tournament.find(params[:tournament_id])
state = params[:state].presence state = params[:state].presence
stream_for TournamentMatchesBroadcast.stream_target(tournament, state: state) stream_for TournamentMatchesBroadcast.stream_target(tournament, state:)
transmit TournamentMatchesBroadcastPayload.build(tournament, state: state) transmit TournamentMatchesBroadcastPayload.build(tournament, state:)
end end
end end

View File

@ -10,8 +10,8 @@ class TournamentMatchesBroadcast
STATES.each do |state| STATES.each do |state|
TournamentMatchesChannel.broadcast_to( TournamentMatchesChannel.broadcast_to(
stream_target(tournament, state: state), stream_target(tournament, state:),
TournamentMatchesBroadcastPayload.build(tournament, state: state) TournamentMatchesBroadcastPayload.build(tournament, state:)
) )
end end
end end

View File

@ -6,8 +6,8 @@ class TournamentMatchesBroadcastPayload
{ {
type: 'tournament_matches.updated', type: 'tournament_matches.updated',
tournament_id: tournament.id, tournament_id: tournament.id,
state: state, state:,
matches: TournamentMatchesPayload.build(tournament, state: state) matches: TournamentMatchesPayload.build(tournament, state:)
} }
end end
end end

View File

@ -3,7 +3,7 @@
class TournamentMatchesPayload class TournamentMatchesPayload
class << self class << self
def build(tournament, state: nil) def build(tournament, state: nil)
serialized_matches(matches_for(tournament, state: state)) serialized_matches(matches_for(tournament, state:))
end end
def matches_for(tournament, state: nil) def matches_for(tournament, state: nil)
@ -16,22 +16,33 @@ class TournamentMatchesPayload
private private
def upcoming_matches_for(tournament) def upcoming_matches_for(tournament)
upcoming_group_matches(tournament).presence || upcoming_playoff_matches(tournament)
end
def upcoming_group_matches(tournament)
group_stage = tournament.stages.find { |stage| stage.level == -1 } group_stage = tournament.stages.find { |stage| stage.level == -1 }
group_matches = group_stage&.groups&.map do |group| return [] if group_stage.nil?
group_stage.groups.filter_map do |group|
group.matches.select { |match| match.state == 'not_started' }.min_by(&:position) group.matches.select { |match| match.state == 'not_started' }.min_by(&:position)
end&.compact
return group_matches unless group_matches.blank?
next_level = nil
tournament.stages.reject { |stage| stage.level.nil? }.sort_by(&:level).reverse_each do |stage|
next unless stage.matches.any?
next unless stage.matches.all?(&:in_progress?)
next_level = stage.level - 1
break
end end
end
tournament.stages.find { |stage| stage.level == next_level }&.matches || [] def upcoming_playoff_matches(tournament)
active_stage = playoff_stages(tournament).reverse.find do |stage|
stage_with_running_matches?(stage)
end
return [] if active_stage.nil?
tournament.stages.find { |stage| stage.level == active_stage.level - 1 }&.matches || []
end
def stage_with_running_matches?(stage)
stage.matches.any? && stage.matches.all?(&:in_progress?)
end
def playoff_stages(tournament)
tournament.stages.reject { |stage| stage.level.nil? }.sort_by(&:level)
end end
def serialized_matches(matches) def serialized_matches(matches)

View File

@ -7,7 +7,7 @@ class TournamentPayload
tournament, tournament,
serializer: TournamentSerializer, serializer: TournamentSerializer,
include: '**', include: '**',
scope: scope scope:
).as_json ).as_json
end end
end end

View File

@ -53,7 +53,7 @@ module TurniereE2E
def subscribe_tournament!(tournament_id:) def subscribe_tournament!(tournament_id:)
identifier = { identifier = {
channel: 'TournamentChannel', channel: 'TournamentChannel',
tournament_id: tournament_id tournament_id:
}.to_json }.to_json
subscribe!(identifier:) do |message| subscribe!(identifier:) do |message|
@ -64,8 +64,8 @@ module TurniereE2E
def subscribe_matches!(tournament_id:, state: nil) def subscribe_matches!(tournament_id:, state: nil)
identifier = { identifier = {
channel: 'TournamentMatchesChannel', channel: 'TournamentMatchesChannel',
tournament_id: tournament_id, tournament_id:,
state: state state:
}.compact.to_json }.compact.to_json
subscribe!(identifier:) do |message| subscribe!(identifier:) do |message|

View File

@ -26,16 +26,23 @@ RSpec.describe 'Tournament follower sync live websocket HTTP E2E' do
let(:source_client) { login_client(base_url: source_base_url) } let(:source_client) { login_client(base_url: source_base_url) }
it 'broadcasts follower tournament and match updates after source match sync import' do it 'broadcasts follower tournament and match updates after source match sync import' do
source = create_group_stage_tournament(client: source_client, base_url: source_base_url, name_prefix: 'Ws Live Source') source = create_group_stage_tournament(
client: source_client,
base_url: source_base_url,
name_prefix: 'Ws Live Source'
)
follower = create_follower_tournament(name_prefix: 'Ws Live Follower') follower = create_follower_tournament(name_prefix: 'Ws Live Follower')
configure_sync = source_client.patch("/tournaments/#{source.fetch(:id)}", body: { configure_sync = source_client.patch("/tournaments/#{source.fetch(:id)}", body: {
sync_target_url: "#{follower_base_url}/tournaments/#{follower.fetch(:id)}/sync_state", sync_target_url: follower_sync_url(follower),
sync_auth_token: sync_token sync_auth_token: sync_token
}) })
expect(configure_sync[:status]).to eq(200) expect(configure_sync[:status]).to eq(200)
follower = wait_for_follower_match_count!(follower.fetch(:id), count: source.fetch(:stages).first.fetch(:groups).flat_map { |group| group.fetch(:matches) }.count) follower = wait_for_follower_match_count!(
follower.fetch(:id),
count: source_group_matches(source).count
)
source_match = source.fetch(:stages).first.fetch(:groups).first.fetch(:matches).first source_match = source.fetch(:stages).first.fetch(:groups).first.fetch(:matches).first
follower_match_id = follower_match_for_source!(follower, source_match).fetch(:id) follower_match_id = follower_match_for_source!(follower, source_match).fetch(:id)
@ -48,22 +55,31 @@ RSpec.describe 'Tournament follower sync live websocket HTTP E2E' do
play_match!(match_id: source_match.fetch(:id), first_score: 5, second_score: 2) play_match!(match_id: source_match.fetch(:id), first_score: 5, second_score: 2)
tournament_payload = wait_for_tournament_payload!(tournament_cable, tournament_id: follower.fetch(:id)) do |payload| tournament_payload = wait_for_tournament_payload!(
tournament_cable,
tournament_id: follower.fetch(:id)
) do |payload|
payload.dig('tournament', 'stages').flat_map { |stage| stage.fetch('groups', []) } payload.dig('tournament', 'stages').flat_map { |stage| stage.fetch('groups', []) }
.flat_map { |group| group.fetch('matches', []) } .flat_map { |group| group.fetch('matches', []) }
.any? { |candidate| candidate.fetch('id') == follower_match_id && candidate.fetch('state') == 'finished' } .any? do |candidate|
candidate.fetch('id') == follower_match_id && candidate.fetch('state') == 'finished'
end
end end
matches_payload = wait_for_matches_payload!(matches_cable, match_id: follower_match_id, state: 'finished') matches_payload = wait_for_matches_payload!(matches_cable, match_id: follower_match_id, state: 'finished')
expect(tournament_payload.fetch('tournament')).to eq(json_for_api(fetch_tournament(base_url: follower_base_url, tournament_id: follower.fetch(:id)))) expect(tournament_payload.fetch('tournament')).to(
expect(matches_payload.fetch('matches')).to eq(json_for_api(fetch_matches(base_url: follower_base_url, tournament_id: follower.fetch(:id)))) eq(json_for_api(fetch_tournament(base_url: follower_base_url, tournament_id: follower.fetch(:id))))
)
expect(matches_payload.fetch('matches')).to(
eq(json_for_api(fetch_matches(base_url: follower_base_url, tournament_id: follower.fetch(:id))))
)
ensure ensure
tournament_cable&.close tournament_cable&.close
matches_cable&.close matches_cable&.close
end end
def login_client(base_url:) def login_client(base_url:)
client = TurniereE2E::ApiClient.new(base_url: base_url) client = TurniereE2E::ApiClient.new(base_url:)
response = client.login!(email: owner_email, password: owner_password) response = client.login!(email: owner_email, password: owner_password)
expect(response[:status]).to eq(200) expect(response[:status]).to eq(200)
client client
@ -77,7 +93,7 @@ RSpec.describe 'Tournament follower sync live websocket HTTP E2E' do
group_stage: true, group_stage: true,
playoff_teams_amount: 2, playoff_teams_amount: 2,
teams: 2.times.flat_map do |group_index| teams: 2.times.flat_map do |group_index|
2.times.map do |seed_index| Array.new(2) do |seed_index|
{ {
name: "#{name_prefix.tr(' ', '')}-G#{group_index + 1}-S#{seed_index + 1}", name: "#{name_prefix.tr(' ', '')}-G#{group_index + 1}-S#{seed_index + 1}",
group: group_index group: group_index
@ -86,7 +102,7 @@ RSpec.describe 'Tournament follower sync live websocket HTTP E2E' do
end end
}) })
expect(response[:status]).to eq(201) expect(response[:status]).to eq(201)
fetch_tournament(base_url: base_url, tournament_id: response.dig(:json, :id)) fetch_tournament(base_url:, tournament_id: response.dig(:json, :id))
end end
def create_follower_tournament(name_prefix:) def create_follower_tournament(name_prefix:)
@ -111,7 +127,7 @@ RSpec.describe 'Tournament follower sync live websocket HTTP E2E' do
ordered_scores = match_response.fetch(:json).fetch(:match_scores).sort_by { |score| score.fetch(:id) } ordered_scores = match_response.fetch(:json).fetch(:match_scores).sort_by { |score| score.fetch(:id) }
[first_score, second_score].each_with_index do |points, index| [first_score, second_score].each_with_index do |points, index|
score_update = source_client.patch("/match_scores/#{ordered_scores[index].fetch(:id)}", body: { points: points }) score_update = source_client.patch("/match_scores/#{ordered_scores[index].fetch(:id)}", body: { points: })
expect(score_update[:status]).to eq(200) expect(score_update[:status]).to eq(200)
end end
@ -120,61 +136,75 @@ RSpec.describe 'Tournament follower sync live websocket HTTP E2E' do
end end
def wait_for_follower_match_count!(tournament_id, count:, timeout: 20) def wait_for_follower_match_count!(tournament_id, count:, timeout: 20)
deadline = Time.now + timeout deadline = monotonic_time + timeout
loop do loop do
follower = fetch_tournament(base_url: follower_base_url, tournament_id: tournament_id) follower = fetch_tournament(base_url: follower_base_url, tournament_id:)
matches = follower.fetch(:stages).flat_map do |stage| matches = follower.fetch(:stages).flat_map do |stage|
stage.fetch(:groups, []).flat_map { |group| group.fetch(:matches, []) } + stage.fetch(:matches, []) stage.fetch(:groups, []).flat_map { |group| group.fetch(:matches, []) } + stage.fetch(:matches, [])
end end
return follower if matches.count == count return follower if matches.count == count
raise "follower tournament not synced within #{timeout}s" if Time.now >= deadline raise "follower tournament not synced within #{timeout}s" if monotonic_time >= deadline
sleep 0.5 sleep 0.5
end end
end end
def follower_match_for_source!(follower, source_match) def follower_match_for_source!(follower, source_match)
follower.fetch(:stages).flat_map do |stage| follower_matches = follower.fetch(:stages).flat_map do |stage|
stage.fetch(:groups, []).flat_map { |group| group.fetch(:matches, []) } + stage.fetch(:matches, []) stage.fetch(:groups, []).flat_map { |group| group.fetch(:matches, []) } + stage.fetch(:matches, [])
end.find do |candidate| end
follower_matches.find do |candidate|
candidate.fetch(:position) == source_match.fetch(:position) candidate.fetch(:position) == source_match.fetch(:position)
end || raise('follower match missing') end || raise('follower match missing')
end end
def fetch_tournament(base_url:, tournament_id:) def fetch_tournament(base_url:, tournament_id:)
response = TurniereE2E::ApiClient.new(base_url: base_url).get("/tournaments/#{tournament_id}") response = TurniereE2E::ApiClient.new(base_url:).get("/tournaments/#{tournament_id}")
expect(response[:status]).to eq(200) expect(response[:status]).to eq(200)
response.fetch(:json) response.fetch(:json)
end end
def fetch_matches(base_url:, tournament_id:) def fetch_matches(base_url:, tournament_id:)
response = TurniereE2E::ApiClient.new(base_url: base_url).get("/tournaments/#{tournament_id}/matches") response = TurniereE2E::ApiClient.new(base_url:).get("/tournaments/#{tournament_id}/matches")
expect(response[:status]).to eq(200) expect(response[:status]).to eq(200)
response.fetch(:json) response.fetch(:json)
end end
def wait_for_tournament_payload!(cable_client, tournament_id:, timeout: 20) def wait_for_tournament_payload!(cable_client, tournament_id:, timeout: 20)
deadline = Time.now + timeout deadline = monotonic_time + timeout
loop do loop do
payload = cable_client.wait_for_tournament_payload!(timeout: [deadline - Time.now, 0.1].max) payload = cable_client.wait_for_tournament_payload!(timeout: [deadline - monotonic_time, 0.1].max)
return payload if payload.fetch('tournament_id') == tournament_id && yield(payload) return payload if payload.fetch('tournament_id') == tournament_id && yield(payload)
raise "follower tournament websocket payload not received within #{timeout}s" if Time.now >= deadline raise "follower tournament websocket payload not received within #{timeout}s" if monotonic_time >= deadline
end end
end end
def wait_for_matches_payload!(cable_client, match_id:, state:, timeout: 20) def wait_for_matches_payload!(cable_client, match_id:, state:, timeout: 20)
deadline = Time.now + timeout deadline = monotonic_time + timeout
loop do loop do
payload = cable_client.wait_for_matches_payload!(timeout: [deadline - Time.now, 0.1].max) payload = cable_client.wait_for_matches_payload!(timeout: [deadline - monotonic_time, 0.1].max)
match = payload.fetch('matches').find { |candidate| candidate.fetch('id') == match_id } match = payload.fetch('matches').find { |candidate| candidate.fetch('id') == match_id }
return payload if match&.fetch('state') == state return payload if match&.fetch('state') == state
raise "follower matches websocket payload not received within #{timeout}s" if Time.now >= deadline raise "follower matches websocket payload not received within #{timeout}s" if monotonic_time >= deadline
end end
end end
def follower_sync_url(follower)
"#{follower_base_url}/tournaments/#{follower.fetch(:id)}/sync_state"
end
def source_group_matches(source)
source.fetch(:stages).first.fetch(:groups).flat_map { |group| group.fetch(:matches) }
end
def monotonic_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def json_for_api(value) def json_for_api(value)
JSON.parse(JSON.dump(value)) JSON.parse(JSON.dump(value))
end end

View File

@ -32,15 +32,24 @@ RSpec.describe 'Tournament live websocket HTTP E2E' do
tournament_cable.subscribe_tournament!(tournament_id: tournament.fetch(:id)) tournament_cable.subscribe_tournament!(tournament_id: tournament.fetch(:id))
matches_cable.subscribe_matches!(tournament_id: tournament.fetch(:id)) matches_cable.subscribe_matches!(tournament_id: tournament.fetch(:id))
expect(tournament_cable.wait_for_tournament_payload!.fetch('tournament')).to eq(json_for_api(fetch_tournament(tournament.fetch(:id)))) expect(tournament_cable.wait_for_tournament_payload!.fetch('tournament')).to(
expect(matches_cable.wait_for_matches_payload!.fetch('matches')).to eq(json_for_api(fetch_matches(tournament.fetch(:id)))) eq(json_for_api(fetch_tournament(tournament.fetch(:id))))
)
expect(matches_cable.wait_for_matches_payload!.fetch('matches')).to(
eq(json_for_api(fetch_matches(tournament.fetch(:id))))
)
play_match!(match.fetch(:id), first_score: 3, second_score: 1) play_match!(match.fetch(:id), first_score: 3, second_score: 1)
tournament_payload = wait_for_tournament_payload!(tournament_cable, tournament_id: tournament.fetch(:id)) do |payload| tournament_payload = wait_for_tournament_payload!(
tournament_cable,
tournament_id: tournament.fetch(:id)
) do |payload|
payload.dig('tournament', 'stages').flat_map { |stage| stage.fetch('groups', []) } payload.dig('tournament', 'stages').flat_map { |stage| stage.fetch('groups', []) }
.flat_map { |group| group.fetch('matches', []) } .flat_map { |group| group.fetch('matches', []) }
.any? { |candidate| candidate.fetch('id') == match.fetch(:id) && candidate.fetch('state') == 'finished' } .any? do |candidate|
candidate.fetch('id') == match.fetch(:id) && candidate.fetch('state') == 'finished'
end
end end
expect(tournament_payload.fetch('tournament')).to eq(json_for_api(fetch_tournament(tournament.fetch(:id)))) expect(tournament_payload.fetch('tournament')).to eq(json_for_api(fetch_tournament(tournament.fetch(:id))))
@ -67,7 +76,7 @@ RSpec.describe 'Tournament live websocket HTTP E2E' do
group_stage: true, group_stage: true,
playoff_teams_amount: 2, playoff_teams_amount: 2,
teams: 2.times.flat_map do |group_index| teams: 2.times.flat_map do |group_index|
2.times.map do |seed_index| Array.new(2) do |seed_index|
{ {
name: "#{name_prefix.tr(' ', '')}-G#{group_index + 1}-S#{seed_index + 1}", name: "#{name_prefix.tr(' ', '')}-G#{group_index + 1}-S#{seed_index + 1}",
group: group_index group: group_index
@ -88,7 +97,7 @@ RSpec.describe 'Tournament live websocket HTTP E2E' do
ordered_scores = match_response.fetch(:json).fetch(:match_scores).sort_by { |score| score.fetch(:id) } ordered_scores = match_response.fetch(:json).fetch(:match_scores).sort_by { |score| score.fetch(:id) }
[first_score, second_score].each_with_index do |points, index| [first_score, second_score].each_with_index do |points, index|
score_update = client.patch("/match_scores/#{ordered_scores[index].fetch(:id)}", body: { points: points }) score_update = client.patch("/match_scores/#{ordered_scores[index].fetch(:id)}", body: { points: })
expect(score_update[:status]).to eq(200) expect(score_update[:status]).to eq(200)
end end
@ -109,26 +118,30 @@ RSpec.describe 'Tournament live websocket HTTP E2E' do
end end
def wait_for_tournament_payload!(cable_client, tournament_id:, timeout: 20) def wait_for_tournament_payload!(cable_client, tournament_id:, timeout: 20)
deadline = Time.now + timeout deadline = monotonic_time + timeout
loop do loop do
payload = cable_client.wait_for_tournament_payload!(timeout: [deadline - Time.now, 0.1].max) payload = cable_client.wait_for_tournament_payload!(timeout: [deadline - monotonic_time, 0.1].max)
return payload if payload.fetch('tournament_id') == tournament_id && yield(payload) return payload if payload.fetch('tournament_id') == tournament_id && yield(payload)
raise "tournament websocket payload not received within #{timeout}s" if Time.now >= deadline raise "tournament websocket payload not received within #{timeout}s" if monotonic_time >= deadline
end end
end end
def wait_for_matches_payload!(cable_client, match_id:, state:, timeout: 20) def wait_for_matches_payload!(cable_client, match_id:, state:, timeout: 20)
deadline = Time.now + timeout deadline = monotonic_time + timeout
loop do loop do
payload = cable_client.wait_for_matches_payload!(timeout: [deadline - Time.now, 0.1].max) payload = cable_client.wait_for_matches_payload!(timeout: [deadline - monotonic_time, 0.1].max)
match = payload.fetch('matches').find { |candidate| candidate.fetch('id') == match_id } match = payload.fetch('matches').find { |candidate| candidate.fetch('id') == match_id }
return payload if match&.fetch('state') == state return payload if match&.fetch('state') == state
raise "matches websocket payload not received within #{timeout}s" if Time.now >= deadline raise "matches websocket payload not received within #{timeout}s" if monotonic_time >= deadline
end end
end end
def monotonic_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def json_for_api(value) def json_for_api(value)
JSON.parse(JSON.dump(value)) JSON.parse(JSON.dump(value))
end end