Skip to content

Commit

Permalink
Fix some code style issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Gatsik committed Sep 21, 2021
1 parent 5cb90fa commit 9648149
Show file tree
Hide file tree
Showing 47 changed files with 168 additions and 102 deletions.
2 changes: 1 addition & 1 deletion license.rtf
Original file line number Diff line number Diff line change
Expand Up @@ -676,4 +676,4 @@ Public License instead of this License. But first, please read\par
<http://www.gnu.org/philosophy/why-not-lgpl.html>.\par
\par
}
1 change: 1 addition & 0 deletions server/api/api_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class SessionManager:
"""
Garantor for API access
"""

def __init__(self):
self.session = None # Instance of session

Expand Down
5 changes: 5 additions & 0 deletions server/broadcast_service.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import TYPE_CHECKING

from aio_pika import DeliveryMode

from .config import config
Expand All @@ -9,6 +11,9 @@
from .player_service import PlayerService
from .timing import LazyIntervalTimer

if TYPE_CHECKING:
from server import ServerInstance


@with_logger
class BroadcastService(Service):
Expand Down
3 changes: 3 additions & 0 deletions server/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class ClientError(Exception):
If recoverable is False, it is expected that the connection be terminated
immediately.
"""

def __init__(self, message, recoverable=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.message = message
Expand All @@ -24,6 +25,7 @@ class BanError(Exception):
"""
Signals that an operation could not be completed because the user is banned.
"""

def __init__(self, ban_expiry, ban_reason, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ban_expiry = ban_expiry
Expand All @@ -50,6 +52,7 @@ class AuthenticationError(Exception):
"""
The operation failed to authenticate.
"""

def __init__(self, message, method, *args, **kwargs):
super().__init__(*args, **kwargs)
self.message = message
Expand Down
1 change: 1 addition & 0 deletions server/game_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class GameService(Service):
"""
Utility class for maintaining lifecycle of games
"""

def __init__(
self,
database: FAFDatabase,
Expand Down
44 changes: 22 additions & 22 deletions server/gameconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ async def handle_game_state(self, state: str):
await self.on_connection_lost()
self._mark_dirty()

async def handle_game_ended(self, *args: List[Any]):
async def handle_game_ended(self, *args: List[Any]):
"""
Signals that the simulation has ended.
"""
Expand Down Expand Up @@ -616,25 +616,25 @@ def __str__(self):


COMMAND_HANDLERS = {
"Desync": GameConnection.handle_desync,
"GameState": GameConnection.handle_game_state,
"GameOption": GameConnection.handle_game_option,
"GameMods": GameConnection.handle_game_mods,
"PlayerOption": GameConnection.handle_player_option,
"AIOption": GameConnection.handle_ai_option,
"ClearSlot": GameConnection.handle_clear_slot,
"GameResult": GameConnection.handle_game_result,
"OperationComplete": GameConnection.handle_operation_complete,
"JsonStats": GameConnection.handle_json_stats,
"EnforceRating": GameConnection.handle_enforce_rating,
"TeamkillReport": GameConnection.handle_teamkill_report,
"TeamkillHappened": GameConnection.handle_teamkill_happened,
"GameEnded": GameConnection.handle_game_ended,
"Rehost": GameConnection.handle_rehost,
"Bottleneck": GameConnection.handle_bottleneck,
"BottleneckCleared": GameConnection.handle_bottleneck_cleared,
"Disconnected": GameConnection.handle_disconnected,
"IceMsg": GameConnection.handle_ice_message,
"Chat": GameConnection.handle_chat,
"GameFull": GameConnection.handle_game_full
"Desync": GameConnection.handle_desync,
"GameState": GameConnection.handle_game_state,
"GameOption": GameConnection.handle_game_option,
"GameMods": GameConnection.handle_game_mods,
"PlayerOption": GameConnection.handle_player_option,
"AIOption": GameConnection.handle_ai_option,
"ClearSlot": GameConnection.handle_clear_slot,
"GameResult": GameConnection.handle_game_result,
"OperationComplete": GameConnection.handle_operation_complete,
"JsonStats": GameConnection.handle_json_stats,
"EnforceRating": GameConnection.handle_enforce_rating,
"TeamkillReport": GameConnection.handle_teamkill_report,
"TeamkillHappened": GameConnection.handle_teamkill_happened,
"GameEnded": GameConnection.handle_game_ended,
"Rehost": GameConnection.handle_rehost,
"Bottleneck": GameConnection.handle_bottleneck,
"BottleneckCleared": GameConnection.handle_bottleneck_cleared,
"Disconnected": GameConnection.handle_disconnected,
"IceMsg": GameConnection.handle_ice_message,
"Chat": GameConnection.handle_chat,
"GameFull": GameConnection.handle_game_full
}
2 changes: 0 additions & 2 deletions server/games/coop.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import asyncio

from .game import Game
from .typedefs import FA, GameType, InitMode, ValidityState, Victory

Expand Down
1 change: 0 additions & 1 deletion server/games/custom_game.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import asyncio
import time

from server.decorators import with_logger
Expand Down
16 changes: 15 additions & 1 deletion server/games/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,17 @@
import logging
import time
from collections import defaultdict
from typing import Any, Dict, FrozenSet, Iterable, List, Optional, Set, Tuple
from typing import (
TYPE_CHECKING,
Any,
Dict,
FrozenSet,
Iterable,
List,
Optional,
Set,
Tuple
)

import pymysql
from sqlalchemy import and_, bindparam
Expand Down Expand Up @@ -43,6 +53,10 @@
VisibilityState
)

if TYPE_CHECKING:
from server import GameConnection, GameService, GameStatsService
from server.db import FAFDatabase


class GameError(Exception):
pass
Expand Down
1 change: 1 addition & 0 deletions server/ice_servers/nts.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class TwilioNTS:
Creates new twilio NTS tokens
"""

def __init__(self, sid=None, token=None):
if sid is None:
sid = config.TWILIO_ACCOUNT_SID # pragma: no cover
Expand Down
6 changes: 5 additions & 1 deletion server/ladder_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import random
import re
from collections import defaultdict
from typing import Dict, List, Optional, Set, Tuple
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple

import aiocron
from sqlalchemy import and_, func, select, text, true
Expand Down Expand Up @@ -37,13 +37,17 @@
from .players import Player, PlayerState
from .types import GameLaunchOptions, Map, NeroxisGeneratedMap

if TYPE_CHECKING:
from .lobbyconnection import LobbyConnection


@with_logger
class LadderService(Service):
"""
Service responsible for managing the 1v1 ladder. Does matchmaking, updates
statistics, and launches the games.
"""

def __init__(
self,
database: FAFDatabase,
Expand Down
5 changes: 3 additions & 2 deletions server/lobbyconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
CoopGame,
CustomGame,
FeaturedModType,
Game,
GameConnectionState,
GameState,
InitMode,
Expand Down Expand Up @@ -1065,7 +1066,7 @@ async def command_modvault(self, message):
downloads=downloads, date=int(date.timestamp()), uid=uid, name=name, version=version, author=author,
ui=ui)
await self.send(out)
except:
except BaseException:
self._logger.error(f"Error handling table_mod row (uid: {uid})", exc_info=True)

elif type == "like":
Expand All @@ -1091,7 +1092,7 @@ async def command_modvault(self, message):
canLike = False
else:
likers.append(self.player.id)
except:
except BaseException:
likers = []

# TODO: Avoid sending all the mod info in the world just because we liked it?
Expand Down
2 changes: 1 addition & 1 deletion server/matchmaker/algorithm/bucket_teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def find(
teams, searches_without_team = self._find_teams(searches, team_size)

matchmaker1v1 = StableMarriageMatchmaker()
matches, unmatched_searches = matchmaker1v1.find(teams, 1)
matches, unmatched_searches = matchmaker1v1.find(teams, 1)

unmatched_searches.extend(searches_without_team)
return matches, unmatched_searches
Expand Down
2 changes: 2 additions & 0 deletions server/matchmaker/algorithm/stable_marriage.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

WeightedGraph = Dict[Search, List[Tuple[Search, float]]]


class StableMarriage(MatchmakingPolicy1v1):
def find(self, ranks: WeightedGraph) -> Dict[Search, Search]:
"""Perform the stable matching algorithm until a maximal stable matching
Expand Down Expand Up @@ -78,6 +79,7 @@ class StableMarriageMatchmaker(Matchmaker):
Runs stable marriage to produce a list of matches
and afterwards adds random matchups for previously unmatched new players.
"""

def find(
self, searches: Iterable[Search], team_size: int
) -> Tuple[List[Match], List[Search]]:
Expand Down
3 changes: 2 additions & 1 deletion server/matchmaker/algorithm/team_matchmaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class TeamMatchMaker(Matchmaker):
8. pick the first game from the game list and remove all other games that contain the same players
9. repeat 8. until the list is empty
"""

def find(self, searches: Iterable[Search], team_size: int) -> Tuple[List[Match], List[Search]]:
if not searches:
return [], []
Expand Down Expand Up @@ -113,7 +114,7 @@ def pick_neighboring_players(searches: List[Search], index: int, team_size: int)
# We need to do this in two steps to ensure that index = 0 gives an empty iterator
lower = searches[:index]
lower = iter(lower[::-1])
higher = iter(searches[index+1:])
higher = iter(searches[index + 1:])
pick_lower = True
candidate = searches[index]
participants = [candidate]
Expand Down
14 changes: 13 additions & 1 deletion server/matchmaker/matchmaker_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@
from collections import OrderedDict
from concurrent.futures import CancelledError
from datetime import datetime, timezone
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple
)

import server.metrics as metrics

Expand All @@ -15,6 +24,9 @@
from .pop_timer import PopTimer
from .search import Match, Search

if TYPE_CHECKING:
from server import GameService

MatchFoundCallback = Callable[[Search, Search, "MatchmakerQueue"], Any]


Expand Down
6 changes: 5 additions & 1 deletion server/matchmaker/pop_timer.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import asyncio
from collections import deque
from time import time
from typing import Deque
from typing import TYPE_CHECKING, Deque

import server.metrics as metrics

from ..config import config
from ..decorators import with_logger

if TYPE_CHECKING:
from .matchmaker_queue import MatchmakerQueue


@with_logger
class PopTimer(object):
Expand All @@ -25,6 +28,7 @@ class PopTimer(object):
The player queue rate is based on a moving average over the last few pops.
The exact size can be set in config.
"""

def __init__(self, queue: "MatchmakerQueue"):
self.queue = queue
# Set up deque's for calculating a moving average
Expand Down
1 change: 1 addition & 0 deletions server/message_queue_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class MessageQueueService(Service):
Service handling connection to the message queue
and providing an interface to publish messages.
"""

def __init__(self) -> None:
self._logger.debug("Message queue service created.")
self._connection = None
Expand Down
5 changes: 4 additions & 1 deletion server/party_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Manages interactions between players and parties
"""

from typing import Dict, List, Set
from typing import TYPE_CHECKING, Dict, List, Set

from .core import Service
from .decorators import with_logger
Expand All @@ -13,6 +13,9 @@
from .team_matchmaker.player_party import PlayerParty
from .timing import at_interval

if TYPE_CHECKING:
from .lobbyconnection import LobbyConnection


@with_logger
class PartyService(Service):
Expand Down
5 changes: 4 additions & 1 deletion server/player_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""

import asyncio
from typing import Optional, Set, ValuesView
from typing import TYPE_CHECKING, Optional, Set, ValuesView

import aiocron
from sqlalchemy import and_, select
Expand Down Expand Up @@ -32,6 +32,9 @@
user_group_assignment
)

if TYPE_CHECKING:
from .lobbyconnection import LobbyConnection


@with_logger
class PlayerService(Service):
Expand Down
5 changes: 4 additions & 1 deletion server/players.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
from collections import defaultdict
from contextlib import suppress
from enum import Enum, unique
from typing import Dict, Optional, Union
from typing import TYPE_CHECKING, Dict, Optional, Union

from .factions import Faction
from .protocol import DisconnectedError
from .rating import Leaderboard, PlayerRatings, RatingType
from .weakattr import WeakAttribute

if TYPE_CHECKING:
from .lobbyconnection import LobbyConnection


@unique
class PlayerState(Enum):
Expand Down
1 change: 1 addition & 0 deletions server/rating.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ class InclusiveRange():
assert -1 not in InclusiveRange(0, 10)
assert 11 not in InclusiveRange(0, 10)
"""

def __init__(self, lo: Optional[float] = None, hi: Optional[float] = None):
self.lo = lo
self.hi = hi
Expand Down
Loading

0 comments on commit 9648149

Please sign in to comment.