Skip to content

Cleanup returns - #7

Merged
Maho-Yoshino merged 95 commits into
mainfrom
cleanup-returns
Nov 21, 2026
Merged

Maho-Yoshino merged 95 commits into
mainfrom
cleanup-returns

Conversation

@Maho-Yoshino

Copy link
Copy Markdown
Member

Adds a few rudimentary tests using pytest (will get expanded upon in the future)
Clears up a lot of the endpoints' return formats, removes unusable/worthless return data, returns a lot less (good for both bandwidth and memory)
Adds automated tests using GitHub Actions, including automatic linting using ruff and running pytest
Upgraded fastapi from 0.136.1 to 0.162.0 (and upgraded the corresponding code that prevented this beforehand)
Reordered some marketplace endpoints
Cleaned up marketplace backend code
Added endpoints for viewing marketplace orders and cancelling them
Improved upon the dictUtil (previously KeyMod) system, which is now async
Moved the app from app/ to src/ to better fit the code, as this is no app
Added forum posts lookup for planned battle rating changes posts, which is now included in the news endpoints
Added a caching module which is to be used in the future (currently used by the replays and news modules)
Fixed /v1/clans/sqb/current throwing an error when it wasn't called during an open bracket
Added documentation to the cln_get_user_open_orders action
Changed the network manager code to also parse the contents
Changed some middleware configs, hopefully I didn't break the cloudflare integration

This better fits the whole project's scope, and it is a more standardized name
Now it is less monolithic in design, with separate classes for different actions
Removed the part, which stores the latest IDs in an external JSON file

This code used to be part of [PECK Bot](https://github.com/Order-Of-The-Birb/peck-bot), however the API doesn't require any persistent check for already-sent data

Added forum parsing
Implemented parralel fetching to speed it up
Restructured the code
Got tired of writing caches manually
Also added new functionality while i was at it
Now websockets get hidden properly
This bugfix allowed us to raise the FastAPI version from 0.136.1 to 0.162.0
more to come in the future
Automatic linting and pytest running should now work in theory
Ruff one didnt work because i was stupid
Websockets are back again

Network.request had return_type at the wrong place, so it raised an error
@MrMindBlow
MrMindBlow requested an adaptive review from Copilot November 19, 2026 17:24

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@MrMindBlow

Copy link
Copy Markdown
Member

fucking clanker... anyway @Maho-Yoshino review the requests bruh and correct the code so we can ship this

@MrMindBlow MrMindBlow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please address the startup and manual login failures before merging 32870f1. Repeated HTTP 429s can prevent the API from starting, and /v1/answer-2fa cannot complete an active manual challenge. I also confirmed that a 0.57 GJN buy order still produces 5699 backend units. The eight inline comments cover these issues and the remaining inventory, localization, routing, parser, and CI findings.

Ruff and pytest passed on GitHub. I verified the price calculation locally and traced the other findings in source. Live Gaijin behavior remains unverified.

Comment thread src/utils/connection/network.py Resolved
Comment thread src/api/v1/auth/__init__.py Resolved
Comment thread src/api/v1/marketplace/backend.py Resolved
Comment thread src/api/v1/marketplace/__init__.py Resolved
Comment thread src/api/v1/units/__init__.py Resolved
Comment thread src/api/v1/users/__init__.py Resolved
Comment thread src/utils/vehicleParser/__init__.py Resolved
Comment thread .github/workflows/linter.yaml Resolved

@MrMindBlow MrMindBlow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct the buy price calculation and the email login procedure before merge. I checked the price calculation for commit e12337ba. A buy order for 0.57 GJN sends 5699 units. The correct value is 5700. The email login procedure can discard a valid code while it waits for a device response.

The ten line comments give the findings and the requested changes. Ruff and Pytest passed on GitHub. I reviewed the source code and checked the price calculation locally. I did not test the API with a Gaijin account.

Comment thread src/api/v1/marketplace/__init__.py Resolved
Comment thread src/utils/auth.py Resolved
Comment thread src/utils/replayParser/__init__.py Resolved
Comment thread src/api/v1/units/__init__.py Resolved
Comment thread src/utils/news.py Resolved
Comment thread src/utils/connection/network.py Resolved
Comment thread src/main.py Resolved
Comment thread src/api/v1/marketplace/backend.py Resolved
Comment thread src/utils/connection/__init__.py Resolved
Comment thread tests/helpers.py Resolved

@MrMindBlow MrMindBlow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 0.57 GJN buy order now converts to 5700 backend units, and the replay download has a single GET retry loop. I’m requesting changes because the email 2FA completion path needs a credential check and cancelling a server-account Gaijin Pass challenge can leave startup waiting indefinitely. The inline comments also cover upstream rate limits, trusted proxies, and vehicle-data refresh.

I reviewed f7808f35 in source. Both GitHub checks passed. I did not exercise the live Gaijin endpoints.

Comment thread src/utils/auth.py Resolved
Comment thread src/utils/auth.py Resolved
Comment thread src/utils/auth.py Resolved
Comment thread src/main.py Resolved
Comment thread src/api/v1/units/__init__.py Resolved
Comment thread src/utils/vehicleParser/shared.py Resolved
Comment thread src/utils/vehicleParser/shared.py Resolved

@MrMindBlow MrMindBlow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pending-login password check and trusted-proxy changes address the earlier findings. Two authentication issues still block approval. A user who follows the Gaijin Pass prompt can start a second challenge after approving the first, and an upstream 429 during token refresh can abort application startup when stored accounts are refreshed. The inline comments identify the affected paths and the changes needed.

Ruff and Pytest passed on GitHub. I traced the authentication and inventory flows in source and checked the news examples against the public War Thunder site. I did not exercise account-backed Gaijin endpoints.

Comment thread src/utils/auth.py Resolved
Comment thread src/utils/auth.py
}
) as r:
content = await Network.handle_response(r)
content = await Network.handle_response(r, Network.ReturnType.JSON)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handle upstream rate limits during token refresh. Entry.refresh() still uses session.post() directly. On a 429, handle_response() raises ClientResponseError, so /v1/refresh-token returns 500. The same exception escapes the startup call to users_auth._refresh() if any stored account hits that limit. Return 429 to an explicit refresh caller and let the background pass defer that account and continue with the others.

Comment thread src/utils/auth.py Outdated
await wait_for(e.login.wait(), timeout=60)
except TimeoutError:
raise HTTPException(status.HTTP_408_REQUEST_TIMEOUT, "2FA timed out")
await wait_for(e.login.wait(), timeout = 60)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deliver a failed 2FA exchange to the waiting request. If the final Network.post() fails after an email code has been submitted, the background task exits before entry.login.set() or cleanup. /answer-2fa waits the full 60 seconds and reports a timeout, and subsequent attempts find the same failed challenge. Propagate the task’s terminal error to the verified caller and clear that challenge so a fresh login can proceed.

Comment thread src/utils/auth.py Outdated
try:
async with Network.get(f"https://auth.gaijinent.com/api/auth/requestTwoStep?requestId={data['requestId']}&userId={data['userId']}", timeout = 60, session = session) as r:
data = r
except (HTTPException, ClientResponseError) as e:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retry a disconnected Gaijin Pass poll. gaijin_api_endpoints.md records that Gaijin can close an unanswered requestTwoStep connection. A socket disconnect or the 60-second timeout falls through to except Exception, which removes the challenge on the first attempt. Include ServerDisconnectedError and TimeoutError in the bounded recovery path so it can obtain a fresh request ID.

Comment thread src/utils/auth.py Outdated
await entry.provided.wait()
data = await login(self.__EMAIL, self.__PASS)
await entry.await_task
data = entry.login_data

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validate the server account’s 2FA result before reading tokens. A rejected code can complete entry.await_task normally with status="2STEPERROR", as the wrong_code.json fixture shows. Reading data["jwt"] then raises KeyError during startup and hides Gaijin’s reason. Apply the same status checks used by the user-login path before reading the token fields.

Comment thread src/api/v1/auth/__init__.py Outdated
# TODO: Implement. Due to the nature of the 2FA system, it is hard to implement
token, uidHint = await users_auth.login(email, password)

return JSONResponse({

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Return the user ID type declared by /answer-2fa. The successful 2FA fixture supplies user_id as a string, and UserAuth.login passes it through unchanged. Returning JSONResponse bypasses FastAPI’s LoginResponse validation, so clients receive a JSON string where the schema promises an integer. Return the response model or a plain dict and let FastAPI serialize it. The same applies to /login.

Comment thread src/api/v1/marketplace/backend.py Outdated

return cls(
LOGIN = user,
commodity = assetData.get("commodity"),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Give inventory items a valid default for commodity. When GetAssetClassInfo omits this flag, .get("commodity") produces None. The new inventory response model requires a bool, so a single such asset makes the entire inventory request fail validation. Use the same False default that MarketItem.from_assetdata already uses for this payload.

Comment thread src/utils/news.py Outdated
async def fetchForumIDs(self) -> tuple[int, ...]:
"""Gets the latest "planned battle rating changes" post's ID"""
async with Network.get(
"https://forum.warthunder.com/tag/br-changes",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Order forum announcements by publication date. The tag page sorts by activity. It currently puts an October 2025 topic above the October 2026 planned changes because the older discussion received a later reply. fetchForum() picks the first eligible row, and the WebSocket poll can announce an old topic again when a reply moves it above the saved ID. Request descending creation order before selecting the first topic or advancing the cursor. Forum listing · Original announcement

Comment thread src/utils/news.py Outdated
def from_json(cls, data:dict[str, Any]):
tags = set(data.get("tags", []))
title:str = data["title"]
for tag in re.finditer(r"\[([A-z ]+)\]", title, re.IGNORECASE):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parse adjacent title tags individually. The ASCII range A-z includes both square brackets. For [Video] [Development], this pattern captures Video] [Development as a single tag and sends that malformed value to feed consumers. Use a character class that excludes the brackets, such as [A-Za-z ], so each prefix produces its own tag. War Thunder title using both tags

* Fix two-factor login, token refresh, inventory, and news handling

* Fix token refresh, 2FA retries, and marketplace and forum responses

@MrMindBlow MrMindBlow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@Maho-Yoshino
Maho-Yoshino merged commit e07ef29 into main Nov 21, 2026
2 checks passed
@Maho-Yoshino
Maho-Yoshino deleted the cleanup-returns branch November 21, 2026 18:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants