Skip to content

refactor(routers): reduce IGW router registration boilerplate - #362

Merged
slin1237 merged 1 commit into
mainfrom
doc-fix-2
Feb 6, 2026
Merged

slin1237 merged 1 commit into
mainfrom
doc-fix-2

Conversation

@slin1237

@slin1237 slin1237 commented Feb 6, 2026 •

Copy link
Copy Markdown
Member

Summary

Reduces ~90 lines of repeated match/register/log boilerplate in RouterManager::from_config() down to a simple loop, and fixes the module dependency direction so router_manager depends on factory (not circular).

What changed

  • model_gateway/src/routers/factory.rs:

    • Moved RouterId type and router_ids constants here from router_manager.rs — factory is the lower-level module, so manager should depend on it, not the other way around
    • Added create_igw_routers() method returning all 6 IGW routers as (id, label, Result) tuples
  • model_gateway/src/routers/router_manager.rs:

    • Removed RouterId and router_ids definitions (now imported from factory)
    • Added try_register() helper that handles the match/log pattern for a single router
    • Replaced 6 repeated 8-line match/register/log blocks in the IGW branch of from_config() with a loop over create_igw_routers()
    • Moved RouterFactory import from function-level to module-level

Why

Adding a new router to IGW mode previously required copying an 8-line block in router_manager.rs and updating 3 strings. Now it requires a single line in create_igw_routers() in factory.rs — the same file where the create_*_router() methods live.

How

The key insight is that the 6 router creation blocks in from_config() all followed the exact same pattern: call a factory method, match on Ok/Err, log, and register. By having the factory return all results as a vec of tuples, the manager can loop over them with a generic try_register() helper. RouterId/router_ids moved to factory.rs to keep the dependency one-directional.

Test plan

  • cargo build — compiles cleanly
  • cargo clippy -p smg --all-targets --all-features -- -D warnings — no warnings
  • cargo test -p smg — all 16 tests pass, 0 failures

Summary by CodeRabbit

  • Refactor
    • Consolidated multi-router initialization into a unified factory method, simplifying the router setup process and improving code maintainability.
    • Streamlined router identity handling with predefined constants to optimize performance in critical execution paths.

Move RouterId and router_ids from router_manager into factory to
keep the dependency direction one-way (router_manager → factory).

Add RouterFactory::create_igw_routers() that returns all IGW routers
as (id, label, result) tuples, and RouterManager::try_register() that
handles the match/log pattern. The IGW block in from_config() goes
from ~90 lines of repeated match/register/log to a simple loop.

Adding a new router to IGW mode now requires a single line in
create_igw_routers() instead of copying an 8-line block in a
separate file.

Files changed:
- model_gateway/src/routers/factory.rs: add RouterId, router_ids
  module, and create_igw_routers() method
- model_gateway/src/routers/router_manager.rs: remove RouterId and
  router_ids (now imported from factory), add try_register() helper,
  replace 6 repeated match blocks with loop over create_igw_routers()
@github-actions github-actions Bot added the model-gateway Model gateway crate changes label Feb 6, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @slin1237, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors the router initialization process within the Inter-Gateway (IGW) mode. By centralizing router creation logic and streamlining the registration boilerplate, it enhances code maintainability and simplifies the future addition of new routers. The changes also improve the module dependency structure, ensuring a clearer and more logical flow of information between components.

Highlights

  • Refactoring Router Registration: Reduced approximately 90 lines of repetitive match/register/log boilerplate in RouterManager::from_config() by introducing a simple loop and a helper function.
  • Dependency Direction Fix: Corrected the module dependency direction, ensuring that router_manager now depends on factory, resolving a potential circular dependency.
  • Centralized Router ID Definitions: Moved the RouterId type and router_ids constants from router_manager.rs to factory.rs, aligning with the principle that the lower-level module (factory) should define these core identifiers.
  • Unified IGW Router Creation: Added a new create_igw_routers() method to factory.rs which returns all six IGW routers as (id, label, Result) tuples, simplifying the process of adding new routers.
  • Simplified Router Registration Logic: Introduced a try_register() helper method in router_manager.rs to encapsulate the common pattern of matching on router creation results, logging, and registering the router.
Changelog
  • model_gateway/src/routers/factory.rs
    • Moved RouterId type and router_ids constants from router_manager.rs to this file to establish a clearer dependency hierarchy.
    • Added a new asynchronous function create_igw_routers() which returns a vector of tuples containing RouterId, a descriptive label, and the creation result for all IGW routers. This method centralizes the creation of all IGW routers.
  • model_gateway/src/routers/router_manager.rs
    • Removed the RouterId type and router_ids constants, now importing them from factory.rs.
    • Introduced a private helper method try_register() to encapsulate the logic for registering a router and logging its creation status (success or failure).
    • Replaced multiple repetitive match statements for router creation and registration within the from_config() method with a single loop that iterates over the results from RouterFactory::create_igw_routers() and utilizes the new try_register() helper.
    • Changed the RouterFactory import from function-level to module-level for consistency.
Activity
  • The author, slin1237, provided a detailed summary of the changes, including the rationale and a comprehensive test plan, indicating a thorough initial submission.
  • The test plan includes cargo build for clean compilation, cargo clippy with all warnings enabled for static analysis, and cargo test to ensure all existing tests pass.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@coderabbitai

coderabbitai Bot commented Feb 6, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Router creation logic has been refactored to centralize multi-router setup. A new RouterId type and factory method create_igw_routers were introduced in the factory module, eliminating duplicate router identity definitions and consolidating IGW router instantiation into a single call.

Changes

Cohort / File(s) Summary
Factory Module
model_gateway/src/routers/factory.rs
Added RouterId struct wrapping static strings with accessors, introduced router_ids module containing six static router constants (HTTP/gRPC variants for regular, PD, OpenAI, Anthropic), and implemented async create_igw_routers factory method that aggregates creation of all routers in a single call.
Router Manager
model_gateway/src/routers/router_manager.rs
Refactored IGW mode to use single RouterFactory::create_igw_routers call instead of individual router creations; introduced try_register helper for centralized logging and registration; removed duplicate RouterId type and router_ids constants module; adjusted imports to reference factory-provided identities.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Hops with glee at factories so keen,
RouterIds consolidated, clean!
No more duplication's scattered dance,
One creation method gives routers a chance,
IGW setup simplified, hop by hop! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main change: reducing boilerplate in IGW router registration through refactoring, which is the primary objective of the pull request.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch doc-fix-2

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request is a solid refactoring that significantly reduces boilerplate for registering IGW routers. The introduction of create_igw_routers in the factory and the try_register helper in the manager centralizes logic, making the code cleaner and more maintainable. Moving RouterId to the factory module is also a good move to fix the dependency direction. Overall, this is a great improvement. I have one minor suggestion to make the new RouterId type more ergonomic to use.

Comment on lines +22 to +30
impl RouterId {
pub const fn new(id: &'static str) -> Self {
Self(id)
}

pub fn as_str(&self) -> &str {
self.0
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To make RouterId more ergonomic, consider implementing the Display and Deref traits. This would allow you to use it directly in formatting macros (like info!) and other places expecting a &str, removing the need for the .as_str() method.

After applying this suggestion, you can remove the .as_str() calls in router_manager.rs.

impl RouterId {
    pub const fn new(id: &'static str) -> Self {
        Self(id)
    }
}

impl std::fmt::Display for RouterId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::ops::Deref for RouterId {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.0
    }
}

@slin1237
slin1237 merged commit d9c8068 into main Feb 6, 2026
8 checks passed
@slin1237
slin1237 deleted the doc-fix-2 branch February 6, 2026 22:39
ppraneth pushed a commit that referenced this pull request Feb 18, 2026
Signed-off-by: ppraneth <pranethparuchuri@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model-gateway Model gateway crate changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants