Title: refactor(gapic-generator): deduplicate sync/async prep_wrapped_messages and transport method wrapping · Issue #18536 · googleapis/google-cloud-python · GitHub
Open Graph Title: refactor(gapic-generator): deduplicate sync/async prep_wrapped_messages and transport method wrapping · Issue #18536 · googleapis/google-cloud-python
X Title: refactor(gapic-generator): deduplicate sync/async prep_wrapped_messages and transport method wrapping · Issue #18536 · googleapis/google-cloud-python
Description: Problem Summary In packages/gapic-generator/gapic/templates/, there is code duplication and structural asymmetry between synchronous and asynchronous RPC preparation and method wrapping across the generated transport classes: _prep_wrapp...
Open Graph Description: Problem Summary In packages/gapic-generator/gapic/templates/, there is code duplication and structural asymmetry between synchronous and asynchronous RPC preparation and method wrapping across the ...
X Description: Problem Summary In packages/gapic-generator/gapic/templates/, there is code duplication and structural asymmetry between synchronous and asynchronous RPC preparation and method wrapping across the ...
Opengraph URL: https://github.com/googleapis/google-cloud-python/issues/18536
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"refactor(gapic-generator): deduplicate sync/async prep_wrapped_messages and transport method wrapping","articleBody":"### Problem Summary\n\nIn `packages/gapic-generator/gapic/templates/`, there is code duplication and structural asymmetry between synchronous and asynchronous RPC preparation and method wrapping across the generated transport classes:\n\n1. **`_prep_wrapped_messages` Duplication**:\n - `packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/transports/base.py.j2` (lines 239–280) defines `_prep_wrapped_messages(self, client_info)` for synchronous transports.\n - `packages/gapic-generator/gapic/templates/%namespace/%name_%version/%sub/services/%service/_shared_macros.j2` (lines 322–371) defines `prep_wrapped_messages_async_method(api, service)` for asynchronous transports.\n - These two blocks are ~50 lines of Jinja template code that are nearly identical. Both iterate over `service.methods.values()` and `api.mixin_api_methods.keys()`, mapping every RPC to its retry predicate, default timeout, client info, fully-qualified method name, and streaming flags. The only differences are:\n - `self._wrap_method` vs `self._wrap_async_method`\n - `retries.Retry(...)` vs `retries.AsyncRetry(...)`\n\n2. **`_wrap_method` vs `_wrap_async_method` Duplication**:\n - Both methods are defined side-by-side in `base.py.j2` (lines 174–237).\n - Both methods implement identical compatibility checks and argument filtering across three generations of `google-api-core` (`client_options`, `kind`, `method_name`, `is_streaming`), delegating respectively to `gapic_v1.method.wrap_method` and `gapic_v1.method_async.wrap_method`.\n - Consider moving these to `_compat.py` to reduce the footprint in generated code.\n\n3. **Architectural Asymmetry (Base Class vs Shared Macros)**:\n - `_wrap_async_method` is defined directly on the synchronous base class `{{ service.name }}Transport` in `base.py.j2`, even though synchronous transports never call it.\n - Conversely, asynchronous `_prep_wrapped_messages` is *not* in `base.py.j2`—it lives as an external Jinja macro in `_shared_macros.j2` that is injected into `grpc_asyncio.py.j2` and `rest_asyncio.py.j2` to override the base class implementation.\n - This mixing makes the transport hierarchy harder to reason about and causes maintenance drift when retry parameters, metadata, or tracing attributes are updated.\n\n---\n\n### Deduplication Options to Consider\n\n#### Option A: Polymorphic Dispatch in Base Transport (Recommended)\nConsolidate `_prep_wrapped_messages` into a single, unified implementation in `base.py.j2` by making transport classes declare their retry class and RPC wrapper callable:\n\n```python\n# In base.py.j2 ({{ service.name }}Transport):\n_is_async: bool = False\n_retry_type = retries.Retry\n\ndef _wrap_rpc(self, func, *args, **kwargs):\n # Unified wrap helper parameterized by sync vs async\n wrap_func = gapic_v1.method_async.wrap_method if self._is_async else gapic_v1.method.wrap_method\n supports_tracing = _ASYNC_WRAP_METHOD_SUPPORTS_TRACING if self._is_async else _WRAP_METHOD_SUPPORTS_TRACING\n if supports_tracing:\n kwargs[\"client_options\"] = self._client_options\n if self.kind:\n kwargs[\"kind\"] = self.kind\n return wrap_func(func, *args, **kwargs)\n ...\n```\n\n- **Pros**:\n - `_prep_wrapped_messages` only exists once in `base.py.j2`. All transports (gRPC, AsyncIO gRPC, REST, AsyncIO REST) inherit it naturally.\n - Deletes `prep_wrapped_messages_async_method` from `_shared_macros.j2` entirely (~50 lines removed).\n - Eliminates duplicate template loops for mixin and service methods.\n- **Cons**: Requires setting transport class-level attributes (`_is_async`, `_retry_type`) on async transports.\n\n#### Option B: Parameterized Jinja Macro\nUnify synchronous and asynchronous message preparation into a single reusable Jinja macro in `_shared_macros.j2`:\n\n```jinja2\n{% macro prep_wrapped_messages(api, service, is_async=False) %}\ndef _prep_wrapped_messages(self, client_info):\n self._wrapped_methods = {\n {% for method in service.methods.values() %}\n self.{{ method.transport_safe_name|snake_case }}: self.{{ \"_wrap_async_method\" if is_async else \"_wrap_method\" }}(\n ...\n {% if method.retry %}\n default_retry=retries.{{ \"AsyncRetry\" if is_async else \"Retry\" }}(...),\n {% endif %}\n ...\n ),\n {% endfor %}\n }\n{% endmacro %}\n```\n\n- **Pros**:\n - Keeps generation purely in templates without modifying Python transport class contracts or inheritance semantics.\n - Single source of truth for method iteration and configuration.\n- **Cons**: Still renders two copies of the method across generated files; Jinja syntax becomes slightly more branchy.\n\n#### Option C: Dedicated `AsyncTransport` Base Class\nIntroduce an explicit `_Base{{ service.name }}AsyncTransport` class (similar to `_Base{{ service.name }}RestTransport`):\n- `{{ service.name }}Transport`: Sync base class containing sync `_prep_wrapped_messages` and `_wrap_method`.\n- `_Base{{ service.name }}AsyncTransport`: Async base class containing async `_prep_wrapped_messages` and `_wrap_async_method`.\n\n- **Pros**:\n - Clean separation of concerns; async wrappers are no longer baked into sync base classes.\n - Idiomatic object-oriented hierarchy.\n- **Cons**:\n - Larger structural change across generated codebases and public type contracts.\n - Requires updating multiple transport inheritance graphs.\n\n---\n\n### Related Discussion\n- PR #18433: `feat(observability): [WIP] implement universal 4-path OpenTelemetry tracing`\n- Follow-up from reviewer feedback regarding code duplication between sync and async transports.\n","author":{"url":"https://github.com/chalmerlowe","@type":"Person","name":"chalmerlowe"},"datePublished":"2026-10-01T11:59:34Z","url":"https://github.com/googleapis/google-cloud-python/issues/18536"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:708c4c79-b8c1-8469-2a44-f49b4cee08e1 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | ED5E:84C13:6058A6:7E7085:6AFE6C3E |
| html-safe-nonce | 4661b9217c90d92ec8fd154f1281817c856d42ef90aaa08158d94a8130e1a54a |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFRDVFOjg0QzEzOjYwNThBNjo3RTcwODU6NkFGRTZDM0UiLCJ2aXNpdG9yX2lkIjoiMzg0NjQ5MTMwNTI4MjUzMDM2NiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 62ae49cc45faca806c24bce58a75543c544913a0c8c6d94bcbad4c5af8e5c04f |
| hovercard-subject-tag | issue:5661765921 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/googleapis/google-cloud-python/18536/issue_layout |
| twitter:image | https://opengraph.githubassets.com/4cf784a608d47bb577abd93166deadf6e653eff0c59afd01037d76231cbd8d0c/googleapis/google-cloud-python/issues/18536 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/4cf784a608d47bb577abd93166deadf6e653eff0c59afd01037d76231cbd8d0c/googleapis/google-cloud-python/issues/18536 |
| og:image:alt | Problem Summary In packages/gapic-generator/gapic/templates/, there is code duplication and structural asymmetry between synchronous and asynchronous RPC preparation and method wrapping across the ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | chalmerlowe |
| hostname | github.com |
| expected-hostname | github.com |
| None | b3c0f155eafc27e60db6e254d1ffff0e072e9ab3b4018a5ee518797c19d89f86 |
| turbo-cache-control | no-preview |
| go-import | github.com/googleapis/google-cloud-python git https://github.com/googleapis/google-cloud-python.git |
| octolytics-dimension-user_id | 16785467 |
| octolytics-dimension-user_login | googleapis |
| octolytics-dimension-repository_id | 16316451 |
| octolytics-dimension-repository_nwo | googleapis/google-cloud-python |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 16316451 |
| octolytics-dimension-repository_network_root_nwo | googleapis/google-cloud-python |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 4a10310af51a1bfffbedc4fd81cb582acf0cb0ff |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width