Skip to content

Conversation

aaa4xu
Copy link
Contributor

@aaa4xu aaa4xu commented Aug 7, 2025

Description:

This PR introduces a graceful fallback path for loading replay files.
If fetching a replay from Cloudflare R2 fails, the server now retries via the public endpoint https://api.openfront.io/game/{gameId}, so developers can replay games locally.

Closes issue #1571

Please complete the following:

  • I have added screenshots for all UI updates
  • I process any text displayed to the user through translateText() and I've added it to the en.json file
  • I have added relevant tests to the test directory
  • I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced
  • I have read and accepted the CLA agreement (only required once).

Please put your Discord username so you can be contacted if a bug or regression is found:

aaa4xu

Copy link
Contributor

coderabbitai bot commented Aug 7, 2025

Walkthrough

Added a server-config replayUrl(gameId: GameID) method; archive writes now separate analytics and redacted full-game uploads (removing player persistent IDs); read path validates archived records via RedactedGameRecordSchema and falls back to fetching config.replayUrl(gameId) when primary storage fails; client and worker error handling updated; new localization keys added.

Changes

Cohort / File(s) Change Summary
Server Config Interface
src/core/configuration/Config.ts
Added replayUrl(gameId: GameID): string to ServerConfig.
Default Server Config
src/core/configuration/DefaultConfig.ts
Implemented replayUrl(gameId) using jwtIssuer() base URL and /game/{gameId} path.
Dev Server Config
src/core/configuration/DevConfig.ts
Added replayUrl(gameId) returning https://api.openfront.io/game/{gameId}.
Test Server Config
tests/util/TestServerConfig.ts
Added replayUrl(gameId) stub that throws not-implemented.
Schemas — Redacted Record
src/core/Schemas.ts
Added RedactedGameRecordSchema and inferred RedactedGameRecord type that remove persistentID from info.players.
Archive logic & validation
src/server/Archive.ts
Refactored archive flow: added stripTurns (analytics) and stripPersistentIds (redacted full game); archive helpers accept typed records; readGameRecord now validates via RedactedGameRecordSchema, improved logging, added readGameRecordFallback that fetches config.replayUrl(gameId). Return type changed to `Promise<RedactedGameRecord
Worker API response
src/server/Worker.ts
/api/archived_game/:id treats string errors specially, returns the error string, and uses JSON.stringify with replacer; sets Content-Type: application/json.
Client archived-game check
src/client/JoinPrivateLobbyModal.ts
checkArchivedGame now short-circuits on archived game or archiveData.error, sets translated error messages and returns early.
Language resources
resources/lang/en.json
Added replay keys: not_found, error, invalid.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Archive
    participant Config
    participant PublicAPI

    Client->>Archive: readGameRecord(gameId)
    Archive->>Archive: try read from primary R2 storage
    alt Primary returns body
        Archive->>Archive: parse & validate (RedactedGameRecordSchema)
        Archive-->>Client: return RedactedGameRecord
    else Primary missing / invalid / error
        Archive->>Config: replayUrl(gameId)
        Archive->>PublicAPI: HTTP GET fallback (Accept: application/json, timeout)
        alt Public API 200 + JSON
            PublicAPI-->>Archive: JSON body
            Archive->>Archive: validate (RedactedGameRecordSchema)
            Archive-->>Client: return RedactedGameRecord
        else 404 / non-JSON / error
            Archive-->>Client: return error string ("replay.not_found" / "replay.error" / "replay.invalid")
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A replay finds a safer road,
IDs stripped where secrets go.
If R2 hides the round you seek,
A public fetch will take a peek.
Logs sing clear and errors show — replays back to play they flow. 🎮

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 7, 2025
@scottanderson scottanderson added Feature - Frontend An entirely new feature, or changes to existing feature. User facing. UI/UX UI/UX changes including assets, menus, QoL, etc. Release Blocker This feature/bug is a priority to work on labels Aug 7, 2025
@scottanderson scottanderson added this to the v26 milestone Aug 7, 2025
@scottanderson scottanderson linked an issue Aug 7, 2025 that may be closed by this pull request
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
src/server/Archive.ts (2)

184-184: Add schema validation for response data.

The response JSON is cast to GameRecord without validation, which could cause runtime errors if the API returns unexpected data structure.


184-184: Critical: Missing schema validation for API response

The response JSON is cast to GameRecord without validation, creating unsafe type assumptions. Based on past comments, GameRecordSchema validation fails with API responses due to missing fields like persistentID and different intent.type structures.

You need to either:

  1. Fix the API to return data matching GameRecordSchema, or
  2. Create a separate schema for API responses, or
  3. Add proper error handling for schema mismatches
-    return await response.json();
+    const json = await response.json();
+    try {
+      return GameRecordSchema.parse(json);
+    } catch (parseError) {
+      log.info(`${gameId}: API response doesn't match expected schema: ${parseError}`);
+      return null;
+    }
🧹 Nitpick comments (1)
src/server/Archive.ts (1)

161-202: Consider adding timeout and retry logic

The fallback function lacks timeout protection and retry logic for network requests. Consider adding:

  • Request timeout to prevent hanging
  • Simple retry logic for transient failures
  • More specific error handling for different HTTP status codes
+const FALLBACK_TIMEOUT = 10000; // 10 seconds
+
 export async function readGameRecordFallback(
   gameId: GameID,
 ): Promise<GameRecord | null> {
   try {
-    const response = await fetch(config.replayFallbackUrl(gameId), {
+    const controller = new AbortController();
+    const timeoutId = setTimeout(() => controller.abort(), FALLBACK_TIMEOUT);
+    
+    const response = await fetch(config.replayFallbackUrl(gameId), {
       headers: {
         Accept: "application/json",
       },
+      signal: controller.signal,
     });
+    
+    clearTimeout(timeoutId);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a910ef4 and 4a80385.

📒 Files selected for processing (3)
  • src/core/configuration/DefaultConfig.ts (1 hunks)
  • src/core/configuration/DevConfig.ts (2 hunks)
  • src/server/Archive.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/configuration/DefaultConfig.ts
🧰 Additional context used
🧠 Learnings (8)
📓 Common learnings
Learnt from: andrewNiziolek
PR: openfrontio/OpenFrontIO#1007
File: resources/lang/de.json:115-115
Timestamp: 2025-06-02T14:27:37.609Z
Learning: For OpenFrontIO project: When localization keys are renamed in language JSON files, the maintainers separate technical changes from translation content updates. They wait for community translators to update the actual translation values rather than attempting to translate in the same PR. This allows technical changes to proceed while ensuring accurate translations from native speakers.
📚 Learning: in the codebase, playerstats is defined as `z.infer` where playerstatssche...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:34-38
Timestamp: 2025-05-21T04:10:33.435Z
Learning: In the codebase, PlayerStats is defined as `z.infer<typeof PlayerStatsSchema>` where PlayerStatsSchema has `.optional()` applied at the object level, making PlayerStats a union type that already includes undefined (PlayerStats | undefined).

Applied to files:

  • src/core/configuration/DevConfig.ts
  • src/server/Archive.ts
📚 Learning: in the codebase, playerstats is defined as a type inferred from a zod schema that is marked as optio...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:34-38
Timestamp: 2025-05-21T04:10:33.435Z
Learning: In the codebase, PlayerStats is defined as a type inferred from a Zod schema that is marked as optional, which means PlayerStats already includes undefined as a possible type (PlayerStats | undefined).

Applied to files:

  • src/core/configuration/DevConfig.ts
  • src/server/Archive.ts
📚 Learning: in the openfrontio codebase, usersettings instances are created directly with `new usersettings()` i...
Learnt from: devalnor
PR: openfrontio/OpenFrontIO#1195
File: src/client/graphics/layers/AlertFrame.ts:18-18
Timestamp: 2025-06-20T20:11:00.965Z
Learning: In the OpenFrontIO codebase, UserSettings instances are created directly with `new UserSettings()` in each component that needs them. This pattern is used consistently across at least 12+ files including OptionsMenu, EventsDisplay, DarkModeButton, Main, UserSettingModal, UsernameInput, NameLayer, AlertFrame, UILayer, InputHandler, ClientGameRunner, and GameView. This is the established architectural pattern and should be followed for consistency.

Applied to files:

  • src/core/configuration/DevConfig.ts
📚 Learning: the playerstats type from archiveschemas already includes undefined in its definition, making explic...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.

Applied to files:

  • src/core/configuration/DevConfig.ts
  • src/server/Archive.ts
📚 Learning: when working with zod schemas in the openfrontio project, values can be marked as possibly undefined...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:189-209
Timestamp: 2025-05-18T23:43:38.150Z
Learning: When working with zod schemas in the OpenFrontIO project, values can be marked as possibly undefined by zod even if logic suggests they should always be defined. It's better to preserve the `| undefined` union types in method signatures to align with zod's type inference, even if runtime checks throw errors for invalid cases.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in zod, when a schema has `.optional()` applied at the object level, the typescript type inferred us...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: In Zod, when a schema has `.optional()` applied at the object level, the TypeScript type inferred using `z.infer` already includes `undefined` in the union type. Therefore, when using such a type as a return type annotation, there's no need to explicitly add `| undefined`.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in zod v4, the correct import is `import { z } from "zod/v4"` and z.prettifyerror(error) is a built-...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1161
File: src/server/jwt.ts:0-0
Timestamp: 2025-06-19T19:31:29.475Z
Learning: In Zod v4, the correct import is `import { z } from "zod/v4"` and z.prettifyError(error) is a built-in utility method for formatting ZodError into readable, multi-line strings. This is different from Zod v3.x which required different error handling approaches.

Applied to files:

  • src/server/Archive.ts
🔇 Additional comments (9)
src/core/configuration/DevConfig.ts (4)

3-3: LGTM!

The GameID import is needed for the new method parameter type.


46-48: LGTM!

Clean implementation using template literal. The hardcoded URL approach is appropriate for dev config.


3-3: LGTM: Import addition is correct

The GameID import is properly added for the new method parameter type.


46-48: LGTM: Clean implementation of fallback URL method

The method correctly implements the interface with a hardcoded URL appropriate for development configuration. The template string interpolation is clean and typed.

src/server/Archive.ts (5)

134-137: LGTM!

Good fallback handling when R2 returns empty response body. The warning log helps with debugging.


144-158: LGTM!

Smart change to use info level logging since R2 failures are no longer terminal with the fallback mechanism in place.


185-201: LGTM!

Consistent error handling pattern with appropriate info level logging for the fallback mechanism.


134-137: Good handling of undefined response body

The explicit check for undefined response body with appropriate logging and fallback call improves robustness.


144-158: LGTM: Error handling improvements

The change to log at info level instead of error addresses previous feedback and makes sense for fallback scenarios. The consistent error handling structure is maintained.

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 7, 2025
@scottanderson
Copy link
Contributor

Thanks for the quick PR for this.

Please note the supported keywords at https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/linking-a-pull-request-to-an-issue I have manually linked the referenced ticket, so no need to do it on this PR.

@CLAassistant
Copy link

CLAassistant commented Aug 7, 2025

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
0 out of 2 committers have signed the CLA.

❌ scottanderson
❌ aaa4xu
You have signed the CLA already but the status is still pending? Let us recheck it.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/server/Archive.ts (1)

218-218: Add schema validation for API response.

The function performs unsafe casting of the JSON response to GameRecord. Based on past review discussions, this should be validated with a proper schema to prevent runtime errors.

Consider implementing the schema validation approach discussed in previous reviews, or use a more lenient schema specifically for API responses if the full GameRecord schema is too strict.

🧹 Nitpick comments (2)
src/server/Archive.ts (2)

36-36: Fix typo in function name.

The function name has a typo: stripPerisistentIds should be stripPersistentIds.

Apply this diff to fix the typo:

-      await archiveFullGameToR2(stripPerisistentIds(gameRecord));
+      await archiveFullGameToR2(stripPersistentIds(gameRecord));

178-192: Consider the impact of reducing error logging level.

The error logging was changed from error to info level. While this reduces noise in logs, it might make debugging R2 connectivity issues harder to spot. Consider if warn level would be more appropriate for actual failures.

The fallback mechanism implementation looks solid and provides good resilience.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a80385 and adffbb7.

📒 Files selected for processing (2)
  • src/core/Schemas.ts (1 hunks)
  • src/server/Archive.ts (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/core/Schemas.ts
🧰 Additional context used
🧠 Learnings (9)
📓 Common learnings
Learnt from: andrewNiziolek
PR: openfrontio/OpenFrontIO#1007
File: resources/lang/de.json:115-115
Timestamp: 2025-06-02T14:27:37.609Z
Learning: For OpenFrontIO project: When localization keys are renamed in language JSON files, the maintainers separate technical changes from translation content updates. They wait for community translators to update the actual translation values rather than attempting to translate in the same PR. This allows technical changes to proceed while ensuring accurate translations from native speakers.
📚 Learning: in the codebase, playerstats is defined as `z.infer` where playerstatssche...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:34-38
Timestamp: 2025-05-21T04:10:33.435Z
Learning: In the codebase, PlayerStats is defined as `z.infer<typeof PlayerStatsSchema>` where PlayerStatsSchema has `.optional()` applied at the object level, making PlayerStats a union type that already includes undefined (PlayerStats | undefined).

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the codebase, playerstats is defined as a type inferred from a zod schema that is marked as optio...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:34-38
Timestamp: 2025-05-21T04:10:33.435Z
Learning: In the codebase, PlayerStats is defined as a type inferred from a Zod schema that is marked as optional, which means PlayerStats already includes undefined as a possible type (PlayerStats | undefined).

Applied to files:

  • src/server/Archive.ts
📚 Learning: when working with zod schemas in the openfrontio project, values can be marked as possibly undefined...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:189-209
Timestamp: 2025-05-18T23:43:38.150Z
Learning: When working with zod schemas in the OpenFrontIO project, values can be marked as possibly undefined by zod even if logic suggests they should always be defined. It's better to preserve the `| undefined` union types in method signatures to align with zod's type inference, even if runtime checks throw errors for invalid cases.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in zod, when a schema has `.optional()` applied at the object level, the typescript type inferred us...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: In Zod, when a schema has `.optional()` applied at the object level, the TypeScript type inferred using `z.infer` already includes `undefined` in the union type. Therefore, when using such a type as a return type annotation, there's no need to explicitly add `| undefined`.

Applied to files:

  • src/server/Archive.ts
📚 Learning: the playerstats type from archiveschemas already includes undefined in its definition, making explic...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in zod v4, the correct import is `import { z } from "zod/v4"` and z.prettifyerror(error) is a built-...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1161
File: src/server/jwt.ts:0-0
Timestamp: 2025-06-19T19:31:29.475Z
Learning: In Zod v4, the correct import is `import { z } from "zod/v4"` and z.prettifyError(error) is a built-in utility method for formatting ZodError into readable, multi-line strings. This is different from Zod v3.x which required different error handling approaches.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the openfrontio project, the correct path for icons from src/client/index.html is ../../resources...
Learnt from: tnhnblgl
PR: openfrontio/OpenFrontIO#875
File: src/client/index.html:396-402
Timestamp: 2025-05-26T09:52:52.465Z
Learning: In the OpenFrontIO project, the correct path for icons from src/client/index.html is ../../resources/icons/, not /static/icons/ as the build process handles the path mapping differently.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the openfrontio codebase, for unit tests it's acceptable to let exceptions (like json parsing err...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1441
File: tests/LangCode.test.ts:19-32
Timestamp: 2025-07-15T17:20:17.831Z
Learning: In the OpenFrontIO codebase, for unit tests it's acceptable to let exceptions (like JSON parsing errors) propagate and fail the test naturally rather than adding explicit error handling with try-catch blocks, as the test framework will catch them and fail the test appropriately.

Applied to files:

  • src/server/Archive.ts
🧬 Code Graph Analysis (1)
src/server/Archive.ts (2)
src/core/Schemas.ts (3)
  • GameRecord (560-560)
  • AnalyticsRecord (555-555)
  • GameID (21-21)
src/core/Util.ts (1)
  • replacer (287-289)
🪛 GitHub Actions: 🧪 CI
src/server/Archive.ts

[error] 98-98: TypeScript error TS2322: Type '{ clientID: string; username: string; pattern: string | undefined; flag: string | undefined; }[]' is not assignable to type with required property 'persistentID'. Property 'persistentID' is missing but required.

🔇 Additional comments (3)
src/server/Archive.ts (3)

57-68: LGTM!

Clean implementation that extracts analytics data by excluding the turns field. The destructuring approach is readable and type-safe.


108-109: LGTM!

Good refactoring - the function now has a clear single responsibility by accepting pre-processed AnalyticsRecord instead of extracting analytics data internally.


146-147: LGTM!

Good separation of concerns - the archiving function now focuses solely on storage while data sanitization is handled by the caller.

@github-project-automation github-project-automation bot moved this from Triage to Development in OpenFront Release Management Aug 7, 2025
@aaa4xu aaa4xu marked this pull request as draft August 7, 2025 13:37
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between adffbb7 and b990aa2.

📒 Files selected for processing (1)
  • src/server/Archive.ts (6 hunks)
🧰 Additional context used
🧠 Learnings (9)
📚 Learning: the playerstats type from archiveschemas already includes undefined in its definition, making explic...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the codebase, playerstats is defined as `z.infer` where playerstatssche...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:34-38
Timestamp: 2025-05-21T04:10:33.435Z
Learning: In the codebase, PlayerStats is defined as `z.infer<typeof PlayerStatsSchema>` where PlayerStatsSchema has `.optional()` applied at the object level, making PlayerStats a union type that already includes undefined (PlayerStats | undefined).

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the codebase, playerstats is defined as a type inferred from a zod schema that is marked as optio...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:34-38
Timestamp: 2025-05-21T04:10:33.435Z
Learning: In the codebase, PlayerStats is defined as a type inferred from a Zod schema that is marked as optional, which means PlayerStats already includes undefined as a possible type (PlayerStats | undefined).

Applied to files:

  • src/server/Archive.ts
📚 Learning: when working with zod schemas in the openfrontio project, values can be marked as possibly undefined...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:189-209
Timestamp: 2025-05-18T23:43:38.150Z
Learning: When working with zod schemas in the OpenFrontIO project, values can be marked as possibly undefined by zod even if logic suggests they should always be defined. It's better to preserve the `| undefined` union types in method signatures to align with zod's type inference, even if runtime checks throw errors for invalid cases.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in zod, when a schema has `.optional()` applied at the object level, the typescript type inferred us...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: In Zod, when a schema has `.optional()` applied at the object level, the TypeScript type inferred using `z.infer` already includes `undefined` in the union type. Therefore, when using such a type as a return type annotation, there's no need to explicitly add `| undefined`.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in zod v4, the correct import is `import { z } from "zod/v4"` and z.prettifyerror(error) is a built-...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1161
File: src/server/jwt.ts:0-0
Timestamp: 2025-06-19T19:31:29.475Z
Learning: In Zod v4, the correct import is `import { z } from "zod/v4"` and z.prettifyError(error) is a built-in utility method for formatting ZodError into readable, multi-line strings. This is different from Zod v3.x which required different error handling approaches.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the openfrontio project, the correct path for icons from src/client/index.html is ../../resources...
Learnt from: tnhnblgl
PR: openfrontio/OpenFrontIO#875
File: src/client/index.html:396-402
Timestamp: 2025-05-26T09:52:52.465Z
Learning: In the OpenFrontIO project, the correct path for icons from src/client/index.html is ../../resources/icons/, not /static/icons/ as the build process handles the path mapping differently.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the openfrontio codebase, for unit tests it's acceptable to let exceptions (like json parsing err...
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1441
File: tests/LangCode.test.ts:19-32
Timestamp: 2025-07-15T17:20:17.831Z
Learning: In the OpenFrontIO codebase, for unit tests it's acceptable to let exceptions (like JSON parsing errors) propagate and fail the test naturally rather than adding explicit error handling with try-catch blocks, as the test framework will catch them and fail the test appropriately.

Applied to files:

  • src/server/Archive.ts
📚 Learning: in the openfrontio codebase, `checkpermission()` function's return values need to be handled with de...
Learnt from: Aotumuri
PR: openfrontio/OpenFrontIO#709
File: src/client/Main.ts:276-296
Timestamp: 2025-05-16T12:06:01.732Z
Learning: In the OpenFrontIO codebase, `checkPermission()` function's return values need to be handled with defensive checks using `Array.isArray()`, even though its TypeScript signature indicates it returns arrays. Removing these checks breaks functionality.

Applied to files:

  • src/server/Archive.ts
🧬 Code Graph Analysis (1)
src/server/Archive.ts (2)
src/core/Schemas.ts (5)
  • GameRecord (560-560)
  • AnalyticsRecord (555-555)
  • RedactedGameRecord (573-573)
  • GameID (21-21)
  • RedactedGameRecordSchema (562-572)
src/core/Util.ts (1)
  • replacer (287-289)
🔇 Additional comments (8)
src/server/Archive.ts (8)

36-36: LGTM! Proper data redaction before archiving.

The preprocessing approach correctly separates analytics data from full game data and removes sensitive information before storage.

Also applies to: 43-43


64-75: LGTM! Clean implementation with proper type safety.

The function clearly extracts analytics data while excluding turns, using readable destructuring syntax.


77-113: LGTM! Addresses past review feedback effectively.

The function correctly:

  • Fixes the typo in function name
  • Uses proper RedactedGameRecord return type
  • Cleanly removes persistentID fields using functional mapping
  • Uses underscore convention for unused destructured variables

115-116: LGTM! Proper type alignment with preprocessing.

The function signature correctly accepts AnalyticsRecord, making the archiving process more type-safe and purposeful.

Also applies to: 124-124


149-149: LGTM! Enhanced data privacy with RedactedGameRecord.

The function signature change ensures sensitive data cannot be accidentally archived to full game storage.

Also applies to: 153-154


167-167: LGTM! Excellent resilience improvements.

The changes provide:

  • Consistent RedactedGameRecord return type
  • Proper fallback when R2 response is empty
  • Appropriate info-level logging for expected failures
  • Centralized validation through validateRecord helper

The fallback mechanism ensures users can replay games even when primary storage fails.

Also applies to: 175-200


202-243: LGTM! Well-implemented HTTP fallback mechanism.

The function demonstrates good practices:

  • Proper HTTP headers and status checking
  • Content type validation before parsing
  • Appropriate info-level error logging for fallback scenarios
  • Consistent schema validation using validateRecord helper

245-258: LGTM! Clean validation helper with proper error handling.

The function correctly:

  • Centralizes schema validation logic
  • Uses safeParse for graceful error handling
  • Formats errors with z.prettifyError (consistent with project patterns)
  • Provides clear return type semantics

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (2)
src/client/JoinPrivateLobbyModal.ts (2)

243-254: Localize “Version mismatch” message

This user-facing string bypasses translateText, which breaks i18n and contradicts the PR goal that all UI text is localized.

Apply this diff:

-      this.message =
-        "This game was created with a different version. Cannot join.";
+      this.message = translateText("replay.error.version_mismatch");

Optionally include details via params if you expose safe fields:

// example if details has { serverHash, clientHash }
this.message = translateText("replay.error.version_mismatch", {
  // serverHash, clientHash
});

Per team standards, update en.json only; other locales will be handled by translators.


130-141: Bug: lobby id cleared before dispatching "leave-lobby"

close() clears lobbyIdInput.value (Line 122). You then dispatch leave-lobby using the cleared value. Capture it first.

-  public closeAndLeave() {
-    this.close();
-    this.hasJoined = false;
-    this.message = "";
-    this.dispatchEvent(
-      new CustomEvent("leave-lobby", {
-        detail: { lobby: this.lobbyIdInput.value },
-        bubbles: true,
-        composed: true,
-      }),
-    );
-  }
+  public closeAndLeave() {
+    const lobby = this.lobbyIdInput.value;
+    this.close();
+    this.hasJoined = false;
+    this.message = "";
+    this.dispatchEvent(
+      new CustomEvent("leave-lobby", {
+        detail: { lobby },
+        bubbles: true,
+        composed: true,
+      }),
+    );
+  }
♻️ Duplicate comments (1)
src/client/JoinPrivateLobbyModal.ts (1)

269-271: Good: translate error key and short-circuit once handled

Using translateText(archiveData.error) and returning early matches the earlier guidance to send translation keys from the server. This keeps UI strings localized and avoids falling through to “not found.”

🧹 Nitpick comments (2)
src/client/JoinPrivateLobbyModal.ts (2)

270-273: Fallback when translation key is missing

If the server sends a key not yet in en.json, translateText returns the key itself. Show a generic localized message instead of the raw key/server string.

Apply this diff:

-    } else if (archiveData.error) {
-      this.message = translateText(archiveData.error);
-      return true;
-    }
+    } else if (archiveData.error) {
+      const key = archiveData.error;
+      const localized = translateText(key);
+      this.message =
+        localized !== key ? localized : translateText("replay.error.generic");
+      return true;
+    }

Ensure en.json has replay.error.generic.


26-27: Use browser-friendly timer type

Use ReturnType for compatibility in browser builds.

-  private playersInterval: NodeJS.Timeout | null = null;
+  private playersInterval: ReturnType<typeof setInterval> | null = null;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5735838 and 16c45d4.

📒 Files selected for processing (3)
  • src/client/JoinPrivateLobbyModal.ts (1 hunks)
  • src/core/Schemas.ts (1 hunks)
  • src/server/Worker.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/server/Worker.ts
  • src/core/Schemas.ts
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: andrewNiziolek
PR: openfrontio/OpenFrontIO#1007
File: resources/lang/de.json:115-115
Timestamp: 2025-06-02T14:27:37.609Z
Learning: For OpenFrontIO project: When localization keys are renamed in language JSON files, the maintainers separate technical changes from translation content updates. They wait for community translators to update the actual translation values rather than attempting to translate in the same PR. This allows technical changes to proceed while ensuring accurate translations from native speakers.
📚 Learning: 2025-06-09T02:20:43.637Z
Learnt from: VariableVince
PR: openfrontio/OpenFrontIO#1110
File: src/client/Main.ts:293-295
Timestamp: 2025-06-09T02:20:43.637Z
Learning: In src/client/Main.ts, during game start in the handleJoinLobby callback, UI elements are hidden using direct DOM manipulation with classList.add("hidden") for consistency. This includes modals, buttons, and error divs. The codebase follows this pattern rather than using component APIs for hiding elements during game transitions.

Applied to files:

  • src/client/JoinPrivateLobbyModal.ts
📚 Learning: 2025-06-02T14:27:37.609Z
Learnt from: andrewNiziolek
PR: openfrontio/OpenFrontIO#1007
File: resources/lang/de.json:115-115
Timestamp: 2025-06-02T14:27:37.609Z
Learning: For OpenFrontIO project: When localization keys are renamed in language JSON files, the maintainers separate technical changes from translation content updates. They wait for community translators to update the actual translation values rather than attempting to translate in the same PR. This allows technical changes to proceed while ensuring accurate translations from native speakers.

Applied to files:

  • src/client/JoinPrivateLobbyModal.ts
📚 Learning: 2025-06-02T14:27:23.893Z
Learnt from: andrewNiziolek
PR: openfrontio/OpenFrontIO#1007
File: resources/lang/he.json:138-138
Timestamp: 2025-06-02T14:27:23.893Z
Learning: andrewNiziolek's project uses community translation for internationalization. When updating map names or other user-facing text, they update the keys programmatically but wait for community translators to provide accurate translations in each language rather than using machine translations.

Applied to files:

  • src/client/JoinPrivateLobbyModal.ts
📚 Learning: 2025-07-12T08:41:35.101Z
Learnt from: Aotumuri
PR: openfrontio/OpenFrontIO#1357
File: resources/lang/de.json:523-540
Timestamp: 2025-07-12T08:41:35.101Z
Learning: In OpenFrontIO project localization files, always check the en.json source file before flagging potential spelling errors in other language files, as some keys may intentionally use non-standard spellings that need to be consistent across all translations.

Applied to files:

  • src/client/JoinPrivateLobbyModal.ts
📚 Learning: 2025-05-30T03:53:52.231Z
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#949
File: resources/lang/en.json:8-10
Timestamp: 2025-05-30T03:53:52.231Z
Learning: For the OpenFrontIO project, do not suggest updating translation files in resources/lang/*.json except for en.json. The project has a dedicated translation team that handles all other locale files.

Applied to files:

  • src/client/JoinPrivateLobbyModal.ts
🧬 Code Graph Analysis (1)
src/client/JoinPrivateLobbyModal.ts (1)
src/client/Utils.ts (1)
  • translateText (82-137)
🔇 Additional comments (1)
src/client/JoinPrivateLobbyModal.ts (1)

241-242: Ignore schema refactor—error is already a strict literal union
The WorkerApiArchivedGameLobbySchema defines error as exactly "Game not found" or "Version mismatch". It does not accept arbitrary strings, so no change to make it a tighter z.enum is needed. Also, there are no replay.error.* keys in your i18n files, so replacing the schema literals with those keys isn’t applicable.

Likely an incorrect or invalid review comment.

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 9, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 9, 2025
scottanderson
scottanderson previously approved these changes Aug 23, 2025
@github-project-automation github-project-automation bot moved this from Development to Final Review in OpenFront Release Management Aug 23, 2025
@cwalo
Copy link

cwalo commented Aug 24, 2025

I pulled this branch locally, but it looks like the there's troop_ratio intents can't be parsed. I know it's been removed in v25, but I'm curious why they would still appear in a v25 game record.
https://api.openfront.io/game/GSrs74Nu

Error parsing game record: ✖ Invalid input\n → at turns[1].intents[0].type

"intents":[{"clientID":"2iGfvjHp","type":"troop_ratio","ratio":0.95}]}

@aaa4xu
Copy link
Contributor Author

aaa4xu commented Aug 24, 2025

"gitCommit": "c7fb5790256814340ed0bb590489eb97198b21c3",
This is replay from v24.13

@cwalo
Copy link

cwalo commented Aug 24, 2025

Ope, good catch. Here's one from v25.3: https://api.openfront.io/game/uHgqzZBF which fails for different reasons

Error parsing game record: ✖ Invalid input: expected string, received undefined\n → at turns[12].intents[2].name\n✖ Invalid option: expected one of \"BOT\"|\"HUMAN\"|\"FAKEHUMAN\"\n → at turns[12].intents[2].playerType\n

@scottanderson
Copy link
Contributor

@aaa4xu could you please resolve the conflicts with main?

@cwalo cwalo mentioned this pull request Aug 25, 2025
4 tasks
@scottanderson scottanderson dismissed stale reviews from coderabbitai[bot] and themself via 44dc690 August 25, 2025 17:56
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/client/JoinPrivateLobbyModal.ts (1)

275-279: Good: translate server error keys and short-circuit the flow

Using translateText(archiveData.error) and returning early keeps the UI logic simple and localized. This matches the earlier guidance to send/translate keys instead of raw messages.

🧹 Nitpick comments (6)
src/client/JoinPrivateLobbyModal.ts (1)

249-260: Localize the version-mismatch message; avoid hard-coded English

Right now the message is a literal string. Please use a translation key for consistency with the rest of this file and the new replay.* keys.

Two options:

  • Minimal change (add a key): set message via translateText("replay.version_mismatch") and add that key to en.json.
  • Better: remove this special-case and rely on archiveData.error to be a translation key ("replay.version_mismatch"), same as the generic branch below.

Suggested minimal diff:

-      this.message =
-        "This game was created with a different version. Cannot join.";
+      this.message = translateText("replay.version_mismatch");

Also add "replay.version_mismatch" to en.json, e.g. "This replay is from a different game version."

Would you like me to wire the en.json key and open a follow-up to make the server return "replay.version_mismatch" for this case so we can delete this special-case?

src/server/Archive.ts (5)

28-41: Nit: avoid mutating the input gameRecord; prefer a composed copy

archive() sets gameRecord.gitCommit in place. If callers reuse the object (tests, logging, or other sinks), this side effect can surprise. Compose a copy with the updated field and pass that through.

-export async function archive(gameRecord: GameRecord) {
+export async function archive(gameRecord: GameRecord) {
   try {
-    gameRecord.gitCommit = config.gitCommit();
+    const recordWithCommit: GameRecord = { ...gameRecord, gitCommit: config.gitCommit() };
     // Archive to R2
-    await archiveAnalyticsToR2(stripTurns(gameRecord));
+    await archiveAnalyticsToR2(stripTurns(recordWithCommit));
     // Archive full game if there are turns
-    if (gameRecord.turns.length > 0) {
+    if (recordWithCommit.turns.length > 0) {
       log.info(
-        `${gameRecord.info.gameID}: game has more than zero turns, attempting to write to full game to R2`,
+        `${recordWithCommit.info.gameID}: game has more than zero turns, attempting to write to full game to R2`,
       );
-      await archiveFullGameToR2(stripPersistentIds(gameRecord));
+      await archiveFullGameToR2(stripPersistentIds(recordWithCommit));
     }

60-71: Confirm PII policy for analytics: players in info may still include persistentID

stripTurns() copies info as-is. If analytics objects are accessible outside trusted scope, we should also remove persistentID from info.players here (same as the full replay path). If analytics are private, ignore this.

If needed, a lightweight redact inline:

 function stripTurns(gameRecord: GameRecord): AnalyticsRecord {
   const { info, version, gitCommit, subdomain, domain } = gameRecord;
-  const analyticsData: AnalyticsRecord = {
-    info,
+  const analyticsData: AnalyticsRecord = {
+    info: {
+      ...info,
+      players: info.players.map(({ persistentID: _omit, ...rest }) => rest),
+    },
     version,
     gitCommit,
     subdomain,
     domain,
   };
   return analyticsData;
 }

73-109: Solid redaction logic; minor naming clarity

The player mapping cleanly strips persistentID. To avoid confusion with the top-level config variable, consider renaming the destructured info.config to gameConfig.

-    info: {
-      gameID,
-      config,
+    info: {
+      gameID,
+      config: gameConfig,
       players: privatePlayers,
       start,
       end,
       duration,
       num_turns,
       winner,
     },
@@
-  const replayData: RedactedGameRecord = {
-    info: { gameID, config, players, start, end, duration, num_turns, winner },
+  const replayData: RedactedGameRecord = {
+    info: { gameID, config: gameConfig, players, start, end, duration, num_turns, winner },

198-247: Timeout on public API fetch: OK given Node ≥20; optionally include the status text in logs

AbortSignal.timeout(5000) is fine on supported Node lines (20/22/24). If you want slightly richer ops context, log response.statusText with status when non-OK.

-      throw new Error(
-        `Http error: non-successful http status ${response.status}`,
-      );
+      throw new Error(
+        `Http error: non-successful http status ${response.status} ${response.statusText ?? ""}`.trim(),
+      );

249-262: Consider a discriminated union to carry error details as values (no exceptions)

Current return type collapses all failures to a key (e.g., "replay.invalid"), so the client cannot surface pretty zod errors as requested in the PR discussion. Keep errors-as-values but lift details into the type.

Example shape:

  • Success: { ok: true; data: RedactedGameRecord }
  • Failure: { ok: false; error: "replay.not_found" | "replay.invalid" | "replay.error"; details?: string }

This keeps typed unions, avoids throws, and lets the UI optionally display details.

If accepted, I can provide a follow-up patch touching:

  • readGameRecord/readGameRecordFallback/validateRecord returns
  • Worker endpoint response shape (add details passthrough)
  • WorkerApiArchivedGameLobbySchema + client branch that shows details (behind a disclosure)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6730ab1 and 44dc690.

📒 Files selected for processing (9)
  • resources/lang/en.json (1 hunks)
  • src/client/JoinPrivateLobbyModal.ts (1 hunks)
  • src/core/Schemas.ts (1 hunks)
  • src/core/configuration/Config.ts (1 hunks)
  • src/core/configuration/DefaultConfig.ts (1 hunks)
  • src/core/configuration/DevConfig.ts (2 hunks)
  • src/server/Archive.ts (6 hunks)
  • src/server/Worker.ts (3 hunks)
  • tests/util/TestServerConfig.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/core/Schemas.ts
  • tests/util/TestServerConfig.ts
  • src/core/configuration/Config.ts
  • src/core/configuration/DefaultConfig.ts
  • resources/lang/en.json
  • src/core/configuration/DevConfig.ts
  • src/server/Worker.ts
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-06-09T02:20:43.637Z
Learnt from: VariableVince
PR: openfrontio/OpenFrontIO#1110
File: src/client/Main.ts:293-295
Timestamp: 2025-06-09T02:20:43.637Z
Learning: In src/client/Main.ts, during game start in the handleJoinLobby callback, UI elements are hidden using direct DOM manipulation with classList.add("hidden") for consistency. This includes modals, buttons, and error divs. The codebase follows this pattern rather than using component APIs for hiding elements during game transitions.

Applied to files:

  • src/client/JoinPrivateLobbyModal.ts
📚 Learning: 2025-05-21T04:10:59.706Z
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.

Applied to files:

  • src/server/Archive.ts
📚 Learning: 2025-08-09T05:03:18.745Z
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1761
File: src/core/ApiSchemas.ts:2-2
Timestamp: 2025-08-09T05:03:18.745Z
Learning: After migrating to Zod v4 in the OpenFrontIO project, the standard import statement `import { z } from "zod"` should be used across the entire codebase, not `import { z } from "zod/v4"`.

Applied to files:

  • src/server/Archive.ts
🧬 Code graph analysis (2)
src/client/JoinPrivateLobbyModal.ts (2)
src/client/Utils.ts (1)
  • translateText (83-147)
src/client/LangSelector.ts (1)
  • translateText (259-279)
src/server/Archive.ts (2)
src/core/Schemas.ts (5)
  • GameRecord (565-565)
  • AnalyticsRecord (560-560)
  • RedactedGameRecord (578-578)
  • GameID (22-22)
  • RedactedGameRecordSchema (567-577)
src/core/Util.ts (1)
  • replacer (303-305)
🔇 Additional comments (3)
src/server/Archive.ts (3)

111-143: LGTM: analytics write path with bigint-safe serialization

Using the replacer prevents bigint crashes and the per-gameID key keeps lookups simple.


145-159: LGTM: full replay write path

Keying by folder/gameID (no extension) matches the read path below and avoids a breaking change.


161-196: Good fallback behavior and structured logging

  • Empty Body fallback to API is pragmatic.
  • Logging non-Error at info level keeps noise down.

No changes needed.

@github-project-automation github-project-automation bot moved this from Final Review to Development in OpenFront Release Management Aug 25, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 25, 2025
@cwalo
Copy link

cwalo commented Aug 26, 2025

@aaa4xu You mind signing the CLA so this can be merged? :)

try {
// Check if file exists and download in one operation
const response = await r2.getObject({
Bucket: bucket,
Key: `${gameFolder}/${gameId}`, // Fixed - needed to include gameFolder
});
// Parse the response body
if (response.Body === undefined) return null;
if (response.Body === undefined) {
log.warn(`${gameId}: Received empty response from R2`);
Copy link
Contributor

Choose a reason for hiding this comment

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

Do we need a warning here?

Comment on lines +187 to +190
log.info(`${gameId}: Error reading game record from R2: ${error}`, {
message,
stack,
name,
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it may be redundant to log both error and message


export async function readGameRecordFallback(
gameId: GameID,
): Promise<RedactedGameRecord | string> {
Copy link
Contributor

Choose a reason for hiding this comment

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

The current return type (RedactedGameRecord | string) works, but it has a couple of drawbacks. It forces callers to do a typeof check, and it limits the amount of information we can pass back on failure.

One option to improve this is to use a discriminated union and to generate a Response from the error handler:

export type Result<T, E> =
  | { success: true; value: T; error: never; }
  | { success: false; value: never; error: E; };
Suggested change
): Promise<RedactedGameRecord | string> {
): Promise<Result<RedactedGameRecord, Response>> {
return { success: false, error: error(404) };

Comment on lines +214 to +216
throw new Error(
`Http error: non-successful http status ${response.status}`,
);
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Consider being consistent with error handling. Mixing throw with errors as values can be a bit confusing. In this case I think it is better to log/return from this point in the code.

Comment on lines +221 to +223
throw new Error(
`Http error: unexpected content type "${response.headers.get("Content-Type")}"`,
);
Copy link
Contributor

Choose a reason for hiding this comment

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

same as above

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 26, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/server/Archive.ts (3)

127-131: Fix undefined variable in analytics error log

gameRecord is not in scope here; this will throw when logging the Non-Error case. Use info.gameID which you already have.

-    if (!(error instanceof Error)) {
-      log.error(
-        `${gameRecord.info.gameID}: Error writing game analytics to R2. Non-Error type: ${String(error)}`,
-      );
-      return;
-    }
+    if (!(error instanceof Error)) {
+      log.error(
+        `${info.gameID}: Error writing game analytics to R2. Non-Error type: ${String(error)}`,
+      );
+      return;
+    }

153-159: Fix two more out-of-scope references to gameRecord

This function receives recordCopy. The logs reference gameRecord, which is undefined in this scope.

-  } catch (error) {
-    log.error(`error saving game ${gameRecord.info.gameID}`);
+  } catch (error: unknown) {
+    log.error(`${recordCopy.info.gameID}: error saving game`);
     throw error;
   }
 
-  log.info(`${gameRecord.info.gameID}: game record successfully written to R2`);
+  log.info(`${recordCopy.info.gameID}: game record successfully written to R2`);

111-143: Fix out-of-scope gameRecord references in archive functions

Both archiveAnalyticsToR2 and archiveFullGameToR2 log using gameRecord.info.gameID, but neither function has a gameRecord parameter. This will cause compile or runtime errors. Please update the logs to use the correct in-scope variable in each function:

• In archiveAnalyticsToR2 (src/server/Archive.ts around lines 127–131):

- if (!(error instanceof Error)) {
-   log.error(
-     `${gameRecord.info.gameID}: Error writing game analytics to R2. Non-Error type: ${String(error)}`,
-   );
+ if (!(error instanceof Error)) {
+   log.error(
+     `${info.gameID}: Error writing game analytics to R2. Non-Error type: ${String(error)}`,
+   );
    return;
  }

• In archiveFullGameToR2 (src/server/Archive.ts around lines 153–159):

- } catch (error) {
-   log.error(`error saving game ${gameRecord.info.gameID}`);
-   throw error;
- }
-
- log.info(`${gameRecord.info.gameID}: game record successfully written to R2`);
+ } catch (error) {
+   log.error(`error saving game ${recordCopy.info.gameID}`);
+   throw error;
+ }
+
+ log.info(`${recordCopy.info.gameID}: game record successfully written to R2`);

These changes ensure you only reference the parameters actually passed into each function.

♻️ Duplicate comments (2)
src/server/Archive.ts (2)

171-175: Lower this to info to avoid noisy warnings on expected fallback

Empty bodies from R2 can happen and we already have a graceful fallback. Using info keeps logs cleaner. This mirrors earlier reviewer feedback.

-    if (response.Body === undefined) {
-      log.warn(`${gameId}: Received empty response from R2`);
+    if (response.Body === undefined) {
+      log.info(`${gameId}: Received empty response from R2`);
       return readGameRecordFallback(gameId);
     }

161-164: Consider a discriminated Result type instead of string error keys

Returning RedactedGameRecord | string forces typeof checks and makes it easy to miss a new error code. A small, typed union keeps call-sites clean and i18n flexible.

Example:

export type ReplayReadResult =
  | { ok: true; record: RedactedGameRecord }
  | { ok: false; code: "replay.not_found" | "replay.error" | "replay.invalid" };

Then change function signatures to return Promise<ReplayReadResult> and wrap existing returns accordingly.

🧹 Nitpick comments (4)
src/server/Archive.ts (4)

73-109: Redact by omitting persistentID, not by hand-picking a subset of fields

Right now you rebuild each player with only four fields. If PlayerRecord gains new required fields (e.g., playerType), they’ll be lost here and fail validation later. Prefer a structured omit that drops only persistentID and keeps everything else.

-  const players = privatePlayers.map(
-    ({ clientID, persistentID: _, username, pattern, flag }) => ({
-      clientID,
-      username,
-      pattern,
-      flag,
-    }),
-  );
+  const players = privatePlayers.map(({ persistentID: _omit, ...rest }) => rest);

This keeps the code simple and future‑proof. TypeScript will infer the shape as “PlayerRecord without persistentID”, which matches RedactedGameRecord.


198-247: Optional: handle fetch timeout explicitly for clearer ops signals

You already use AbortSignal.timeout(5000). If a timeout happens, logging it explicitly helps triage. We can keep the same return key to avoid i18n churn.

   } catch (error: unknown) {
+    // Special-case fetch timeouts for clearer logs
+    if (error && typeof error === "object" && (error as any).name === "AbortError") {
+      log.info(`${gameId}: Timeout reading game record from public api`);
+      return "replay.error";
+    }
     // If the error is not an instance of Error, log it as a string
     if (!(error instanceof Error)) {
       log.info(

28-40: Avoid mutating the incoming gameRecord (optional)

Setting gameRecord.gitCommit mutates the input. Prefer creating a shallow copy so callers don’t see surprises if they reuse the object.

Sketch:

const record = { ...gameRecord, gitCommit: config.gitCommit() };
await archiveAnalyticsToR2(stripTurns(record));
if (record.turns.length > 0) await archiveFullGameToR2(stripPersistentIds(record));

Also applies to: 60-71


145-152: Nit: align object key naming and content types are good

Using .json extension for analytics and no extension for full games is fine as long as readers match the same convention (they do). Just calling out that the Content-Type is correctly set to application/json in both paths.

Also applies to: 118-122

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 44dc690 and f90e723.

📒 Files selected for processing (1)
  • src/server/Archive.ts (6 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-05-21T04:10:59.706Z
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.

Applied to files:

  • src/server/Archive.ts
📚 Learning: 2025-08-09T05:03:18.745Z
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1761
File: src/core/ApiSchemas.ts:2-2
Timestamp: 2025-08-09T05:03:18.745Z
Learning: After migrating to Zod v4 in the OpenFrontIO project, the standard import statement `import { z } from "zod"` should be used across the entire codebase, not `import { z } from "zod/v4"`.

Applied to files:

  • src/server/Archive.ts
📚 Learning: 2025-08-25T18:30:48.646Z
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1725
File: src/server/Archive.ts:255-258
Timestamp: 2025-08-25T18:30:48.646Z
Learning: z.prettifyError was added in zod v4 and is part of the official Zod API. It can be safely used in codebases using zod v4+.

Applied to files:

  • src/server/Archive.ts
🧬 Code graph analysis (1)
src/server/Archive.ts (1)
src/core/Schemas.ts (5)
  • GameRecord (565-565)
  • AnalyticsRecord (560-560)
  • RedactedGameRecord (578-578)
  • GameID (22-22)
  • RedactedGameRecordSchema (567-577)
🔇 Additional comments (3)
src/server/Archive.ts (3)

255-258: LGTM: use z.prettifyError with Zod v4

Nice use of z.prettifyError for readable diagnostics. This aligns with the project’s Zod v4 usage.


1-7: Imports look consistent with project standards

Using { z } from "zod" matches the codebase convention after the v4 migration. Schema imports are correct.


249-262: Validation flow is solid and simple

Centralizing schema validation into validateRecord keeps the read paths clean and ensures consistent logging and error translation.

@aaa4xu
Copy link
Contributor Author

aaa4xu commented Aug 27, 2025

I would like to inform you that I am withdrawing my CLA with OpenFront LLC and will no longer be contributing to the project.

Since I have already created a pull request, I understand that the project retains the rights to the code submitted under the CLA. However, I will not be proceeding further with this contribution, and if the pull request is to be merged, someone else will need to carry it through.

@aaa4xu aaa4xu removed their assignment Aug 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Feature - Frontend An entirely new feature, or changes to existing feature. User facing. Release Blocker This feature/bug is a priority to work on UI/UX UI/UX changes including assets, menus, QoL, etc.
Projects
Status: Development
Development

Successfully merging this pull request may close these issues.

Pull replay files from api
4 participants