2323from gapic import generator
2424from gapic .schema import api
2525from gapic .utils import Options
26+ from gapic .utils .cache import generation_cache_context
2627
2728
2829@click .command ()
3839 "--output" ,
3940 type = click .File ("wb" ),
4041 default = sys .stdout .buffer ,
41- help = "Where to output the `CodeGeneratorResponse`. " " Defaults to stdout." ,
42+ help = "Where to output the `CodeGeneratorResponse`. Defaults to stdout." ,
4243)
4344def generate (request : typing .BinaryIO , output : typing .BinaryIO ) -> None :
4445 """Generate a full API client description."""
@@ -56,15 +57,23 @@ def generate(request: typing.BinaryIO, output: typing.BinaryIO) -> None:
5657 [p .package for p in req .proto_file if p .name in req .file_to_generate ]
5758 ).rstrip ("." )
5859
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 )
6372
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 )
6877
6978 # Output the serialized response.
7079 output .write (res .SerializeToString ())
0 commit comments