Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Monorepo2 #1940

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open

Monorepo2 #1940

wants to merge 15 commits into from

Conversation

drazisil-codecov
Copy link
Collaborator

@drazisil-codecov drazisil-codecov commented May 14, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive schema for game-related data management, including tables for parts, players, vehicles, and more.
  • Configuration Updates

    • Updated repository URL and package name in package.json.
    • Added new settings and dependencies in various tsconfig.json and package.json files.
    • Updated .gitignore to include *.tsbuildinfo.
  • Refactor

    • Moved component paths from packages to src directories.
    • Switched from dotenv to dotenv/config for environment variable configuration.
  • Build and Testing

    • Updated npm test commands to use pnpm.
    • Added new testing configurations and dependencies.
  • Chores

    • Downgraded Node.js version in .nvmrc.
    • Updated .npmrc with new configurations.

Copy link

codecov bot commented May 14, 2024

Codecov Report

Attention: Patch coverage is 9.95735% with 5489 lines in your changes are missing coverage. Please review.

Project coverage is 9.66%. Comparing base (b8a0fb7) to head (a7101ea).
Report is 10 commits behind head on main.

✅ All tests successful. No failed tests found.

Files Patch % Lines
src/connection/src/Connection.ts 21.57% 298 Missing ⚠️
src/database/src/functions/createNewCar.ts 0.00% 294 Missing ⚠️
src/mcots/payloads/LoginCompleteMessage.ts 0.00% 229 Missing ⚠️
src/nps/gameMessageProcessors/processGameLogin.ts 0.00% 211 Missing ⚠️
src/database/src/seeders/index.ts 0.00% 208 Missing ⚠️
src/nps/messageStructs/GameMessage.ts 0.00% 204 Missing ⚠️
src/nps/messageStructs/GameProfile.ts 0.00% 198 Missing ⚠️
src/gateway/src/GatewayServer.ts 54.12% 178 Missing ⚠️
src/database/src/functions/transferPartAssembly.ts 0.00% 153 Missing ⚠️
src/database/src/seeders/populateWarehouse.ts 0.00% 124 Missing ⚠️
... and 60 more
Additional details and impacted files
@@           Coverage Diff            @@
##            main   #1940      +/-   ##
========================================
- Coverage   9.74%   9.66%   -0.08%     
========================================
  Files        133     132       -1     
  Lines       9730    9714      -16     
  Branches     134     157      +23     
========================================
- Hits         948     939       -9     
+ Misses      8782    8759      -23     
- Partials       0      16      +16     
Flag Coverage Δ *Carryforward flag
cli 0.00% <0.00%> (ø) Carriedforward from 2f74d60
connection 22.79% <21.57%> (-2.87%) ⬇️ Carriedforward from 2f74d60
database 9.80% <5.70%> (+0.09%) ⬆️ Carriedforward from 2f74d60
gateway 40.80% <40.37%> (-0.68%) ⬇️ Carriedforward from 2f74d60
mcots 0.00% <0.00%> (ø) Carriedforward from 2f74d60
nps 0.00% <0.00%> (ø) Carriedforward from 2f74d60
patch 86.32% <87.06%> (+0.23%) ⬆️ Carriedforward from 2f74d60
schema 0.00% <ø> (ø) Carriedforward from 2f74d60
shard 41.47% <ø> (ø)
shared 13.81% <ø> (+0.36%) ⬆️
shared-packets 0.00% <ø> (ø)

*This pull request uses carry forward flags. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

deepsource-io bot commented May 14, 2024

Here's the code health analysis summary for commits b8a0fb7..a7101ea. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource JavaScript LogoJavaScript❌ Failure
❗ 766 occurences introduced
🎯 761 occurences resolved
View Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link
Contributor

coderabbitai bot commented May 14, 2024

Walkthrough

Walkthrough

The recent changes involve significant reorganization and updates across various configuration files, TypeScript settings, and npm package management. Key modifications include moving components from packages to src directories, updating npm and pnpm commands in GitHub workflows, refining TypeScript configurations, and introducing new functionalities in the @rustymotors modules. Additionally, a comprehensive SQL schema for a game system has been added, along with updates to ESLint settings and package dependencies.

Changes

File/Directory Change Summary
.github/codecov.yml Reorganized paths from packages to src directories.
.github/workflows/main.yml Updated npm test command to npm test.
.github/workflows/node.yml Modified npm test command to pnpm -r test after enabling pnpm with corepack.
.gitignore Added *.tsbuildinfo to the ignore list.
.npmrc Added configurations for engine-strict, sign-git-tag, and link-workspace-packages, replacing node-options.
.nvmrc Downgraded Node.js version from 22.1.0 to 21.7.2.
drizzle.config.ts Refactored configuration setup by importing dotenv/config and drizzle-kit's defineConfig function.
drizzle/0000_secret_lady_mastermind.sql Introduced a schema and multiple tables related to various aspects of a game system.
eslint.config.mjs Introduced TypeScript ESLint configuration settings.
package.json Changed package name, updated repository URL, modified start script, removed workspaces, updated dependencies, and added packageManager field.
pnpm-workspace.yaml Included configuration setting specifying all packages in the src/ directory as part of the workspace.
src/cli/... Added ConsoleThread, MessageQueue, and ScheduledThread classes with various functionalities. Updated tsconfig.json and added vite.config copy.ts.
src/connection/index.ts Removed createDataEncryptionPair export.
src/connection/package.json Introduced new package configuration with versioning, dependencies, scripts for linting, building, and testing.
src/connection/src/... Added new functionalities for managing connections, encryption pairs, and message processing.
src/connection/test/Connection.test.ts Introduced tests for functions related to encryption pairs and cipher support.
src/connection/tsconfig.json Updated to include references to various other modules and define compiler options.
src/database/tsconfig.json Updated to include references to tsconfig.base.json, set compilation options, specify files to include and exclude, and add references to external paths.
src/gateway/tsconfig.json Extended base configuration, set compilation options, defined file inclusions and exclusions, and specified project references.
src/mcots/tsconfig.json Introduced configuration settings for TypeScript compilation.
src/nps/package.json Introduced a Node.js package configuration for @rustymotors/nps.
src/patch/package.json Introduced new npm package configuration with metadata, dependencies, devDependencies, scripts, and other settings.
src/schema/brandedPart.schema.ts Introduced schema definition for branded_part table within the mcos schema.

Poem

In the code where changes bloom,
Paths realigned, new scripts in tune.
TypeScript whispers, configs hum,
A game schema where players run.
Rusty motors, engines roar,
With pnpm, we explore.
Code evolves, a rabbit's cheer,
To new heights, we engineer! 🐇🚀

Tip

New Features and Improvements

Review Settings

Introduced new personality profiles for code reviews. Users can now select between "Chill" and "Assertive" review tones to tailor feedback styles according to their preferences. The "Assertive" profile posts more comments and nitpicks the code more aggressively, while the "Chill" profile is more relaxed and posts fewer comments.

AST-based Instructions

CodeRabbit offers customizing reviews based on the Abstract Syntax Tree (AST) pattern matching. Read more about AST-based instructions in the documentation.

Community-driven AST-based Rules

We are kicking off a community-driven initiative to create and share AST-based rules. Users can now contribute their AST-based rules to detect security vulnerabilities, code smells, and anti-patterns. Please see the ast-grep-essentials repository for more information.

New Static Analysis Tools

We are continually expanding our support for static analysis tools. We have added support for biome, hadolint, and ast-grep. Update the settings in your .coderabbit.yaml file or head over to the settings page to enable or disable the tools you want to use.

Tone Settings

Users can now customize CodeRabbit to review code in the style of their favorite characters or personalities. Here are some of our favorite examples:

  • Mr. T: "You must talk like Mr. T in all your code reviews. I pity the fool who doesn't!"
  • Pirate: "Arr, matey! Ye must talk like a pirate in all yer code reviews. Yarrr!"
  • Snarky: "You must be snarky in all your code reviews. Snark, snark, snark!"

Revamped Settings Page

We have redesigned the settings page for a more intuitive layout, enabling users to find and adjust settings quickly. This change was long overdue; it not only improves the user experience but also allows our development team to add more settings in the future with ease. Going forward, the changes to .coderabbit.yaml will be reflected in the settings page, and vice versa.

Miscellaneous

  • Turn off free summarization: You can switch off free summarization of PRs opened by users not on a paid plan using the enable_free_tier setting.
  • Knowledge-base scope: You can now set the scope of the knowledge base to either the repository (local) or the organization (global) level using the knowledge_base setting. In addition, you can specify Jira project keys and Linear team keys to limit the knowledge base scope for those integrations.
  • High-level summary placement: You can now customize the location of the high-level summary in the PR description using the high_level_summary_placeholder setting (default @coderabbitai summary).
  • Revamped request changes workflow: You can now configure CodeRabbit to auto-approve or request changes on PRs based on the review feedback using the request_changes_workflow setting.

Tip

Early Access Features
  • gpt-4o model for chat

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to full the review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

Documentation and Community

  • 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.

libs/connection/src/Connection.ts Fixed Show fixed Hide fixed
libs/connection/src/Connection.ts Fixed Show fixed Hide fixed
libs/connection/src/Connection.ts Fixed Show fixed Hide fixed
Copy link

socket-security bot commented May 14, 2024

👍 Dependency issues cleared. Learn more about Socket for GitHub ↗︎

This PR previously contained dependency changes with security issues that have been resolved, removed, or ignored.

View full report↗︎

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: 42

Out of diff range and nitpick comments (17)
src/database/src/seeders/populateBrand.ts (3)

1-4: Consider adding a comment to describe the purpose of the imports.

Adding comments to describe the purpose of each import can improve code readability and maintainability.


7-9: Consider adding a comment to describe the purpose of the populateBrand function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.


12-13: Consider adding a comment to describe the purpose of the getDatabase call.

Adding a comment to describe the purpose of the getDatabase call can improve code readability and maintainability.

src/database/src/seeders/populateBrandedPart.ts (3)

1-4: Consider adding a comment to describe the purpose of the imports.

Adding comments to describe the purpose of each import can improve code readability and maintainability.


7-9: Consider adding a comment to describe the purpose of the populateBrandedPart function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.


12-13: Consider adding a comment to describe the purpose of the getDatabase call.

Adding a comment to describe the purpose of the getDatabase call can improve code readability and maintainability.

src/database/src/functions/getWarehouseInventory.ts (2)

1-8: Consider adding a comment to describe the purpose of the imports.

Adding comments to describe the purpose of each import can improve code readability and maintainability.


21-24: Consider adding a comment to describe the purpose of the getWarehouseInventory function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.

src/database/src/seeders/populateWarehouse.ts (3)

1-4: Consider adding a comment to describe the purpose of the imports.

Adding comments to describe the purpose of each import can improve code readability and maintainability.


7-9: Consider adding a comment to describe the purpose of the populateWarehouse function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.


12-13: Consider adding a comment to describe the purpose of the getDatabase call.

Adding a comment to describe the purpose of the getDatabase call can improve code readability and maintainability.

src/database/src/seeders/populateModel.ts (3)

1-4: Consider adding a comment to describe the purpose of the imports.

Adding comments to describe the purpose of each import can improve code readability and maintainability.


7-9: Consider adding a comment to describe the purpose of the populateModel function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.


12-13: Consider adding a comment to describe the purpose of the getDatabase call.

Adding a comment to describe the purpose of the getDatabase call can improve code readability and maintainability.

src/gateway/src/handleGameMessage.ts (3)

12-33: Consider adding a comment to describe the purpose of the sendToGameSocket function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.


35-75: Consider adding a comment to describe the purpose of the processGameMessage function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.


77-123: Consider adding a comment to describe the purpose of the handleGameMessage function.

Adding a comment to describe the purpose of the function can improve code readability and maintainability.

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between b8a0fb7 and 60dad23.
Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
Files selected for processing (57)
  • .github/codecov.yml (1 hunks)
  • .github/workflows/main.yml (1 hunks)
  • .github/workflows/node.yml (1 hunks)
  • .gitignore (1 hunks)
  • .npmrc (1 hunks)
  • .nvmrc (1 hunks)
  • drizzle.config.ts (1 hunks)
  • eslint.config.mjs (1 hunks)
  • package.json (1 hunks)
  • pnpm-workspace.yaml (1 hunks)
  • src/cli/ConsoleThread.ts (1 hunks)
  • src/cli/MessageQueue.ts (1 hunks)
  • src/cli/ScheduledThread.ts (1 hunks)
  • src/cli/package.json (1 hunks)
  • src/cli/tsconfig.json (1 hunks)
  • src/cli/vite.config copy.ts (1 hunks)
  • src/cli/vite.config.ts (1 hunks)
  • src/connection/index.ts (1 hunks)
  • src/connection/package.json (1 hunks)
  • src/connection/src/Connection.ts (1 hunks)
  • src/connection/test/Connection.test.ts (1 hunks)
  • src/connection/tsconfig.json (1 hunks)
  • src/connection/vite.config.ts (1 hunks)
  • src/database/package.json (1 hunks)
  • src/database/src/DatabaseManager.ts (5 hunks)
  • src/database/src/functions/createNewCar.ts (1 hunks)
  • src/database/src/functions/getAbstractPartTypeId.ts (1 hunks)
  • src/database/src/functions/getWarehouseInventory.ts (1 hunks)
  • src/database/src/functions/transferPartAssembly.ts (1 hunks)
  • src/database/src/seeders/index.ts (1 hunks)
  • src/database/src/seeders/populateAbstractPartType.ts (1 hunks)
  • src/database/src/seeders/populateBrand.ts (1 hunks)
  • src/database/src/seeders/populateBrandedPart.ts (1 hunks)
  • src/database/src/seeders/populateModel.ts (1 hunks)
  • src/database/src/seeders/populatePartGrade.ts (1 hunks)
  • src/database/src/seeders/populatePartType.ts (1 hunks)
  • src/database/src/seeders/populatePlayer.ts (1 hunks)
  • src/database/src/seeders/populatePlayerType.ts (1 hunks)
  • src/database/src/seeders/populateSkin.ts (1 hunks)
  • src/database/src/seeders/populateSkinType.ts (1 hunks)
  • src/database/src/seeders/populateWarehouse.ts (1 hunks)
  • src/database/test/Database.test.ts (1 hunks)
  • src/database/tsconfig.json (1 hunks)
  • src/database/vite.config.ts (1 hunks)
  • src/gateway/package.json (1 hunks)
  • src/gateway/src/GatewayServer.ts (1 hunks)
  • src/gateway/src/handleGameMessage.ts (1 hunks)
  • src/gateway/src/index.ts (1 hunks)
  • src/gateway/src/web.ts (1 hunks)
  • src/gateway/test/GatewayServer.test.ts (1 hunks)
  • src/gateway/test/socketErrorHandler.test.ts (1 hunks)
  • src/gateway/test/web.test.ts (1 hunks)
  • src/gateway/tsconfig.json (1 hunks)
  • src/gateway/vite.config.ts (1 hunks)
  • src/mcots/ClientConnectionManager.ts (1 hunks)
  • src/mcots/index.ts (1 hunks)
  • src/mcots/messageProcessors/index.ts (2 hunks)
Files not processed due to max files limit (73)
  • src/mcots/messageProcessors/processClientConnect.ts
  • src/mcots/messageProcessors/processClientTracking.ts
  • src/mcots/messageProcessors/processServerLogin.ts
  • src/mcots/messageProcessors/processSetOptions.ts
  • src/mcots/messageProcessors/processStockCarInfo.ts
  • src/mcots/messageProcessors/sendSuccess.ts
  • src/mcots/package.json
  • src/mcots/payloads/ClientConnectMessage.ts
  • src/mcots/payloads/ClientTrackingMessage.ts
  • src/mcots/payloads/LoginCompleteMessage.ts
  • src/mcots/payloads/LoginMessage.ts
  • src/mcots/payloads/SetOptionsMessage.ts
  • src/mcots/payloads/StockCar.ts
  • src/mcots/payloads/index.ts
  • src/mcots/tsconfig.json
  • src/mcots/vite.config.ts
  • src/nps/gameMessageProcessors/getLobMiniRiffList.ts
  • src/nps/gameMessageProcessors/getLobMiniUserList.ts
  • src/nps/gameMessageProcessors/processCheckPlateText.ts
  • src/nps/gameMessageProcessors/processCheckProfileName.ts
  • src/nps/gameMessageProcessors/processCreateProfile.ts
  • src/nps/gameMessageProcessors/processDeleteProfile.ts
  • src/nps/gameMessageProcessors/processEncryptedGameCommand.ts
  • src/nps/gameMessageProcessors/processGameLogin.ts
  • src/nps/gameMessageProcessors/processGetFirstBuddy.ts
  • src/nps/gameMessageProcessors/processGetProfileInfo.ts
  • src/nps/gameMessageProcessors/processGetProfileMaps.ts
  • src/nps/gameMessageProcessors/processPing.ts
  • src/nps/gameMessageProcessors/processSelectPersona.ts
  • src/nps/gameMessageProcessors/processUserLogin.ts
  • src/nps/index.ts
  • src/nps/messageStructs/GameMessage.ts
  • src/nps/messageStructs/GameProfile.ts
  • src/nps/messageStructs/MiniRiffList.ts
  • src/nps/messageStructs/MiniUserList.ts
  • src/nps/messageStructs/NPSList.ts
  • src/nps/messageStructs/ProfileList.ts
  • src/nps/messageStructs/SessionKey.ts
  • src/nps/messageStructs/UserAction.ts
  • src/nps/messageStructs/UserInfo.ts
  • src/nps/package.json
  • src/nps/services/account.ts
  • src/nps/services/profile.ts
  • src/nps/services/token.ts
  • src/nps/services/types.ts
  • src/nps/src/UserStatusManager.ts
  • src/nps/tsconfig.json
  • src/nps/vite.config.ts
  • src/patch/package.json
  • src/patch/src/PatchServer.ts
  • src/patch/test/PatchServer.test.ts
  • src/patch/tsconfig.json
  • src/patch/vite.config.ts
  • src/schema/package.json
  • src/schema/profile.ts
  • src/schema/tsconfig.json
  • src/server/instrument.mts
  • src/server/package.json
  • src/server/server.mts
  • src/server/tsconfig.json
  • src/shard/package.json
  • src/shard/src/index.ts
  • src/shard/tsconfig.json
  • src/shared-packets/index.ts
  • src/shared-packets/package.json
  • src/shared-packets/src/ServerMessage.ts
  • src/shared-packets/test/index.test.ts
  • src/shared-packets/tsconfig.json
  • src/shared/Configuration.ts
  • src/shared/SubThread.ts
  • src/shared/index.ts
  • src/shared/package.json
  • src/shared/src/ServerMessage.ts
Files not reviewed due to errors (4)
  • src/database/src/functions/transferPartAssembly.ts (no review received)
  • src/gateway/src/web.ts (no review received)
  • src/database/src/seeders/index.ts (no review received)
  • src/database/src/functions/createNewCar.ts (no review received)
Files skipped from review due to trivial changes (20)
  • .github/workflows/main.yml
  • .github/workflows/node.yml
  • .gitignore
  • .npmrc
  • .nvmrc
  • package.json
  • pnpm-workspace.yaml
  • src/cli/package.json
  • src/cli/tsconfig.json
  • src/cli/vite.config.ts
  • src/connection/index.ts
  • src/connection/tsconfig.json
  • src/connection/vite.config.ts
  • src/database/package.json
  • src/database/src/seeders/populateAbstractPartType.ts
  • src/database/tsconfig.json
  • src/database/vite.config.ts
  • src/gateway/package.json
  • src/gateway/test/socketErrorHandler.test.ts
  • src/gateway/tsconfig.json
Additional Context Used
GitHub Check Runs (1)
codecov/patch success (30)

src/cli/ConsoleThread.ts: [warning] 27-27: src/cli/ConsoleThread.ts#L27
Added line #L27 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 33-33: src/cli/ConsoleThread.ts#L33
Added line #L33 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 36-36: src/cli/ConsoleThread.ts#L36
Added line #L36 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 39-39: src/cli/ConsoleThread.ts#L39
Added line #L39 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 43-43: src/cli/ConsoleThread.ts#L43
Added line #L43 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 47-47: src/cli/ConsoleThread.ts#L47
Added line #L47 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 50-50: src/cli/ConsoleThread.ts#L50
Added line #L50 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 52-52: src/cli/ConsoleThread.ts#L52
Added line #L52 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 59-59: src/cli/ConsoleThread.ts#L59
Added line #L59 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 62-62: src/cli/ConsoleThread.ts#L62
Added line #L62 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 70-70: src/cli/ConsoleThread.ts#L70
Added line #L70 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 74-74: src/cli/ConsoleThread.ts#L74
Added line #L74 was not covered by tests


src/cli/ConsoleThread.ts: [warning] 81-81: src/cli/ConsoleThread.ts#L81
Added line #L81 was not covered by tests


src/cli/MessageQueue.ts: [warning] 7-69: src/cli/MessageQueue.ts#L7-L69
Added lines #L7 - L69 were not covered by tests


src/cli/ScheduledThread.ts: [warning] 12-53: src/cli/ScheduledThread.ts#L12-L53
Added lines #L12 - L53 were not covered by tests


src/connection/src/Connection.ts: [warning] 81-96: src/connection/src/Connection.ts#L81-L96
Added lines #L81 - L96 were not covered by tests


src/connection/src/Connection.ts: [warning] 106-129: src/connection/src/Connection.ts#L106-L129
Added lines #L106 - L129 were not covered by tests


src/connection/src/Connection.ts: [warning] 133-187: src/connection/src/Connection.ts#L133-L187
Added lines #L133 - L187 were not covered by tests


src/connection/src/Connection.ts: [warning] 191-226: src/connection/src/Connection.ts#L191-L226
Added lines #L191 - L226 were not covered by tests


src/connection/src/Connection.ts: [warning] 230-235: src/connection/src/Connection.ts#L230-L235
Added lines #L230 - L235 were not covered by tests


src/connection/src/Connection.ts: [warning] 239-258: src/connection/src/Connection.ts#L239-L258
Added lines #L239 - L258 were not covered by tests


src/connection/src/Connection.ts: [warning] 262-290: src/connection/src/Connection.ts#L262-L290
Added lines #L262 - L290 were not covered by tests


src/connection/src/Connection.ts: [warning] 294-311: src/connection/src/Connection.ts#L294-L311
Added lines #L294 - L311 were not covered by tests


src/connection/src/Connection.ts: [warning] 317-343: src/connection/src/Connection.ts#L317-L343
Added lines #L317 - L343 were not covered by tests


src/connection/src/Connection.ts: [warning] 349-356: src/connection/src/Connection.ts#L349-L356
Added lines #L349 - L356 were not covered by tests


src/connection/src/Connection.ts: [warning] 360-364: src/connection/src/Connection.ts#L360-L364
Added lines #L360 - L364 were not covered by tests


src/connection/src/Connection.ts: [warning] 367-380: src/connection/src/Connection.ts#L367-L380
Added lines #L367 - L380 were not covered by tests


src/database/src/DatabaseManager.ts: [warning] 35-36: src/database/src/DatabaseManager.ts#L35-L36
Added lines #L35 - L36 were not covered by tests


src/database/src/DatabaseManager.ts: [warning] 48-48: src/database/src/DatabaseManager.ts#L48
Added line #L48 was not covered by tests


src/database/src/DatabaseManager.ts: [warning] 53-53: src/database/src/DatabaseManager.ts#L53
Added line #L53 was not covered by tests

Additional comments not posted (99)
drizzle.config.ts (3)

10-10: Update schema path to reflect new directory structure.


12-12: Update driver value to use double quotes for consistency.


15-15: Ensure the addition of the comma in the dbCredentials object is correct.

src/cli/vite.config copy.ts (5)

6-7: Enable coverage and set to include all files.


8-15: Set coverage exclusions to avoid unnecessary files.


16-17: Specify coverage reporters for different formats.


18-19: Configure test reporters and output file.


20-20: Set test pool to use forks.

src/gateway/vite.config.ts (5)

6-7: Enable coverage and set to include all files.


8-15: Set coverage exclusions to avoid unnecessary files.


16-17: Specify coverage reporters for different formats.


18-19: Configure test reporters and output file.


20-20: Set test pool to use forks.

src/mcots/index.ts (5)

1-1: Export ClientConnectionManager from ClientConnectionManager.js.


2-2: Export ErrorNoKey from errors/ErrorNoKey.js.


3-6: Export message processors from messageProcessors/index.js.


7-7: Export ServerSocketCallback type from messageProcessors/index.js.


8-16: Export payloads from payloads/index.js.

eslint.config.mjs (5)

3-4: Import ESLint and TypeScript ESLint configurations.


12-15: Set parser options for TypeScript projects.


11-11: Set language options for ESLint.


19-19: Specify files to lint.


20-21: Extend ESLint configurations.

src/database/src/seeders/populateSkinType.ts (4)

6-6: Set up logging for the seeder.


12-19: Insert values into the skinType table.


20-20: Handle conflicts by doing nothing.


24-27: Handle errors and log them to Sentry.

src/mcots/ClientConnectionManager.ts (7)

6-11: Singleton pattern implementation looks good.


14-16: Method for adding a connection looks good.


18-20: Method for removing a connection looks good.


22-24: Method for retrieving a connection looks good.


26-28: Method for retrieving all connections looks good.


30-32: Method for clearing all connections looks good.


34-47: Static methods for managing connections look good.

src/database/test/Database.test.ts (3)

9-23: Test case for fetchSessionKeyByCustomerId looks good.


26-41: Test case for fetchSessionKeyByConnectionId looks good.


43-57: Test case for updateUser looks good.

.github/codecov.yml (3)

2-2: Codecov configuration looks good.


5-5: AI PR review configuration looks good.


11-80: Path updates in flags and component_management sections look good.

src/cli/MessageQueue.ts (6)

20-40: Constructor implementation looks good.


42-47: Initialization method looks good.


49-51: Method for adding a message looks good.


53-55: Method for retrieving and removing a message looks good.


57-61: Run method implementation looks good.


63-68: Stop method implementation looks good.

src/cli/ConsoleThread.ts (5)

23-35: Constructor implementation looks good.


37-51: Method for handling keypress events looks good.


53-69: Initialization method looks good.


71-73: Run method implementation looks good.


75-80: Stop method implementation looks good.

src/database/src/seeders/populateSkin.ts (1)

7-90: Ensure the correctness of the data being inserted.

Please verify that the data being inserted into the skinSchema is accurate and complete. This includes checking the values for each field to ensure they match the expected data format and constraints.

src/connection/test/Connection.test.ts (2)

12-25: Test cases for createCommandEncryptionPair are well-written.

The test cases cover both valid and invalid key scenarios effectively.


54-69: Test cases for verifyLegacyCipherSupport are comprehensive.

The test cases effectively cover scenarios where required ciphers are available and unavailable.

src/database/src/seeders/populatePlayer.ts (1)

8-81: Ensure the correctness of the data being inserted.

Please verify that the data being inserted into the playerSchema is accurate and complete. This includes checking the values for each field to ensure they match the expected data format and constraints.

src/gateway/test/GatewayServer.test.ts (1)

5-91: Test cases for getGatewayServer are well-written.

The test cases effectively cover scenarios with multiple ports, a single port, and no ports.

src/database/src/seeders/populatePartType.ts (1)

7-95: Ensure the correctness of the data being inserted.

Please verify that the data being inserted into the partTypeSchema is accurate and complete. This includes checking the values for each field to ensure they match the expected data format and constraints.

src/database/src/DatabaseManager.ts (1)

66-85: Function updateSessionKey looks good.

The function correctly updates the session key data.

src/gateway/src/index.ts (2)

32-50: LGTM! The socketErrorHandler function correctly handles and logs socket errors.


52-67: LGTM! The socketEndHandler function correctly handles and logs the end of a socket connection.

src/gateway/src/GatewayServer.ts (39)

1-1: Ensure all imported modules are necessary and used in the file.

Verify that ConsoleThread and ScheduledThread from @rustymotors/cli are used in the file.


2-8: Ensure all imported types and functions from @rustymotors/shared are necessary and used in the file.

Verify that Configuration, getServerConfiguration, TGateway, TGatewayOptions, and TServerLogger are used in the file.


9-9: Ensure fastify import is necessary and used in the file.

Verify that fastify is used in the file.


10-10: Ensure Socket and createServer from node:net are necessary and used in the file.

Verify that Socket and createServer are used in the file.


11-12: Ensure onSocketConnection and addWebRoutes are necessary and used in the file.

Verify that onSocketConnection and addWebRoutes are used in the file.


14-14: Ensure FastifySensible import is necessary and used in the file.

Verify that FastifySensible is used in the file.


16-27: Ensure all imported functions from @rustymotors/database are necessary and used in the file.

Verify that populateAbstractPartType, populateBrand, populateBrandedPart, populateModel, populatePartGrade, populatePartType, populatePlayer, populatePlayerType, populateSkin, and populateSkinType are used in the file.


28-36: Ensure all imported functions from @rustymotors/nps are necessary and used in the file.

Verify that gameMessageProcessors, gameProfiles, populateGameMessageProcessors, populateGameProfiles, populateGameUsers, and populatePortToMessageTypes are used in the file.


37-37: Ensure populateServerMessageProcessors from @rustymotors/mcots is necessary and used in the file.

Verify that populateServerMessageProcessors is used in the file.


48-48: Ensure config property is necessary and correctly initialized.

Verify that config is used in the class and correctly initialized.


49-49: Ensure log property is necessary and correctly initialized.

Verify that log is used in the class and correctly initialized.


50-50: Ensure timer property is necessary and correctly initialized.

Verify that timer is used in the class and correctly initialized.


51-51: Ensure loopInterval property is necessary and correctly initialized.

Verify that loopInterval is used in the class and correctly initialized.


52-52: Ensure status property is necessary and correctly initialized.

Verify that status is used in the class and correctly initialized.


53-53: Ensure consoleEvents property is necessary and correctly initialized.

Verify that consoleEvents is used in the class and correctly initialized.


54-54: Ensure backlogAllowedCount property is necessary and correctly initialized.

Verify that backlogAllowedCount is used in the class and correctly initialized.


55-55: Ensure listeningPortList property is necessary and correctly initialized.

Verify that listeningPortList is used in the class and correctly initialized.


56-56: Ensure servers property is necessary and correctly initialized.

Verify that servers is used in the class and correctly initialized.


57-63: Ensure socketconnection property is necessary and correctly initialized.

Verify that socketconnection is used in the class and correctly initialized.


64-64: Ensure _instance static property is necessary and correctly initialized.

Verify that _instance is used in the class and correctly initialized.


65-65: Ensure webServer property is necessary and correctly initialized.

Verify that webServer is used in the class and correctly initialized.


66-66: Ensure readThread property is necessary and correctly initialized.

Verify that readThread is used in the class and correctly initialized.


67-67: Ensure scheduledThread property is necessary and correctly initialized.

Verify that scheduledThread is used in the class and correctly initialized.


73-101: Ensure the constructor correctly initializes all properties and handles errors appropriately.

Verify that the constructor correctly initializes config, log, backlogAllowedCount, listeningPortList, socketConnectionHandler, and handles errors appropriately.


106-108: Ensure deleteInstance method is necessary and correctly implemented.

Verify that deleteInstance is used in the class and correctly implemented.


110-122: Ensure verifyPortListIsNotEmpty method is necessary and correctly implemented.

Verify that verifyPortListIsNotEmpty is used in the class and correctly implemented.


127-132: Ensure getWebServer method is necessary and correctly implemented.

Verify that getWebServer is used in the class and correctly implemented.


134-179: Ensure start method is necessary and correctly implemented.

Verify that start is used in the class and correctly implemented.


181-189: Ensure restart method is necessary and correctly implemented.

Verify that restart is used in the class and correctly implemented.


191-197: Ensure exit method is necessary and correctly implemented.

Verify that exit is used in the class and correctly implemented.


199-234: Ensure stop method is necessary and correctly implemented.

Verify that stop is used in the class and correctly implemented.


239-249: Ensure handleReadThreadEvent method is necessary and correctly implemented.

Verify that handleReadThreadEvent is used in the class and correctly implemented.


251-306: Ensure init method is necessary and correctly implemented.

Verify that init is used in the class and correctly implemented.


308-314: Ensure help method is necessary and correctly implemented.

Verify that help is used in the class and correctly implemented.


315-317: Ensure run method is necessary and correctly implemented.

Verify that run is used in the class and correctly implemented.


325-341: Ensure getInstance method is necessary and correctly implemented.

Verify that getInstance is used in the class and correctly implemented.


344-350: Ensure shutdown method is necessary and correctly implemented.

Verify that shutdown is used in the class and correctly implemented.


353-354: Ensure _instance static property is necessary and correctly initialized.

Verify that _instance is used in the class and correctly initialized.


362-388: Ensure getGatewayServer function is necessary and correctly implemented.

Verify that getGatewayServer is used in the file and correctly implemented.

Comment on lines +28 to +36
userId: number;
userData: Buffer;
}): Promise<void> {
try {
_users.set(user.userId, user.userData);
return Promise.resolve();
} catch (error) {
throw Error(`Error updating user: ${String(error)}`);
}
try {
_users.set(user.userId, user.userData);
return Promise.resolve();
} catch (error) {
throw Error(`Error updating user: ${String(error)}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling in updateUser.

-    throw Error(`Error updating user: ${String(error)}`);
+    throw new Error(`Error updating user with ID ${user.userId}: ${String(error)}`);

Providing more context in the error message helps with debugging.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
userId: number;
userData: Buffer;
}): Promise<void> {
try {
_users.set(user.userId, user.userData);
return Promise.resolve();
} catch (error) {
throw Error(`Error updating user: ${String(error)}`);
}
try {
_users.set(user.userId, user.userData);
return Promise.resolve();
} catch (error) {
throw Error(`Error updating user: ${String(error)}`);
}
userId: number;
userData: Buffer;
}): Promise<void> {
try {
_users.set(user.userId, user.userData);
return Promise.resolve();
} catch (error) {
throw new Error(`Error updating user with ID ${user.userId}: ${String(error)}`);
}

Comment on lines +40 to +62
export function createCommandEncryptionPair(key: string): McosEncryptionPair {
if (key.length < 16) {
log.error(`Key too short: length ${key.length.toString()}, value ${key}`);
throw Error(`Key too short: length ${key.length.toString()}, value ${key}`);
}

const sKey = key.slice(0, 16);

// Deepcode ignore HardcodedSecret: This uses an empty IV
const desIV = Buffer.alloc(8);

const gsCipher = createCipheriv("des-cbc", Buffer.from(sKey, "hex"), desIV);
gsCipher.setAutoPadding(false);

const gsDecipher = createDecipheriv(
"des-cbc",
Buffer.from(sKey, "hex"),
desIV
);
gsDecipher.setAutoPadding(false);

return new McosEncryptionPair(gsCipher, gsDecipher);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid using insecure ciphers like DES-CBC and RC4.

The use of DES-CBC and RC4 ciphers is considered insecure by modern cryptographic standards. It is recommended to use more secure algorithms like AES.

-  const gsCipher = createCipheriv("des-cbc", Buffer.from(sKey, "hex"), desIV);
+  const gsCipher = createCipheriv("aes-256-cbc", Buffer.from(sKey, "hex"), desIV);
-  const gsDecipher = createDecipheriv("des-cbc", Buffer.from(sKey, "hex"), desIV);
+  const gsDecipher = createDecipheriv("aes-256-cbc", Buffer.from(sKey, "hex"), desIV);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export function createCommandEncryptionPair(key: string): McosEncryptionPair {
if (key.length < 16) {
log.error(`Key too short: length ${key.length.toString()}, value ${key}`);
throw Error(`Key too short: length ${key.length.toString()}, value ${key}`);
}
const sKey = key.slice(0, 16);
// Deepcode ignore HardcodedSecret: This uses an empty IV
const desIV = Buffer.alloc(8);
const gsCipher = createCipheriv("des-cbc", Buffer.from(sKey, "hex"), desIV);
gsCipher.setAutoPadding(false);
const gsDecipher = createDecipheriv(
"des-cbc",
Buffer.from(sKey, "hex"),
desIV
);
gsDecipher.setAutoPadding(false);
return new McosEncryptionPair(gsCipher, gsDecipher);
}
export function createCommandEncryptionPair(key: string): McosEncryptionPair {
if (key.length < 16) {
log.error(`Key too short: length ${key.length.toString()}, value ${key}`);
throw Error(`Key too short: length ${key.length.toString()}, value ${key}`);
}
const sKey = key.slice(0, 16);
// Deepcode ignore HardcodedSecret: This uses an empty IV
const desIV = Buffer.alloc(8);
const gsCipher = createCipheriv("aes-256-cbc", Buffer.from(sKey, "hex"), desIV);
gsCipher.setAutoPadding(false);
const gsDecipher = createDecipheriv(
"aes-256-cbc",
Buffer.from(sKey, "hex"),
desIV
);
gsDecipher.setAutoPadding(false);
return new McosEncryptionPair(gsCipher, gsDecipher);
}

Comment on lines +45 to +53
customerId: number
): Promise<ConnectionRecord> {
const record = _sessions.find((session) => {
return session.customerId === customerId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for customer ${customerId}`);
}
return Promise.resolve(record);
const record = _sessions.find((session) => {
return session.customerId === customerId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for customer ${customerId}`);
}
return Promise.resolve(record);
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling in fetchSessionKeyByCustomerId.

-    throw Error(`Session key not found for customer ${customerId}`);
+    throw new Error(`Session key not found for customer ID ${customerId}`);

Providing more context in the error message helps with debugging.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
customerId: number
): Promise<ConnectionRecord> {
const record = _sessions.find((session) => {
return session.customerId === customerId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for customer ${customerId}`);
}
return Promise.resolve(record);
const record = _sessions.find((session) => {
return session.customerId === customerId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for customer ${customerId}`);
}
return Promise.resolve(record);
customerId: number
): Promise<ConnectionRecord> {
const record = _sessions.find((session) => {
return session.customerId === customerId;
});
if (typeof record === "undefined") {
throw new Error(`Session key not found for customer ID ${customerId}`);
}
return Promise.resolve(record);

Comment on lines +96 to +104
connectionId: string
): Promise<ConnectionRecord> {
const record = _sessions.find((session) => {
return session.connectionId === connectionId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for connection ${connectionId}`);
}
return Promise.resolve(record);
const record = _sessions.find((session) => {
return session.connectionId === connectionId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for connection ${connectionId}`);
}
return Promise.resolve(record);
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling in fetchSessionKeyByConnectionId.

-    throw Error(`Session key not found for connection ${connectionId}`);
+    throw new Error(`Session key not found for connection ID ${connectionId}`);

Providing more context in the error message helps with debugging.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
connectionId: string
): Promise<ConnectionRecord> {
const record = _sessions.find((session) => {
return session.connectionId === connectionId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for connection ${connectionId}`);
}
return Promise.resolve(record);
const record = _sessions.find((session) => {
return session.connectionId === connectionId;
});
if (typeof record === "undefined") {
throw Error(`Session key not found for connection ${connectionId}`);
}
return Promise.resolve(record);
connectionId: string
): Promise<ConnectionRecord> {
const record = _sessions.find((session) => {
return session.connectionId === connectionId;
});
if (typeof record === "undefined") {
throw new Error(`Session key not found for connection ID ${connectionId}`);
}
return Promise.resolve(record);

Comment on lines +70 to +78
export function verifyLegacyCipherSupport() {
const cipherList = getCiphers();
if (!cipherList.includes("des-cbc")) {
throw Error("DES-CBC cipher not available");
}
if (!cipherList.includes("rc4")) {
throw Error("RC4 cipher not available");
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Reconsider the necessity of supporting legacy ciphers.

The function verifyLegacyCipherSupport checks for DES-CBC and RC4 ciphers, which are insecure. It is advisable to remove support for these ciphers and use modern alternatives like AES.

-  if (!cipherList.includes("des-cbc")) {
-    throw Error("DES-CBC cipher not available");
-  }
-  if (!cipherList.includes("rc4")) {
-    throw Error("RC4 cipher not available");
-  }
+  if (!cipherList.includes("aes-256-cbc")) {
+    throw Error("AES-256-CBC cipher not available");
+  }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export function verifyLegacyCipherSupport() {
const cipherList = getCiphers();
if (!cipherList.includes("des-cbc")) {
throw Error("DES-CBC cipher not available");
}
if (!cipherList.includes("rc4")) {
throw Error("RC4 cipher not available");
}
}
export function verifyLegacyCipherSupport() {
const cipherList = getCiphers();
if (!cipherList.includes("aes-256-cbc")) {
throw Error("AES-256-CBC cipher not available");
}
}

Comment on lines +120 to +123
.catch((error: Error) => {
log.error(`Error seeding warehouse: ${error.message}`);
Sentry.captureException(error);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding more context to the error message.

Providing more context in the error message can help with debugging. For example, include the warehouse data that caused the error.

- log.error(`Error seeding warehouse: ${error.message}`);
+ log.error(`Error seeding warehouse with data ${JSON.stringify(wareHouseSchema)}: ${error.message}`);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
.catch((error: Error) => {
log.error(`Error seeding warehouse: ${error.message}`);
Sentry.captureException(error);
});
.catch((error: Error) => {
log.error(`Error seeding warehouse with data ${JSON.stringify(wareHouseSchema)}: ${error.message}`);
Sentry.captureException(error);
});

Comment on lines +77 to +149
export function onSocketConnection({
incomingSocket,
log,
}: {
incomingSocket: Socket;
log: TServerLogger;
}) {
log.setName("gateway:onSocketConnection");

// Get the local port and remote address
const { localPort, remoteAddress } = incomingSocket;

if (localPort === undefined || remoteAddress === undefined) {
log.error("localPort or remoteAddress is undefined");
throw new Error("localPort or remoteAddress is undefined");
}

// This is a new connection so generate a new connection ID
const connectionId = randomUUID();

const userStatus = UserStatusManager.newUserStatus();

if (localPort === 43300) {
log.info("New connection on port 43300");
ClientConnectionManager.addConnection(
new Connection(incomingSocket, connectionId, log)
);
return;
}

incomingSocket.on("error", (error) =>
socketErrorHandler({ connectionId: connectionId, error, log })
);

// Add the data handler to the socket
incomingSocket.on("data", (incomingDataAsBuffer: Buffer) => {
// Get message type from the port
let messageType = "Unknown";
try {
messageType = getPortMessageType(localPort);
log.debug(`Message type: ${messageType}`);
} catch (error) {
log.error(`Error getting message type: ${(error as Error).message}`);
throw error;
}

if (messageType !== "Unknown") {
// Call the message handler
if (messageType === "Game") {
const gameSocketCallback = (messages: Buffer[]) => {
sendToGameSocket(messages, incomingSocket, log);
};

return handleGameMessage(
connectionId,
userStatus,
incomingDataAsBuffer,
log,
gameSocketCallback
);
}
}
});

log.debug(`Client ${remoteAddress} connected to port ${localPort}`);

if (localPort === 7003) {
log.info("Sending ok to login packet");

incomingSocket.write(Buffer.from([0x02, 0x30, 0x00, 0x00]));
}
log.resetName();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling for ClientConnectionManager.addConnection to ensure robustness.

+ try {
    ClientConnectionManager.addConnection(
      new Connection(incomingSocket, connectionId, log)
    );
+ } catch (error) {
+   log.error(`Error adding connection: ${error.message}`);
+   throw error;
+ }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export function onSocketConnection({
incomingSocket,
log,
}: {
incomingSocket: Socket;
log: TServerLogger;
}) {
log.setName("gateway:onSocketConnection");
// Get the local port and remote address
const { localPort, remoteAddress } = incomingSocket;
if (localPort === undefined || remoteAddress === undefined) {
log.error("localPort or remoteAddress is undefined");
throw new Error("localPort or remoteAddress is undefined");
}
// This is a new connection so generate a new connection ID
const connectionId = randomUUID();
const userStatus = UserStatusManager.newUserStatus();
if (localPort === 43300) {
log.info("New connection on port 43300");
ClientConnectionManager.addConnection(
new Connection(incomingSocket, connectionId, log)
);
return;
}
incomingSocket.on("error", (error) =>
socketErrorHandler({ connectionId: connectionId, error, log })
);
// Add the data handler to the socket
incomingSocket.on("data", (incomingDataAsBuffer: Buffer) => {
// Get message type from the port
let messageType = "Unknown";
try {
messageType = getPortMessageType(localPort);
log.debug(`Message type: ${messageType}`);
} catch (error) {
log.error(`Error getting message type: ${(error as Error).message}`);
throw error;
}
if (messageType !== "Unknown") {
// Call the message handler
if (messageType === "Game") {
const gameSocketCallback = (messages: Buffer[]) => {
sendToGameSocket(messages, incomingSocket, log);
};
return handleGameMessage(
connectionId,
userStatus,
incomingDataAsBuffer,
log,
gameSocketCallback
);
}
}
});
log.debug(`Client ${remoteAddress} connected to port ${localPort}`);
if (localPort === 7003) {
log.info("Sending ok to login packet");
incomingSocket.write(Buffer.from([0x02, 0x30, 0x00, 0x00]));
}
log.resetName();
}
export function onSocketConnection({
incomingSocket,
log,
}: {
incomingSocket: Socket;
log: TServerLogger;
}) {
log.setName("gateway:onSocketConnection");
// Get the local port and remote address
const { localPort, remoteAddress } = incomingSocket;
if (localPort === undefined || remoteAddress === undefined) {
log.error("localPort or remoteAddress is undefined");
throw new Error("localPort or remoteAddress is undefined");
}
// This is a new connection so generate a new connection ID
const connectionId = randomUUID();
const userStatus = UserStatusManager.newUserStatus();
if (localPort === 43300) {
log.info("New connection on port 43300");
try {
ClientConnectionManager.addConnection(
new Connection(incomingSocket, connectionId, log)
);
} catch (error) {
log.error(`Error adding connection: ${error.message}`);
throw error;
}
return;
}
incomingSocket.on("error", (error) =>
socketErrorHandler({ connectionId: connectionId, error, log })
);
// Add the data handler to the socket
incomingSocket.on("data", (incomingDataAsBuffer: Buffer) => {
// Get message type from the port
let messageType = "Unknown";
try {
messageType = getPortMessageType(localPort);
log.debug(`Message type: ${messageType}`);
} catch (error) {
log.error(`Error getting message type: ${(error as Error).message}`);
throw error;
}
if (messageType !== "Unknown") {
// Call the message handler
if (messageType === "Game") {
const gameSocketCallback = (messages: Buffer[]) => {
sendToGameSocket(messages, incomingSocket, log);
};
return handleGameMessage(
connectionId,
userStatus,
incomingDataAsBuffer,
log,
gameSocketCallback
);
}
}
});
log.debug(`Client ${remoteAddress} connected to port ${localPort}`);
if (localPort === 7003) {
log.info("Sending ok to login packet");
incomingSocket.write(Buffer.from([0x02, 0x30, 0x00, 0x00]));
}
log.resetName();
}

Comment on lines +119 to +122
.catch((error: Error) => {
log.error(`Error seeding model: ${error.message}`);
Sentry.captureException(error);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding more context to the error message.

Providing more context in the error message can help with debugging. For example, include the model data that caused the error.

- log.error(`Error seeding model: ${error.message}`);
+ log.error(`Error seeding model with data ${JSON.stringify(modelSchema)}: ${error.message}`);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
.catch((error: Error) => {
log.error(`Error seeding model: ${error.message}`);
Sentry.captureException(error);
});
.catch((error: Error) => {
log.error(`Error seeding model with data ${JSON.stringify(modelSchema)}: ${error.message}`);
Sentry.captureException(error);
});

Comment on lines +119 to +121
const err = `Error processing game message: ${(error as Error).message}`;
log.fatal(err);
throw Error(err);
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding more context to the error message.

Providing more context in the error message can help with debugging. For example, include the connection ID and user status.

- log.fatal(err);
+ log.fatal(`Error processing game message for connection ${connectionId} and user status ${userStatus}: ${err}`);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const err = `Error processing game message: ${(error as Error).message}`;
log.fatal(err);
throw Error(err);
const err = `Error processing game message: ${(error as Error).message}`;
log.fatal(`Error processing game message for connection ${connectionId} and user status ${userStatus}: ${err}`);
throw Error(err);

Comment on lines +111 to +139
// Add the data handler to the socket
incomingSocket.on("data", (incomingDataAsBuffer: Buffer) => {
// Get message type from the port
let messageType = "Unknown";
try {
messageType = getPortMessageType(localPort);
log.debug(`Message type: ${messageType}`);
} catch (error) {
log.error(`Error getting message type: ${(error as Error).message}`);
throw error;
}

if (messageType !== "Unknown") {
// Call the message handler
if (messageType === "Game") {
const gameSocketCallback = (messages: Buffer[]) => {
sendToGameSocket(messages, incomingSocket, log);
};

return handleGameMessage(
connectionId,
userStatus,
incomingDataAsBuffer,
log,
gameSocketCallback
);
}
}
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding logging for incoming data to aid in debugging.

incomingSocket.on("data", (incomingDataAsBuffer: Buffer) => {
+ log.debug(`Received data: ${incomingDataAsBuffer.toString('hex')}`);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
// Add the data handler to the socket
incomingSocket.on("data", (incomingDataAsBuffer: Buffer) => {
// Get message type from the port
let messageType = "Unknown";
try {
messageType = getPortMessageType(localPort);
log.debug(`Message type: ${messageType}`);
} catch (error) {
log.error(`Error getting message type: ${(error as Error).message}`);
throw error;
}
if (messageType !== "Unknown") {
// Call the message handler
if (messageType === "Game") {
const gameSocketCallback = (messages: Buffer[]) => {
sendToGameSocket(messages, incomingSocket, log);
};
return handleGameMessage(
connectionId,
userStatus,
incomingDataAsBuffer,
log,
gameSocketCallback
);
}
}
});
// Add the data handler to the socket
incomingSocket.on("data", (incomingDataAsBuffer: Buffer) => {
log.debug(`Received data: ${incomingDataAsBuffer.toString('hex')}`);
// Get message type from the port
let messageType = "Unknown";
try {
messageType = getPortMessageType(localPort);
log.debug(`Message type: ${messageType}`);
} catch (error) {
log.error(`Error getting message type: ${(error as Error).message}`);
throw error;
}
if (messageType !== "Unknown") {
// Call the message handler
if (messageType === "Game") {
const gameSocketCallback = (messages: Buffer[]) => {
sendToGameSocket(messages, incomingSocket, log);
};
return handleGameMessage(
connectionId,
userStatus,
incomingDataAsBuffer,
log,
gameSocketCallback
);
}
}
});

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 60dad23 and 26635fd.
Files selected for processing (1)
  • .github/workflows/node.yml (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • .github/workflows/node.yml

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 26635fd and 47cb2aa.
Files selected for processing (1)
  • .github/workflows/node.yml (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • .github/workflows/node.yml

…hard, schema, shared, gateway, and connection
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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 47cb2aa and 226b7ed.
Files selected for processing (3)
  • .github/workflows/node.yml (1 hunks)
  • src/connection/package.json (1 hunks)
  • src/connection/vite.config.ts (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • .github/workflows/node.yml
  • src/connection/package.json
  • src/connection/vite.config.ts

…hard, schema, shared, gateway, and connection
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: 4

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 226b7ed and fcb1f7b.
Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
Files selected for processing (47)
  • src/cli/eslint.config.mjs (1 hunks)
  • src/cli/index.ts (1 hunks)
  • src/cli/package.json (1 hunks)
  • src/cli/src/ConsoleThread.ts (1 hunks)
  • src/cli/src/MessageQueue.ts (1 hunks)
  • src/cli/src/ScheduledThread.ts (1 hunks)
  • src/cli/tsconfig.json (1 hunks)
  • src/connection/eslint.config.mjs (1 hunks)
  • src/connection/package.json (1 hunks)
  • src/connection/tsconfig.json (1 hunks)
  • src/database/eslint.config.mjs (1 hunks)
  • src/database/package.json (1 hunks)
  • src/database/tsconfig.json (1 hunks)
  • src/gateway/eslint.config.mjs (1 hunks)
  • src/gateway/package.json (1 hunks)
  • src/gateway/tsconfig.json (1 hunks)
  • src/mcots/eslint.config.mjs (1 hunks)
  • src/mcots/package.json (1 hunks)
  • src/mcots/payloads/ClientConnectMessage.ts (1 hunks)
  • src/mcots/payloads/ClientTrackingMessage.ts (1 hunks)
  • src/mcots/payloads/LoginCompleteMessage.ts (1 hunks)
  • src/mcots/payloads/LoginMessage.ts (1 hunks)
  • src/mcots/payloads/SetOptionsMessage.ts (1 hunks)
  • src/mcots/tsconfig.json (1 hunks)
  • src/nps/eslint.config.mjs (1 hunks)
  • src/nps/package.json (1 hunks)
  • src/nps/tsconfig.json (1 hunks)
  • src/patch/eslint.config.mjs (1 hunks)
  • src/patch/package.json (1 hunks)
  • src/patch/src/PatchServer.ts (1 hunks)
  • src/patch/tsconfig.json (1 hunks)
  • src/schema/eslint.config.mjs (1 hunks)
  • src/schema/package.json (1 hunks)
  • src/schema/tsconfig.json (1 hunks)
  • src/server/eslint.config.mjs (1 hunks)
  • src/server/package.json (1 hunks)
  • src/server/tsconfig.json (1 hunks)
  • src/shard/eslint.config.mjs (1 hunks)
  • src/shard/package.json (1 hunks)
  • src/shard/src/index.ts (4 hunks)
  • src/shard/src/shard-entry.ts (1 hunks)
  • src/shard/tsconfig.json (1 hunks)
  • src/shared-packets/eslint.config.mjs (1 hunks)
  • src/shared-packets/index.ts (1 hunks)
  • src/shared-packets/package.json (1 hunks)
  • src/shared-packets/src/BasePacket.ts (1 hunks)
  • src/shared-packets/src/ServerMessage.ts (1 hunks)
Files skipped from review due to trivial changes (10)
  • src/mcots/package.json
  • src/mcots/tsconfig.json
  • src/nps/package.json
  • src/nps/tsconfig.json
  • src/patch/package.json
  • src/schema/package.json
  • src/server/package.json
  • src/shard/package.json
  • src/shared-packets/index.ts
  • src/shared-packets/package.json
Files skipped from review as they are similar to previous changes (8)
  • src/cli/package.json
  • src/cli/tsconfig.json
  • src/connection/package.json
  • src/connection/tsconfig.json
  • src/database/package.json
  • src/database/tsconfig.json
  • src/gateway/package.json
  • src/gateway/tsconfig.json
Additional Context Used
GitHub Check Runs (1)
codecov/patch failure (30)

src/cli/index.ts: [warning] 2-2: src/cli/index.ts#L2
Added line #L2 was not covered by tests


src/cli/src/ConsoleThread.ts: [warning] 2-81: src/cli/src/ConsoleThread.ts#L2-L81
Added lines #L2 - L81 were not covered by tests


src/cli/src/MessageQueue.ts: [warning] 2-69: src/cli/src/MessageQueue.ts#L2-L69
Added lines #L2 - L69 were not covered by tests


src/cli/src/ScheduledThread.ts: [warning] 2-53: src/cli/src/ScheduledThread.ts#L2-L53
Added lines #L2 - L53 were not covered by tests

Additional comments not posted (49)
src/cli/index.ts (1)

1-1: Export of ScheduledThread looks good.

src/shard/tsconfig.json (1)

1-13: TypeScript configuration settings are correctly set up.

src/schema/tsconfig.json (1)

1-17: Configuration settings for the schema directory are appropriately set.

src/patch/tsconfig.json (1)

1-17: TypeScript configuration in the patch directory is consistent with project standards.

src/server/tsconfig.json (1)

1-20: Server module TypeScript configuration correctly includes necessary references to other modules.

src/cli/eslint.config.mjs (1)

1-25: ESLint configuration for the CLI module is robust and well-defined.

src/connection/eslint.config.mjs (1)

1-25: ESLint configuration for the connection module maintains consistent coding standards with the rest of the project.

src/database/eslint.config.mjs (1)

1-25: ESLint configuration for the database module is consistent and ensures uniform coding practices across the project.

src/gateway/eslint.config.mjs (1)

1-25: Configuration setup looks good and adheres to best practices for TypeScript projects.

src/mcots/eslint.config.mjs (1)

1-25: Configuration setup is consistent with other modules, promoting maintainability and standardization.

src/nps/eslint.config.mjs (1)

1-25: Consistent ESLint configuration across modules enhances project maintainability.

src/patch/eslint.config.mjs (1)

1-25: Configuration adheres to established patterns, ensuring consistency across the monorepo.

src/schema/eslint.config.mjs (1)

1-25: Unified ESLint configuration across the project promotes a consistent coding style.

src/server/eslint.config.mjs (1)

1-25: Consistent ESLint configuration ensures high code quality across the project.

src/shard/eslint.config.mjs (1)

1-25: Configuration supports scalability and maintainability by adhering to consistent standards.

src/shared-packets/eslint.config.mjs (1)

1-25: Configuration ensures interoperability and consistent standards across the project.

src/mcots/payloads/ClientTrackingMessage.ts (3)

10-14: Ensure proper initialization of buffer size in constructor.


20-34: Handle exceptions gracefully in deserialize method.


37-39: Getter methods are correctly implemented.

src/shared-packets/src/BasePacket.ts (3)

7-11: Ensure hexadecimal conversion handles odd byte lengths correctly.


13-18: Proper error handling in _assertEnoughData.


38-47: Ensure BasePacket correctly concatenates header and data in serialize.

src/cli/src/ScheduledThread.ts (4)

18-32: Ensure parentThread is not undefined before assignment.


34-39: Proper logging and initialization in init method.


41-45: Placeholder for future implementation in run method.


47-52: Correct shutdown sequence in stop method.

src/cli/src/MessageQueue.ts (4)

20-40: Ensure parentThread is not undefined before assignment and handle singleton pattern correctly.


42-47: Proper logging and initialization in init method.


49-55: Message handling methods are implemented correctly.


57-68: Placeholder for future implementation in run method and correct shutdown sequence in stop method.

src/mcots/payloads/ClientConnectMessage.ts (3)

13-17: Ensure proper initialization of buffer size in constructor.


23-45: Handle exceptions gracefully in deserialize method.


48-66: Getter methods are correctly implemented.

src/cli/src/ConsoleThread.ts (4)

23-35: Ensure parentThread is not undefined before assignment.


37-51: Handle keypress events correctly and ensure proper event emission.


53-69: Proper logging and initialization in init method.


71-80: Placeholder for future implementation in run method and correct shutdown sequence in stop method.

src/mcots/payloads/SetOptionsMessage.ts (3)

19-23: Ensure proper initialization of buffer size in constructor.


29-52: Handle exceptions gracefully in deserialize method.


55-77: Getter methods and toString method are correctly implemented.

src/mcots/payloads/LoginMessage.ts (3)

15-19: Ensure proper initialization of buffer size in constructor.


25-49: Handle exceptions gracefully in deserialize method.


52-81: Getter methods and toString method are correctly implemented.

src/patch/src/PatchServer.ts (3)

22-108: Singleton pattern usage in PatchServer class.

The singleton pattern is correctly implemented using a private constructor and a static method to ensure only one instance of PatchServer is created. This is a common pattern for services that should only have a single instance.


71-86: Ensure proper logging and response handling in castanetResponse.

The method logs the request details and sets the response headers and body correctly. However, ensure that the logging level and information are appropriate for production environments.


94-107: Review routing logic in handleRequest.

The routing logic correctly handles specific URLs by delegating to castanetResponse and sets a 404 status code for other URLs. This is a straightforward and effective way to handle routing in a small HTTP server.

src/shard/src/index.ts (1)

45-49: Review registry configuration generation in handleGetRegistry.

The function generates a Windows registry configuration string based on the provided configuration. This is a specialized function that appears to correctly format the registry settings for a specific application.

src/shard/src/shard-entry.ts (1)

93-105: Review formatting in formatForShardList.

The method correctly formats the shard entry properties into a structured string. This is useful for displaying shard information in a consistent format.

src/shared-packets/src/ServerMessage.ts (1)

27-46: Review serialization and deserialization methods in ServerMessageHeader.

The methods correctly handle the serialization and deserialization of the message header. The use of little-endian format and handling of different data types (e.g., integers, strings) is appropriate for network communications.

@@ -0,0 +1,2 @@
export { ScheduledThread } from "./src/ScheduledThread.js";
export { ConsoleThread } from "./src/ConsoleThread.js";
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Several files in the codebase reference ConsoleThread, but no test files directly reference it.

  • src/gateway/src/GatewayServer.ts uses ConsoleThread.
  • src/cli/src/ConsoleThread.ts defines ConsoleThread.

It appears that ConsoleThread is not directly covered by tests. Please ensure that ConsoleThread is explicitly tested to verify its functionality.

Analysis chain

Ensure ConsoleThread is covered by tests.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify if `ConsoleThread` is covered by tests.

# Test: Search for test files that include `ConsoleThread`. Expect: At least one match.
rg --type python $'ConsoleThread' --glob '*test*'

Length of output: 79



Script:

#!/bin/bash
# Description: Verify if `ConsoleThread` is covered by tests.

# Test: Search for test files that include `ConsoleThread`. Expect: At least one match.
rg --type ts 'ConsoleThread' --glob '*test*'

Length of output: 44



Script:

#!/bin/bash
# Description: Locate all test files and search for `ConsoleThread` within them.

# Step 1: Locate all test files.
test_files=$(fd --type f --glob '*test*.ts')

# Step 2: Search for `ConsoleThread` within the located test files.
if [ -n "$test_files" ]; then
  rg 'ConsoleThread' $test_files
else
  echo "No test files found."
fi

Length of output: 1738



Script:

#!/bin/bash
# Description: Search for `ConsoleThread` usage across the entire codebase to identify any indirect testing.

# Step 1: Search for `ConsoleThread` usage across the entire codebase.
rg 'ConsoleThread'

Length of output: 774

Comment on lines +29 to +36
if (typeof config.certificateFile === "undefined") {
throw new Error("Certificate file not defined");
}
try {
return await readFile(config.certificateFile, "utf8");
} catch (err) {
throw new Error(`Error reading certificate file: ${String(err)}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling in handleGetCert.

- throw new Error(`Error reading certificate file: ${String(err)}`);
+ throw new Error(`Error reading certificate file: ${err.message}`);

Using err.message provides a clearer and more specific error message, which is beneficial for debugging and logging.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if (typeof config.certificateFile === "undefined") {
throw new Error("Certificate file not defined");
}
try {
return await readFile(config.certificateFile, "utf8");
} catch (err) {
throw new Error(`Error reading certificate file: ${String(err)}`);
}
if (typeof config.certificateFile === "undefined") {
throw new Error("Certificate file not defined");
}
try {
return await readFile(config.certificateFile, "utf8");
} catch (err) {
throw new Error(`Error reading certificate file: ${err.message}`);
}

Comment on lines +84 to +91
if (typeof config.publicKeyFile === "undefined") {
throw new Error("Public key file not defined");
}
try {
return await readFile(config.publicKeyFile, "utf8");
} catch (err) {
throw new Error(`Error reading public key file: ${String(err)}`);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling in handleGetKey.

- throw new Error(`Error reading public key file: ${String(err)}`);
+ throw new Error(`Error reading public key file: ${err.message}`);

Similar to handleGetCert, improving the error message makes the function more robust and the errors more understandable.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
if (typeof config.publicKeyFile === "undefined") {
throw new Error("Public key file not defined");
}
try {
return await readFile(config.publicKeyFile, "utf8");
} catch (err) {
throw new Error(`Error reading public key file: ${String(err)}`);
}
if (typeof config.publicKeyFile === "undefined") {
throw new Error("Public key file not defined");
}
try {
return await readFile(config.publicKeyFile, "utf8");
} catch (err) {
throw new Error(`Error reading public key file: ${err.message}`);
}

Comment on lines +35 to +74
override deserialize(data: Buffer): this {
try {
this._assertEnoughData(data, this.getByteSize());

this.messageId = data.readUInt16LE(0);

this._serverTime = data.readUInt32LE(2);

this._firstTime = data.readUInt8(6) === 1;

this._paycheckWaiting = data.readUInt8(7) === 1;

this._clubInvitesWaiting = data.readUInt8(8) === 1;

this.tallyInProgress = data.readUInt8(9) === 1;

this._secondsUntilShutdown = data.readUInt16LE(10);

this._shardGNP = data.readUInt32LE(12);

this._shardCarsSold = data.readUInt32LE(16);

this._shardAverageSalaries = data.readUInt32LE(20);

this._shardAverageCarsOwned = data.readUInt32LE(24);

this._shardAverageLevel = data.readUInt32LE(28);

this._cookie = data.readUInt32LE(32);

this._nextTallyDate = data.readUInt32LE(36);

this._nextPaycheckDate = data.readUInt32LE(40);

return this;
} catch (error) {
log.error(`Error deserializing LoginCompleteMessage: ${error as string}`);
throw error;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure robust error handling in serialization and deserialization.

- log.error(`Error deserializing LoginCompleteMessage: ${error as string}`);
+ log.error(`Error deserializing LoginCompleteMessage: ${error.message}`);

Improving the error logging to include error.message provides more specific information, which is crucial for debugging.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
override deserialize(data: Buffer): this {
try {
this._assertEnoughData(data, this.getByteSize());
this.messageId = data.readUInt16LE(0);
this._serverTime = data.readUInt32LE(2);
this._firstTime = data.readUInt8(6) === 1;
this._paycheckWaiting = data.readUInt8(7) === 1;
this._clubInvitesWaiting = data.readUInt8(8) === 1;
this.tallyInProgress = data.readUInt8(9) === 1;
this._secondsUntilShutdown = data.readUInt16LE(10);
this._shardGNP = data.readUInt32LE(12);
this._shardCarsSold = data.readUInt32LE(16);
this._shardAverageSalaries = data.readUInt32LE(20);
this._shardAverageCarsOwned = data.readUInt32LE(24);
this._shardAverageLevel = data.readUInt32LE(28);
this._cookie = data.readUInt32LE(32);
this._nextTallyDate = data.readUInt32LE(36);
this._nextPaycheckDate = data.readUInt32LE(40);
return this;
} catch (error) {
log.error(`Error deserializing LoginCompleteMessage: ${error as string}`);
throw error;
}
}
override deserialize(data: Buffer): this {
try {
this._assertEnoughData(data, this.getByteSize());
this.messageId = data.readUInt16LE(0);
this._serverTime = data.readUInt32LE(2);
this._firstTime = data.readUInt8(6) === 1;
this._paycheckWaiting = data.readUInt8(7) === 1;
this._clubInvitesWaiting = data.readUInt8(8) === 1;
this.tallyInProgress = data.readUInt8(9) === 1;
this._secondsUntilShutdown = data.readUInt16LE(10);
this._shardGNP = data.readUInt32LE(12);
this._shardCarsSold = data.readUInt32LE(16);
this._shardAverageSalaries = data.readUInt32LE(20);
this._shardAverageCarsOwned = data.readUInt32LE(24);
this._shardAverageLevel = data.readUInt32LE(28);
this._cookie = data.readUInt32LE(32);
this._nextTallyDate = data.readUInt32LE(36);
this._nextPaycheckDate = data.readUInt32LE(40);
return this;
} catch (error) {
log.error(`Error deserializing LoginCompleteMessage: ${error.message}`);
throw error;
}
}

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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between fcb1f7b and 2f74d60.
Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
Files selected for processing (12)
  • src/cli/package.json (1 hunks)
  • src/connection/package.json (1 hunks)
  • src/database/package.json (1 hunks)
  • src/gateway/package.json (1 hunks)
  • src/mcots/package.json (1 hunks)
  • src/nps/package.json (1 hunks)
  • src/patch/package.json (1 hunks)
  • src/schema/package.json (1 hunks)
  • src/server/instrument.mts (1 hunks)
  • src/server/package.json (1 hunks)
  • src/shard/package.json (1 hunks)
  • src/shared-packets/package.json (1 hunks)
Files skipped from review due to trivial changes (1)
  • src/server/instrument.mts
Files skipped from review as they are similar to previous changes (11)
  • src/cli/package.json
  • src/connection/package.json
  • src/database/package.json
  • src/gateway/package.json
  • src/mcots/package.json
  • src/nps/package.json
  • src/patch/package.json
  • src/schema/package.json
  • src/server/package.json
  • src/shard/package.json
  • src/shared-packets/package.json

…hard, schema, shared, gateway, and connection
Copy link

sonarcloud bot commented May 26, 2024

Quality Gate Failed Quality Gate failed

Failed conditions
2 Security Hotspots
D Security Rating on New Code (required ≥ A)
B Reliability Rating on New Code (required ≥ A)

See analysis details on SonarCloud

Catch issues before they fail your Quality Gate with our IDE extension SonarLint

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: 4

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 2f74d60 and a7101ea.
Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !pnpm-lock.yaml
Files selected for processing (35)
  • drizzle.config.ts (1 hunks)
  • drizzle/0000_secret_lady_mastermind.sql (1 hunks)
  • drizzle/meta/_journal.json (1 hunks)
  • package.json (1 hunks)
  • src/cli/tsconfig.json (1 hunks)
  • src/connection/tsconfig.json (1 hunks)
  • src/database/tsconfig.json (1 hunks)
  • src/gateway/tsconfig.json (1 hunks)
  • src/mcots/tsconfig.json (1 hunks)
  • src/nps/tsconfig.json (1 hunks)
  • src/patch/test/PatchServer.test.ts (1 hunks)
  • src/patch/tsconfig.json (1 hunks)
  • src/schema/abstractPartType.schema.ts (1 hunks)
  • src/schema/attachmentPoint.schema.ts (1 hunks)
  • src/schema/brand.schema.ts (1 hunks)
  • src/schema/brandedPart.schema.ts (1 hunks)
  • src/schema/driverClass.schema.ts (1 hunks)
  • src/schema/index.ts (1 hunks)
  • src/schema/model.schema.ts (1 hunks)
  • src/schema/part.schema.ts (1 hunks)
  • src/schema/partGrade.schema.ts (1 hunks)
  • src/schema/partType.schema.ts (1 hunks)
  • src/schema/player.schema.ts (1 hunks)
  • src/schema/playerType.schema.ts (1 hunks)
  • src/schema/profile.schema.ts (1 hunks)
  • src/schema/raceType.schema.ts (1 hunks)
  • src/schema/skin.schema.ts (1 hunks)
  • src/schema/skinType.schema.ts (1 hunks)
  • src/schema/stockAssembly.schema.ts (1 hunks)
  • src/schema/stockVehicleAttributes.schema.ts (1 hunks)
  • src/schema/svaCarClass.schema.ts (1 hunks)
  • src/schema/svaModeRestriction.schema.ts (1 hunks)
  • src/schema/tsconfig.json (1 hunks)
  • src/schema/tunables.schema.ts (1 hunks)
  • src/schema/user.schema.ts (1 hunks)
Files skipped from review due to trivial changes (3)
  • src/mcots/tsconfig.json
  • src/patch/tsconfig.json
  • src/schema/index.ts
Additional Context Used
Biome (2)
src/patch/test/PatchServer.test.ts (2)

1-1: A Node.js builtin module should be imported with the node: protocol.


3-4: All these imports are only used as types.

Additional comments not posted (52)
src/schema/tsconfig.json (2)

2-2: Configuration correctly extends the base TypeScript settings.


3-7: Compiler options are set appropriately for the schema directory.

drizzle/meta/_journal.json (1)

1-13: The journal configuration appears correctly formatted and includes necessary versioning and tagging details.

src/schema/raceType.schema.ts (2)

1-3: Imports are correctly set up for database schema definitions.


5-10: The raceType table schema is well-defined with appropriate data types and constraints.

src/schema/skinType.schema.ts (2)

1-3: Imports are correctly set up for database schema definitions.


5-10: The skinType table schema is well-defined with appropriate data types and constraints.

drizzle.config.ts (2)

1-2: Correctly imports necessary configurations and tools for setting up drizzle.


8-16: Configuration for drizzle is appropriately set with correct paths, database credentials, and schema filters.

src/database/tsconfig.json (3)

2-2: Configuration correctly extends the base TypeScript settings.


3-7: Compiler options are set appropriately for the database directory.


12-18: Project references are correctly set to include the schema and shared directories.

src/connection/tsconfig.json (3)

3-6: Compiler options are correctly set for the project structure.


7-8: Include and exclude patterns are appropriately configured.


11-17: Project references are well-defined, enhancing modularity and scalability.

src/gateway/tsconfig.json (3)

3-6: Compiler options are correctly set for the project structure.


7-8: Include and exclude patterns are appropriately configured.


10-18: Project references are well-defined, enhancing modularity and scalability.

src/cli/tsconfig.json (3)

3-11: Compiler options are well-configured to support development and debugging features.


12-13: Include and exclude patterns are appropriately configured.


15-22: Project references are well-defined, enhancing modularity and scalability.

src/schema/playerType.schema.ts (1)

1-18: The schema definition for player_type is well-structured and uses best practices for database design.

src/schema/driverClass.schema.ts (1)

1-18: The schema definition for driver_class is well-structured and uses best practices for database design.

src/schema/svaCarClass.schema.ts (1)

1-20: The schema definition for sva_car_class is well-structured and uses best practices for database design.

src/schema/svaModeRestriction.schema.ts (1)

1-20: The schema definition for sva_mode_restriction looks correct and follows standard practices for using drizzle-orm/pg-core.

src/schema/brand.schema.ts (1)

1-20: The schema definition for brand is well-structured and correctly utilizes the features of drizzle-orm/pg-core.

src/schema/attachmentPoint.schema.ts (1)

1-20: The schema definition for attachment_point is correctly set up and follows the expected practices for schema definitions using drizzle-orm/pg-core.

src/nps/tsconfig.json (1)

1-31: The TypeScript configuration for the nps module is correctly set up and follows standard practices for TypeScript projects.

src/schema/partGrade.schema.ts (1)

1-21: The schema definition for part_grade is well-structured and correctly utilizes the features of drizzle-orm/pg-core.

src/schema/user.schema.ts (1)

1-21: The schema definition for user is correctly set up and follows the expected practices for schema definitions using drizzle-orm/pg-core.

package.json (5)

2-2: Updated package name to scoped name for better organization in a monorepo.


7-7: Updated repository URL to reflect the new GitHub repository location.


14-14: Updated start script to use the correct environment file path and executable.


18-21: Added new dependencies necessary for the project's functionality.


23-23: Specified the package manager version to ensure consistency across environments.

src/schema/stockAssembly.schema.ts (1)

1-33: Introduced a new schema for stock_assembly with appropriate references and indexes.

src/schema/partType.schema.ts (1)

1-33: Introduced a new schema for part_type with appropriate references and unique indexes.

src/schema/brandedPart.schema.ts (1)

1-34: Introduced a new schema for branded_part with appropriate references and indexes.

src/schema/stockVehicleAttributes.schema.ts (1)

1-41: Introduced a new schema for stock_vehicle_attributes with appropriate references and indexes.

src/schema/part.schema.ts (2)

36-47: Indexes are correctly defined for optimization.

Indexes on partId, parentPartId, brandedPartId, and attachmentPointId are well-defined for quick lookups.


15-34: Ensure foreign key references are correctly implemented.

Verification successful

The foreign key references in src/schema/part.schema.ts are correctly implemented.

  • The brandedPartId column is defined in src/schema/brandedPart.schema.ts.
  • The attachmentPointId column is defined in src/schema/attachmentPoint.schema.ts.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the referenced columns exist in the respective tables.

# Test: Search for the referenced columns in the respective table definitions.
rg --type typescript $'brandedPartId: integer("branded_part_id")' src/schema/brandedPart.schema.ts
rg --type typescript $'attachmentPointId: integer("attachment_point_id")' src/schema/attachmentPoint.schema.ts

Length of output: 281



Script:

#!/bin/bash
# Description: Verify that the referenced columns exist in the respective tables.

# Test: Search for the referenced columns in the respective table definitions.
rg --type ts $'brandedPartId: integer("branded_part_id")' src/schema/brandedPart.schema.ts
rg --type ts $'attachmentPointId: integer("attachment_point_id")' src/schema/attachmentPoint.schema.ts

Length of output: 195



Script:

#!/bin/bash
# Description: Verify that the referenced columns exist in the respective tables.

# Test: Search for the table definitions and their columns in the entire codebase.
ast-grep --lang typescript --pattern $'const brandedPart = mySchema.table("branded_part", { brandedPartId: integer("branded_part_id") })'
ast-grep --lang typescript --pattern $'const attachmentPoint = mySchema.table("attachment_point", { attachmentPointId: integer("attachment_point_id") })'

Length of output: 293



Script:

#!/bin/bash
# Description: Verify that the referenced columns exist in the respective tables.

# Test: Search for the table definitions and their columns in the entire codebase.
rg 'brandedPartId: integer\("branded_part_id"\)' 
rg 'attachmentPointId: integer\("attachment_point_id"\)' 

Length of output: 735

src/schema/profile.schema.ts (2)

41-43: Index on profileId is correctly defined.

The unique index on profileId ensures that each profile can be quickly accessed and is unique.


14-39: Review default values and data types for consistency.

src/schema/model.schema.ts (1)

8-40: Ensure all fields are correctly defined and necessary.

src/schema/abstractPartType.schema.ts (2)

59-67: Indexes are well-defined for optimization.

Indexes on abstractPartTypeId, parentAbstractPartTypeId, and dependsOn are correctly defined for quick lookups.


14-57: Check for correct default values and references.

src/schema/skin.schema.ts (2)

90-94: Indexes are correctly defined for optimization.

Indexes on skinId, creatorId, and skinTypeId are well-defined for quick lookups.


14-88: Ensure all fields and references are correctly defined.

src/schema/tunables.schema.ts (1)

7-72: Review all fields for correct data types and default values.

Verification successful

The fields dealOfTheDayBrandedPartId and dealOfTheDayDiscount in the tunables schema are correctly defined as integers and marked as not null. No issues were found with the schema definition.

  • dealOfTheDayBrandedPartId: integer, not null
  • dealOfTheDayDiscount: integer, not null
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all fields have correct data types and default values according to the system requirements.

# Test: Check the system documentation or configuration files for field definitions.
cat docs/system_requirements.md | grep 'tunables schema'

Length of output: 118



Script:

#!/bin/bash
# Description: Search for references to the `tunables` schema in the codebase to verify the fields.

# Find all files that reference the `tunables` schema.
rg 'tunables' --type js --type ts

Length of output: 835



Script:

#!/bin/bash
# Description: Extract relevant lines from files that reference the `tunables` schema to verify the fields.

# Extract lines from `getWarehouseInventory.ts` that reference `tunablesSchema`.
rg 'tunablesSchema' src/database/src/functions/getWarehouseInventory.ts

# Extract lines from `createNewCar.ts` that reference `tunablesSchema`.
rg 'tunablesSchema' src/database/src/functions/createNewCar.ts

Length of output: 447

src/schema/player.schema.ts (1)

14-118: The schema definition for the player table appears comprehensive and well-structured. Ensure that all referenced entities like playerType and driverClass are correctly defined elsewhere in the schema to maintain integrity.

drizzle/0000_secret_lady_mastermind.sql (2)

1-587: The SQL schema definitions are well-structured and include necessary constraints and default values. Ensure that all foreign key references are correctly set up and that the referenced tables and columns exist.


407-587: The addition of constraints using DO blocks with exception handling is a robust approach. Verify that all constraints are necessary and correctly reference the intended tables and columns.

@@ -0,0 +1,47 @@
import type { IncomingMessage, ServerResponse } from "http";
Copy link
Contributor

Choose a reason for hiding this comment

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

Import Node.js built-in modules using the node: protocol for clarity and consistency.

- import type { IncomingMessage, ServerResponse } from "http";
+ import type { IncomingMessage, ServerResponse } from "node:http";

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
import type { IncomingMessage, ServerResponse } from "http";
import type { IncomingMessage, ServerResponse } from "node:http";

Comment on lines +3 to +4
import { CastanetResponse, PatchServer } from "../src/PatchServer.js";
import { TServerLogger } from "@rustymotors/shared";
Copy link
Contributor

Choose a reason for hiding this comment

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

These imports are only used as types and should be marked accordingly to prevent runtime imports.

- import { CastanetResponse, PatchServer } from "../src/PatchServer.js";
- import { TServerLogger } from "@rustymotors/shared";
+ import type { CastanetResponse, PatchServer } from "../src/PatchServer.js";
+ import type { TServerLogger } from "@rustymotors/shared";

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
import { CastanetResponse, PatchServer } from "../src/PatchServer.js";
import { TServerLogger } from "@rustymotors/shared";
import type { CastanetResponse, PatchServer } from "../src/PatchServer.js";
import type { TServerLogger } from "@rustymotors/shared";

"outDir": "./dist",

},
"include": ["./*.ts"],
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure all TypeScript files in the schema directory are included in the tsconfig.json.

The following TypeScript files are not included in the tsconfig.json:

  • src/schema/abstractPartType.schema.ts
  • src/schema/attachmentPoint.schema.ts
  • src/schema/brand.schema.ts
  • src/schema/brandedPart.schema.ts
  • src/schema/driverClass.schema.ts
  • src/schema/index.ts
  • src/schema/key.ts
  • src/schema/model.schema.ts
  • src/schema/part.schema.ts
  • src/schema/partGrade.schema.ts
  • src/schema/partType.schema.ts
  • src/schema/player.schema.ts
  • src/schema/playerType.schema.ts
  • src/schema/profile.schema.ts
  • src/schema/raceType.schema.ts
  • src/schema/skin.schema.ts
  • src/schema/skinType.schema.ts
  • src/schema/stockAssembly.schema.ts
  • src/schema/stockVehicleAttributes.schema.ts
  • src/schema/svaCarClass.schema.ts
  • src/schema/svaModeRestriction.schema.ts
  • src/schema/tunables.schema.ts
  • src/schema/user.schema.ts
  • src/schema/vehicle.schema.ts
  • src/schema/warehouse.schema.ts

Please ensure these files are included in the tsconfig.json file.

Analysis chain

Ensure all TypeScript files in the schema directory are included.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all TypeScript files in the schema directory are included in the tsconfig.json.

# Test: List all TypeScript files in the schema directory and check if they are included in the tsconfig.json.
fd --type f --extension ts src/schema | xargs -I {} grep -q {} src/schema/tsconfig.json

Length of output: 439



Script:

#!/bin/bash
# Description: Verify all TypeScript files in the schema directory are included in the tsconfig.json.

# List all TypeScript files in the src/schema directory
ts_files=$(fd --type f --extension ts . src/schema)

# Check if each TypeScript file is included in the tsconfig.json
for file in $ts_files; do
  if ! grep -q "$(basename "$file")" src/schema/tsconfig.json; then
    echo "File not included: $file"
  fi
done

Length of output: 6545

Comment on lines +8 to +9
"include": ["./index.ts", "./src/**/*.ts"],
"exclude": ["node_modules/*", "dist/*", "coverage/*"],
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The verification script has revealed that several TypeScript files in the src/database directory are neither included nor excluded in the tsconfig.json. This indicates that the tsconfig.json configuration might be incomplete or incorrect.

Files not included or excluded:

  • src/database/index.ts
  • src/database/src/DatabaseManager.ts
  • src/database/src/functions/createNewCar.ts
  • src/database/src/functions/getAbstractPartTypeId.ts
  • src/database/src/functions/getWarehouseInventory.ts
  • src/database/src/functions/transferPartAssembly.ts
  • src/database/src/seeders/index.ts
  • src/database/src/seeders/populateAbstractPartType.ts
  • src/database/src/seeders/populateBrand.ts
  • src/database/src/seeders/populateBrandedPart.ts
  • src/database/src/seeders/populateModel.ts
  • src/database/src/seeders/populatePartGrade.ts
  • src/database/src/seeders/populatePartType.ts
  • src/database/src/seeders/populatePlayer.ts
  • src/database/src/seeders/populatePlayerType.ts
  • src/database/src/seeders/populateSkin.ts
  • src/database/src/seeders/populateSkinType.ts
  • src/database/src/seeders/populateWarehouse.ts
  • src/database/src/services/database.ts
  • src/database/test/Database.test.ts
  • src/database/vite.config.ts

Please review and update the tsconfig.json to ensure all necessary TypeScript files are included and excluded appropriately.

Analysis chain

Ensure all necessary TypeScript files in the database directory are included and excluded appropriately.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all TypeScript files in the database directory are included in the tsconfig.json and excluded directories are respected.

# Test: List all TypeScript files in the database directory and check if they are included in the tsconfig.json, and ensure excluded directories are respected.
fd --type f --extension ts src/database | xargs -I {} grep -q {} src/database/tsconfig.json

Length of output: 451



Script:

#!/bin/bash
# Description: Verify all TypeScript files in the database directory are included in the tsconfig.json and excluded directories are respected.

# List all TypeScript files in the src/database directory
fd --type f --extension ts . src/database > all_ts_files.txt

# Check if these files are included in the tsconfig.json
included_files=$(grep -oP '(?<="include": \[)[^\]]*' src/database/tsconfig.json | tr -d '", ')
excluded_files=$(grep -oP '(?<="exclude": \[)[^\]]*' src/database/tsconfig.json | tr -d '", ')

# Verify inclusion and exclusion
while IFS= read -r file; do
  if [[ $included_files == *"${file}"* ]]; then
    echo "Included: ${file}"
  elif [[ $excluded_files == *"${file}"* ]]; then
    echo "Excluded: ${file}"
  else
    echo "Not included or excluded: ${file}"
  fi
done < all_ts_files.txt

Length of output: 9056

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants