Repository navigation
refactor(gateway): extract route_responses orchestration into responses/route.rs - #735
Conversation
…es/route.rs Move ~145 lines of inline orchestration logic from the RouterTrait impl in router.rs into a dedicated responses/route.rs module, mirroring the existing chat.rs delegation pattern. What changed: - model_gateway/src/routers/openai/responses/route.rs: new file with ResponsesRouterContext struct and route_responses() free function containing all responses orchestration logic (metrics, worker selection, validation, history loading, payload prep, provider transform, RequestContext setup, streaming dispatch, duration metrics) - model_gateway/src/routers/openai/responses/mod.rs: add pub(crate) mod route declaration - model_gateway/src/routers/openai/router.rs: replace 145-line inline route_responses with 8-line delegation (pack deps + delegate), remove dead responses_components() helper, clean up unused imports (Instant, to_value, ResponseInput, ResponseInputOutputItem, ComponentRefs, PayloadState, RequestContext, WorkerSelection, handle_non_streaming_response, handle_streaming_response, Endpoint, bool_to_static_str, error) - model_gateway/src/routers/openai/chat.rs: rename RouterContext to ChatRouterContext for consistency with ResponsesRouterContext Why: router.rs now has both route_chat and route_responses following the same delegation pattern — pack borrowed refs into a context struct, delegate to a module-level free function. This reduces router.rs from ~422 to ~278 lines of pure routing dispatch. How: pure mechanical extraction — the orchestration logic is moved verbatim with self.* references replaced by deps.* accesses on the new context struct. Worker selection is inlined via WorkerSelector::new() matching the chat.rs pattern. Signed-off-by: Simon Lin <simon@seekerlabs.ai> Signed-off-by: Simo Lin <linsimo.mark@gmail.com>
Summary of ChangesHello, 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 focuses on improving the modularity and organization of the OpenAI router by refactoring the Highlights
Changelog
Activity
Using Gemini Code AssistThe 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
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 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
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThis PR refactors OpenAI routing by extracting response routing logic into a dedicated module. It renames Changes
Sequence DiagramsequenceDiagram
participant Client
participant Router as OpenAI Router
participant RouteResp as route_responses
participant WorkerSel as WorkerSelector
participant WRegistry as WorkerRegistry
participant PRegistry as ProviderRegistry
participant RespHandler as Response Handler
participant Upstream as Upstream Service
Client->>Router: POST /responses
Router->>RouteResp: route_responses(context, headers, body)
RouteResp->>RouteResp: Extract model & streaming<br/>Record router metric
RouteResp->>WorkerSel: Select worker with model
WorkerSel->>WRegistry: Lookup worker
WRegistry-->>WorkerSel: Worker result
WorkerSel-->>RouteResp: Worker or error
alt Worker Selection Failed
RouteResp->>RouteResp: Record error metric
RouteResp-->>Router: Return error response
else Success
RouteResp->>RouteResp: Validate conversation vs<br/>previous_response_id
alt Validation Failed
RouteResp->>RouteResp: Record validation error
RouteResp-->>Router: Return 400 error
else Validation Passed
RouteResp->>RouteResp: Load input history
RouteResp->>RouteResp: Strip reasoning items<br/>if store disabled
RouteResp->>PRegistry: Resolve provider
PRegistry-->>RouteResp: Provider result
alt Provider Resolution Failed
RouteResp->>RouteResp: Record validation error
RouteResp-->>Router: Return 400 error
else Success
RouteResp->>RouteResp: Apply provider transform
RouteResp->>RespHandler: Handle response<br/>(streaming or non-streaming)
RespHandler->>Upstream: Forward request
Upstream-->>RespHandler: Response
RespHandler-->>RouteResp: Return response
RouteResp->>RouteResp: Record route duration metric
RouteResp-->>Router: Return response
end
end
end
Router-->>Client: HTTP Response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Code Review
This pull request is a solid refactoring that extracts the route_responses logic into its own module, improving code organization and consistency with the route_chat pattern. The changes are clean and well-executed.
I've identified a minor improvement opportunity to reduce redundancy in the newly created ResponsesRouterContext. The client field is redundant as it can be accessed through responses_components. Removing it would simplify the context struct. A similar pattern exists in ChatRouterContext, which could also be simplified in a follow-up change.
| pub worker_registry: &'a WorkerRegistry, | ||
| pub provider_registry: &'a ProviderRegistry, | ||
| pub responses_components: &'a Arc<ResponsesComponents>, | ||
| pub client: &'a reqwest::Client, |
| bool_to_static_str(streaming), | ||
| ); | ||
|
|
||
| let worker = match WorkerSelector::new(deps.worker_registry, deps.client) |
There was a problem hiding this comment.
To go along with the removal of the redundant client field from ResponsesRouterContext, please update this to access the client via deps.responses_components.shared.client.
| let worker = match WorkerSelector::new(deps.worker_registry, deps.client) | |
| let worker = match WorkerSelector::new(deps.worker_registry, &deps.responses_components.shared.client) |
| let deps = ResponsesRouterContext { | ||
| worker_registry: &self.worker_registry, | ||
| provider_registry: &self.provider_registry, | ||
| responses_components: &self.responses_components, | ||
| client: &self.responses_components.shared.client, | ||
| }; |
There was a problem hiding this comment.
Following the removal of the redundant client field from ResponsesRouterContext, this field should be removed from the struct initialization.
let deps = ResponsesRouterContext {
worker_registry: &self.worker_registry,
provider_registry: &self.provider_registry,
responses_components: &self.responses_components,
};
Summary
Extract ~145 lines of inline
route_responsesorchestration logic fromrouter.rsinto a dedicatedresponses/route.rsmodule, matching the existingchat.rsdelegation pattern. Continues the OpenAI router cleanup series (PRs #730, #732).Closes: N/A (refactor)
Refs: #730, #732
What changed
responses/route.rs(new):ResponsesRouterContextstruct +route_responses()free function with all orchestration logic — metrics recording, worker selection, mutual exclusivity validation, history loading, payload serialization, provider transform,RequestContextsetup, streaming/non-streaming dispatch, duration metricsresponses/mod.rs: addedpub(crate) mod route;declarationrouter.rs: replaced 145-line inlineroute_responseswith 8-line delegation (pack deps intoResponsesRouterContext, delegate toresponses_route::route_responses()). Removed deadresponses_components()helper. Cleaned up unused imports (Instant,to_value,ResponseInput,ResponseInputOutputItem,ComponentRefs,PayloadState,RequestContext,WorkerSelection,handle_non_streaming_response,handle_streaming_response,Endpoint,bool_to_static_str,error)chat.rs: renamedRouterContext→ChatRouterContextfor naming consistency withResponsesRouterContextWhy
route_chatwas already 8 lines of delegation whileroute_responseswas 145 lines inline — inconsistent patterns in the same file. Now both follow identical structure: pack borrowed refs into a context struct, delegate to a module-level free function. Reducesrouter.rsfrom ~422 to ~278 lines.How
Pure mechanical extraction — orchestration logic moved verbatim with
self.*replaced bydeps.*on the new context struct. Worker selection inlined viaWorkerSelector::new()matching thechat.rspattern.Test plan
cargo build -p smg— compiles cleancargo clippy -p smg --all-targets -- -D warnings— no warningscargo test -p smg— all 93+ tests pass across all test suitesSummary by CodeRabbit