|
23 | 23 | from gapic import generator |
24 | 24 | from gapic.schema import api |
25 | 25 | from gapic.utils import Options |
| 26 | +from gapic.utils.cache import generation_cache_context |
26 | 27 |
|
27 | 28 |
|
28 | 29 | @click.command() |
@@ -56,15 +57,23 @@ def generate(request: typing.BinaryIO, output: typing.BinaryIO) -> None: |
56 | 57 | [p.package for p in req.proto_file if p.name in req.file_to_generate] |
57 | 58 | ).rstrip(".") |
58 | 59 |
|
59 | | - # Build the API model object. |
60 | | - # This object is a frozen representation of the whole API, and is sent |
61 | | - # to each template in the rendering step. |
62 | | - api_schema = api.API.build(req.proto_file, opts=opts, package=package) |
| 60 | + # Create the generation cache context. |
| 61 | + # This provides the shared storage for the @cached_proto_context decorator. |
| 62 | + # 1. Performance: Memoizes `with_context` calls, speeding up generation significantly. |
| 63 | + # 2. Safety: The decorator uses this storage to "pin" Proto objects in memory. |
| 64 | + # This prevents Python's Garbage Collector from deleting objects created during |
| 65 | + # `API.build` while `Generator.get_response` is still using their IDs. |
| 66 | + # (See `gapic.utils.cache.cached_proto_context` for the specific pinning logic). |
| 67 | + with generation_cache_context(): |
| 68 | + # Build the API model object. |
| 69 | + # This object is a frozen representation of the whole API, and is sent |
| 70 | + # to each template in the rendering step. |
| 71 | + api_schema = api.API.build(req.proto_file, opts=opts, package=package) |
63 | 72 |
|
64 | | - # Translate into a protobuf CodeGeneratorResponse; this reads the |
65 | | - # individual templates and renders them. |
66 | | - # If there are issues, error out appropriately. |
67 | | - res = generator.Generator(opts).get_response(api_schema, opts) |
| 73 | + # Translate into a protobuf CodeGeneratorResponse; this reads the |
| 74 | + # individual templates and renders them. |
| 75 | + # If there are issues, error out appropriately. |
| 76 | + res = generator.Generator(opts).get_response(api_schema, opts) |
68 | 77 |
|
69 | 78 | # Output the serialized response. |
70 | 79 | output.write(res.SerializeToString()) |
|
0 commit comments