Files
Hunter/scripts/HostedArenaService.server.luau
T
2026-11-29 20:51:32 +05:00

645 lines
24 KiB
Luau

--!strict
local HttpService = game:GetService("HttpService")
local MemoryStoreService = game:GetService("MemoryStoreService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local TeleportService = game:GetService("TeleportService")
local Hosting = require(ReplicatedStorage:WaitForChild("HostedArena") :: ModuleScript)
local Modes = require(ReplicatedStorage:WaitForChild("ArenaModes") :: ModuleScript)
local Rules = require(ReplicatedStorage:WaitForChild("MatchRules") :: ModuleScript)
type RoundOptions = Hosting.RoundOptions
type Session = {
hostId: number, hostName: string, access: "Public" | "Private",
allowed: {[string]: boolean}, startedAt: number, roundOptions: RoundOptions?,
}
type Seat = "Pending" | "Accepted" | "Declined"
type Party = {id: string, host: Player, answers: {[Player]: Seat}, expires: number, roundOptions: RoundOptions}
type Side = Hosting.Side
type Transfer = {destination: string?, side: Side?, attempts: number}
type Listing = Hosting.Listing
type Cursor = {key: string, sortKey: number?}
type Page = {rows: {Listing}, next: Cursor?}
local hosted = Hosting.isReserved()
-- An unpublished place has no MemoryStore namespace. Preview hosting on its existing arena.
local localPreview = RunService:IsStudio() and (game.GameId == 0 or game.PlaceId == 0)
local storesReady, sessionStore, publicStore = pcall(function()
if localPreview then return nil, nil end
return MemoryStoreService:GetHashMap("HunterHostedArenaSessionsV1"),
MemoryStoreService:GetSortedMap("HunterPublicArenasV1")
end)
local sessions = if storesReady then sessionStore else nil
local directory = if storesReady then publicStore else nil
local SESSION_TTL = 240
local DIRECTORY_TTL = 50
local PAGE_SIZE = 24
local remote = Instance.new("RemoteEvent")
remote.Name = "HostedArenaRemote"
remote:SetAttribute("IsHosted", hosted)
remote:SetAttribute("LocalPublicPreview", localPreview)
local previewOwner: Player? = nil
local configuringPreview = false
local parties: {[Player]: Party} = {}
local invitations: {[Player]: Party} = {}
local transfers: {[Player]: Transfer} = {}
local lastAction: {[Player]: number} = {}
local lastCreate: {[Player]: number} = {}
local lastList: {[Player]: number} = {}
local lastDetails: {[Player]: number} = {}
local moreFrom: {[Player]: Cursor} = {}
local firstPage: Page = {rows = {}, next = nil}
local hasFirstPage = false
local listUpdatedAt = -math.huge
local function present(player: Player): boolean
return player.Parent == Players
end
local function inLobby(player: Player): boolean
return present(player) and player:GetAttribute("InArena") ~= true and player:GetAttribute("ArenaTeam") == nil
end
local function send(player: Player, event: string, data: any?)
if present(player) then remote:FireClient(player, event, data) end
end
local function fail(player: Player, message: string)
send(player, "Error", message)
end
local function setPreviewOwner(player: Player?)
previewOwner = player
remote:SetAttribute("LocalPublicOwnerUserId", if player then player.UserId else nil)
end
local function configureRound(options: RoundOptions): boolean
local endpoint = script.Parent:WaitForChild("ArenaRounds"):WaitForChild("HostedArenaConfigure") :: BindableFunction
return endpoint:Invoke(options)
end
local function createLocalPublic(player: Player, options: RoundOptions)
if previewOwner and previewOwner ~= player then
fail(player, "На этом тестовом сервере уже есть публичная арена. Откройте её карточку.")
return
end
if configuringPreview then
fail(player, "Тестовая арена уже готовится.")
return
end
configuringPreview = true
local ok, configured = pcall(configureRound, options)
configuringPreview = false
if not ok or not configured then
fail(player, "Дождитесь, пока тестовая арена освободится.")
return
end
if not inLobby(player) then return end
setPreviewOwner(player)
send(player, "LocalPublicReady")
end
local function transferFailed(player: Player)
if not transfers[player] then return end
transfers[player] = nil
fail(player, "Переход не удался. Попробуйте снова.")
end
local function teleport(group: {Player}, destination: string?, side: Side?): boolean
local options = Instance.new("TeleportOptions")
if destination then options.ReservedServerId = destination else options.ForcePublicServer = true end
if destination and side then options:SetTeleportData({arenaId = destination, team = side}) end
local ok, result = pcall(TeleportService.TeleportAsync, TeleportService, game.PlaceId, group, options)
if not ok then warn("[HostedArena] TeleportAsync failed:", result) end
return ok
end
local function transfer(group: {Player}, destination: string?, side: Side?)
for _, player in group do
local pending = {destination = destination, side = side, attempts = 1}
transfers[player] = pending
send(player, "Transfer", if destination then "Загружаем арену…" else "Возвращаем в общее лобби…")
task.delay(25, function()
if transfers[player] == pending and present(player) then transferFailed(player) end
end)
end
if not teleport(group, destination, side) then
for _, player in group do transferFailed(player) end
end
end
TeleportService.TeleportInitFailed:Connect(function(player, result, _, placeId, options)
local pending = transfers[player]
if not pending or placeId ~= game.PlaceId then return end
if options.ReservedServerId ~= (pending.destination or "") then return end
if pending.attempts >= 2 or (result ~= Enum.TeleportResult.Failure and result ~= Enum.TeleportResult.Flooded) then
transferFailed(player)
return
end
pending.attempts += 1
task.delay(if result == Enum.TeleportResult.Flooded then 3 else 1, function()
if present(player) and transfers[player] == pending and not teleport({player}, pending.destination, pending.side) then
transferFailed(player)
end
end)
end)
local function saveSession(host: Player, destination: string, record: Session): boolean
if not sessions then
warn("[HostedArena] MemoryStore initialization failed:", sessionStore)
return false
end
for attempt = 1, 3 do
if not present(host) then return false end
local ok, issue = pcall(sessions.SetAsync, sessions, destination, record, SESSION_TTL)
if ok then return true end
local reason = string.lower(tostring(issue))
local retryable = string.find(reason, "internal", 1, true) or string.find(reason, "throttl", 1, true)
or string.find(reason, "requestsoverlimit", 1, true) or string.find(reason, "timeout", 1, true)
if not retryable or attempt == 3 then
warn("[HostedArena] Could not register session:", issue)
return false
end
task.wait(2 ^ (attempt - 1))
end
return false
end
local function launch(host: Player, guests: {Player}?, access: "Public" | "Private", options: RoundOptions)
local destination = HttpService:GenerateGUID(false)
local members = {host}
local allowed = {[tostring(host.UserId)] = true}
if guests then
for _, player in guests do
if present(player) then
allowed[tostring(player.UserId)] = true
table.insert(members, player)
end
end
end
for _, player in members do
transfers[player] = {destination = destination, attempts = 1}
if access == "Private" then send(player, "Transfer", "Готовим арену…") end
end
local record: Session = {
hostId = host.UserId, hostName = host.DisplayName, access = access,
allowed = if access == "Private" then allowed else {},
startedAt = workspace:GetServerTimeNow(), roundOptions = options,
}
local saved = saveSession(host, destination, record)
local hostHere = present(host)
for index = #members, 2, -1 do
if not present(members[index]) then table.remove(members, index) end
end
if not saved or not hostHere or (access == "Private" and #members < 2) then
for _, player in members do
transfers[player] = nil
fail(player, if not hostHere then "Создатель вышел с сервера."
elseif not saved then "Сервис арен Roblox временно недоступен. Попробуйте позже."
else "Подтвердившие игроки вышли с сервера.")
end
if saved and sessions then
pcall(sessions.RemoveAsync, sessions, destination)
end
return
end
transfer(members, destination)
end
local function closeParty(party: Party, reason: string?)
parties[party.host] = nil
send(party.host, "PartyClosed", reason)
for player in party.answers do
if invitations[player] == party then
invitations[player] = nil
send(player, "InviteClosed", party.id)
end
end
end
local function updateParty(party: Party, expired: boolean?)
if parties[party.host] ~= party then return end
local accepted: {Player} = {}
local waiting = 0
for player, answer in party.answers do
if not present(player) then continue end
if answer == "Accepted" then table.insert(accepted, player) end
if answer == "Pending" then waiting += 1 end
end
if waiting > 0 and not expired then
send(party.host, "Party", {accepted = #accepted, pending = waiting, expires = party.expires})
return
end
if #accepted == 0 or not inLobby(party.host) then
closeParty(party, if #accepted == 0 then "Никто не подтвердил приглашение." else "Создатель покинул лобби.")
return
end
closeParty(party)
launch(party.host, accepted, "Private", party.roundOptions)
end
local function invite(host: Player, selection: unknown, options: RoundOptions)
if typeof(selection) ~= "table" then return end
local answers: {[Player]: Seat} = {}
local checked = 0
for _, userId in selection do
checked += 1
if checked >= Hosting.MaxPlayers or typeof(userId) ~= "number" or userId % 1 ~= 0 or math.abs(userId) >= 2^53 then
fail(host, "Выберите до 19 игроков.")
return
end
local player = Players:GetPlayerByUserId(userId)
if player == host or not player or not present(player) or invitations[player] or parties[player] or transfers[player] then
fail(host, "Кто-то из выбранных уже недоступен. Проверьте список игроков.")
return
end
answers[player] = "Pending"
end
if not next(answers) then
fail(host, "Выберите хотя бы одного игрока.")
return
end
local party = {id = HttpService:GenerateGUID(false), host = host, answers = answers, roundOptions = options,
expires = workspace:GetServerTimeNow() + Hosting.InviteSeconds}
parties[host] = party
local payload = {id = party.id, hostId = host.UserId, hostName = host.DisplayName,
hostUsername = host.Name, expires = party.expires}
for player in answers do
invitations[player] = party
send(player, "Invite", payload)
end
updateParty(party)
task.delay(Hosting.InviteSeconds, updateParty, party, true)
end
local function answer(player: Player, id: unknown, accepted: unknown)
local party = invitations[player]
if not party or id ~= party.id or typeof(accepted) ~= "boolean" or workspace:GetServerTimeNow() >= party.expires then return end
local previous = party.answers[player]
if previous ~= "Pending" and (previous ~= "Accepted" or accepted) then return end
party.answers[player] = if accepted then "Accepted" else "Declined"
if accepted then
send(player, "Accepted", party.id)
else
invitations[player] = nil
send(player, "InviteClosed", party.id)
end
updateParty(party)
end
local function readPage(cursor: Cursor?): Page?
if not directory then return {rows = {}, next = nil} end
local ok, entries = pcall(directory.GetRangeAsync, directory, Enum.SortDirection.Descending, PAGE_SIZE, nil, cursor)
if not ok then return nil end
local rows: {Listing} = {}
for _, entry in entries do
local row = entry.value
table.insert(rows, {id = entry.key, hostId = row.hostId, hostName = row.hostName, players = row.players,
ruleset = Rules.get(row.ruleset).id})
end
local last = entries[PAGE_SIZE]
return {rows = rows, next = if last then {key = last.key, sortKey = last.sortKey} else nil}
end
local function listPublic(player: Player, now: number, more: boolean)
if now - (lastList[player] or -math.huge) < 1 then return end
lastList[player] = now
local page: Page = firstPage
if more then
local cursor = moreFrom[player]
if not cursor then return end
local nextPage = readPage(cursor)
if not nextPage then
send(player, "ListUnavailable")
return
end
page = nextPage
elseif now - listUpdatedAt >= 8 then
listUpdatedAt = now
local refreshed = readPage(nil)
if refreshed then
firstPage, page, hasFirstPage = refreshed, refreshed, true
elseif not hasFirstPage then
send(player, "ListUnavailable")
return
end
end
moreFrom[player] = page.next
send(player, "PublicList", {rows = page.rows, append = more, more = page.next ~= nil})
end
local function publicDetails(player: Player, id: unknown, now: number)
if typeof(id) ~= "string" or #id ~= 36 or now - (lastDetails[player] or -math.huge) < 1 then return end
lastDetails[player] = now
if not directory then send(player, "DetailsUnavailable", id) return end
local ok, row = pcall(directory.GetAsync, directory, id)
if not ok or not row then
send(player, "DetailsUnavailable", id)
return
end
local detail: Hosting.Details = {id = id, blue = row.blue or {}, orange = row.orange or {}, players = row.players}
send(player, "PublicDetails", detail)
end
local function joinPublic(player: Player, id: unknown, preference: unknown)
if typeof(id) ~= "string" or #id ~= 36 or not directory then return end
if preference ~= nil and preference ~= "Blue" and preference ~= "Orange" then return end
transfers[player] = {destination = id, attempts = 1}
local ok, row = pcall(directory.GetAsync, directory, id)
if not inLobby(player) then transfers[player] = nil return end
if not ok or not row or row.players >= Hosting.MaxPlayers then
transfers[player] = nil
fail(player, "Арена закрылась или уже заполнена.")
return
end
if preference then
local blue, orange = #(row.blue or {}), #(row.orange or {})
local issue = if preference == "Blue" then Hosting.teamJoinError(blue, orange) else Hosting.teamJoinError(orange, blue)
if issue then
transfers[player] = nil
fail(player, if issue == "Full" then "В этой команде нет мест." else "Составы изменились. Выберите другую команду.")
return
end
end
transfer({player}, id, preference)
end
remote.OnServerEvent:Connect(function(player: Player, action: unknown, value: unknown, extra: unknown)
if typeof(action) ~= "string" then return end
local now = workspace:GetServerTimeNow()
if not hosted and inLobby(player) then
if action == "PublicList" or action == "MorePublic" then listPublic(player, now, action == "MorePublic") return end
if action == "PublicDetails" then publicDetails(player, value, now) return end
end
if now - (lastAction[player] or -math.huge) < .16 then return end
lastAction[player] = now
if transfers[player] then return end
if hosted then
if action == "Exit" and inLobby(player) then transfer({player}) end
return
end
if action == "Answer" then answer(player, value, extra) return end
if action == "Cancel" then
local party = parties[player]
if party then closeParty(party, "Приглашения отменены.") end
return
end
if not inLobby(player) then return end
if parties[player] or invitations[player] then
fail(player, "Сначала завершите текущее приглашение.")
return
end
if action == "JoinPublic" then joinPublic(player, value, extra) return end
if action ~= "CreatePublic" and action ~= "InvitePrivate" then return end
local options = Hosting.readRoundOptions(if action == "CreatePublic" then value else extra)
if not options then
fail(player, "Проверьте выбранный режим и настройки арены.")
return
end
if now - (lastCreate[player] or -math.huge) < 3 then
fail(player, "Подождите несколько секунд перед повторной попыткой.")
return
end
lastCreate[player] = now
if localPreview then
if action == "CreatePublic" then createLocalPublic(player, options)
else fail(player, "Для приватной арены нужен плейс, сохранённый в Roblox.") end
return
end
if action == "CreatePublic" then launch(player, nil, "Public", options) else invite(player, value, options) end
end)
local function releasePreviewSeat(leaving: Player)
if not previewOwner then return end
local successor: Player? = nil
for _, other in Players:GetPlayers() do
if other ~= leaving and other:GetAttribute("ArenaTeam") ~= nil then
if other == previewOwner then return end
successor = successor or other
end
end
setPreviewOwner(successor)
end
if localPreview then
local function watchPreviewSeat(player: Player)
local hadSeat = player:GetAttribute("ArenaTeam") ~= nil
player:GetAttributeChangedSignal("ArenaTeam"):Connect(function()
local hasSeat = player:GetAttribute("ArenaTeam") ~= nil
if hadSeat and not hasSeat then releasePreviewSeat(player) end
hadSeat = hasSeat
end)
end
Players.PlayerAdded:Connect(watchPreviewSeat)
for _, player in Players:GetPlayers() do watchPreviewSeat(player) end
end
Players.PlayerRemoving:Connect(function(player)
if previewOwner == player or player:GetAttribute("ArenaTeam") ~= nil then
releasePreviewSeat(player)
end
lastAction[player], lastCreate[player], lastList[player], transfers[player] = nil, nil, nil, nil
lastDetails[player], moreFrom[player] = nil, nil
local sent = parties[player]
if sent then closeParty(sent, "Создатель вышел с сервера.") end
local received = invitations[player]
if received then
invitations[player], received.answers[player] = nil, nil
updateParty(received)
end
end)
if hosted then
local rounds = script.Parent:WaitForChild("ArenaRounds")
local admission = rounds:WaitForChild("HostedArenaAdmission") :: BindableEvent
local exit = rounds:WaitForChild("HostedArenaExit") :: BindableEvent
exit.Event:Connect(function(player: Player)
if inLobby(player) and not transfers[player] then transfer({player}) end
end)
local match = ReplicatedStorage:WaitForChild("ArenaRound"):WaitForChild("Procedural")
local reservationId = game.PrivateServerId
local session: Session? = nil
local loaded = false
local closing, removed = false, false
local writing, pending = false, false
local admitted: {[Player]: number} = {}
local nextArrival = 0
local ownerDeparted = false
local ownerGraceUntil = workspace:GetServerTimeNow() + 20
local lastSessionWrite, savedOwner = -math.huge, nil :: number?
local function showOwner(record: Session)
remote:SetAttribute("OwnerUserId", record.hostId)
remote:SetAttribute("OwnerName", record.hostName)
end
local function chooseSuccessor(record: Session, now: number)
if not ownerDeparted and now < ownerGraceUntil then return end
local successor: Player? = nil
local oldest = math.huge
for player, order in admitted do
if player.UserId == record.hostId then return end
if order < oldest then successor, oldest = player, order end
end
if successor then
record.hostId, record.hostName = successor.UserId, successor.DisplayName
ownerDeparted = false
showOwner(record)
end
end
local function removeSession(record: Session)
local registryRemoved = sessions == nil
local listingRemoved = directory == nil or record.access ~= "Public"
for attempt = 1, 3 do
if not registryRemoved and sessions then registryRemoved = pcall(sessions.RemoveAsync, sessions, reservationId) end
if not listingRemoved and directory then listingRemoved = pcall(directory.RemoveAsync, directory, reservationId) end
if registryRemoved and listingRemoved then break end
if attempt < 3 then task.wait(attempt) end
end
removed = true
end
-- The same writer publishes and retires the session, so a pending refresh cannot recreate a closed entry.
local function sync()
local record = session
if writing or removed or not record then return end
writing = true
repeat
pending = false
if closing then
removeSession(record)
break
end
local now = workspace:GetServerTimeNow()
chooseSuccessor(record, now)
if sessions and (savedOwner ~= record.hostId or now - lastSessionWrite >= 90) then
local snapshot = table.clone(record)
if pcall(sessions.SetAsync, sessions, reservationId, snapshot, SESSION_TTL) then
lastSessionWrite, savedOwner = now, snapshot.hostId
end
end
if not closing and record.access == "Public" and directory and next(admitted) then
local count = 0
local blue: {Hosting.Member}, orange: {Hosting.Member} = {}, {}
for player in admitted do
count += 1
local side = player:GetAttribute("ArenaTeam")
if side == "Blue" or side == "Orange" then
table.insert(if side == "Blue" then blue else orange, {userId = player.UserId, displayName = player.DisplayName})
end
end
pcall(directory.SetAsync, directory, reservationId,
{hostId = record.hostId, hostName = record.hostName, players = count,
blue = blue, orange = orange, ruleset = Rules.get(match:GetAttribute("Ruleset")).id},
DIRECTORY_TTL, record.startedAt or now)
end
until not pending
writing = false
end
local function scheduleSync()
pending = true
task.spawn(sync)
end
local function allowed(record: Session, player: Player): boolean
return record.access == "Public" or record.allowed[tostring(player.UserId)] == true
end
local function closeIfEmpty(leaving: Player?)
local record = session
if closing or not record or nextArrival == 0 or next(admitted) then return end
for _, player in Players:GetPlayers() do
if player ~= leaving and allowed(record, player) and not player:GetAttribute("HostedArenaFull") then return end
end
closing = true
scheduleSync()
end
local function authorize(player: Player)
while not loaded and present(player) do task.wait(.1) end
if not present(player) or admitted[player] then return end
local record = session
if not record or closing then
player:Kick("Эта арена больше недоступна.")
return
end
if not allowed(record, player) then
player:Kick("Эта арена доступна только участникам с подтверждённым приглашением.")
return
end
local count = 0
for _ in admitted do count += 1 end
if count >= Hosting.MaxPlayers then
player:SetAttribute("HostedArenaFull", true)
return
end
nextArrival += 1
admitted[player] = nextArrival
local side: Side? = nil
if record.access == "Public" then
-- The preference grants no admission or team rights. The destination checks its own roster.
local data = player:GetJoinData()
local payload = data.TeleportData
if data.SourcePlaceId == game.PlaceId and data.SourceGameId == game.GameId
and typeof(payload) == "table" and payload.arenaId == reservationId
and (payload.team == "Blue" or payload.team == "Orange") then
side = payload.team
end
end
admission:Fire(player, side)
scheduleSync()
end
Players.PlayerAdded:Connect(authorize)
Players.PlayerRemoving:Connect(function(player)
admitted[player] = nil
local record = session
if not record then return end
if player.UserId == record.hostId then ownerDeparted = true end
closeIfEmpty(player)
if not closing then scheduleSync() end
end)
Players.ChildRemoved:Connect(function(child)
if child:IsA("Player") then closeIfEmpty(nil) end
end)
for _, player in Players:GetPlayers() do task.spawn(authorize, player) end
game:BindToClose(function()
if not session or nextArrival == 0 or removed then return end
closing = true
pending = true
sync()
while writing do task.wait() end
end)
task.spawn(function()
if not sessions then loaded = true return end
for attempt = 1, 3 do
local ok, record = pcall(sessions.GetAsync, sessions, reservationId)
if ok and record then session = record break end
if attempt < 3 then task.wait(1) end
end
local record = session
if record then
local options = Hosting.readRoundOptions(record.roundOptions)
if not options or not configureRound(options) then
warn("[HostedArena] Could not configure hosted rounds")
session, record = nil, nil
end
end
loaded = true
if not record then return end
savedOwner = record.hostId
showOwner(record)
while not closing do
task.wait(16)
if not closing then scheduleSync() end
end
end)
end
remote.Parent = ReplicatedStorage