1+ import random
2+ import string
13import typing
4+ from uuid import uuid4
25
36import grpc .aio
47from grpc .aio import ClientCallDetails , Metadata
58
9+ import flyte
10+
611_default_metadata = Metadata (("accept" , "application/grpc" ))
12+ ALPHABET = string .ascii_lowercase + string .digits
13+
14+
15+ def fast_short_id ():
16+ return "" .join (random .choices (ALPHABET , k = 4 ))
17+
18+
19+ def _generate_request_id () -> str :
20+ """
21+ Generate a request ID based on the current Flyte context.
22+
23+ If running within a Flyte task context, creates a request ID using the action's unique_id_str method.
24+ Otherwise, falls back to a UUID4.
25+
26+ :return: The generated request ID string
27+ """
28+ ctx = flyte .ctx ()
29+ if ctx and ctx .action :
30+ return ctx .action .unique_id_str (salt = fast_short_id ())
31+
32+ # Fall back to UUID4 if context is not available
33+ return str (uuid4 ())
734
835
936def with_metadata (call_details : ClientCallDetails , new_metadata : Metadata ) -> ClientCallDetails :
@@ -27,20 +54,27 @@ def with_metadata(call_details: ClientCallDetails, new_metadata: Metadata) -> Cl
2754class _BaseDefaultMetadataInterceptor :
2855 """
2956 Base class for all default metadata interceptors that provides common functionality.
57+ Injects both default metadata (accept header) and x-request-id.
3058 """
3159
3260 async def _inject_default_metadata (self , call_details : grpc .aio .ClientCallDetails ):
3361 """
34- Injects default metadata into the client call details.
62+ Injects default metadata and request ID into the client call details.
3563
36- This method adds all key-value pairs from the default metadata dictionary to the
37- client call details metadata. If the client call details don't have metadata,
38- a new Metadata object is created.
64+ This method adds:
65+ - Default metadata (accept: application/grpc)
66+ - x-request-id header with context-based or UUID4 value
3967
4068 :param call_details: The client call details to inject metadata into
4169 :return: A new ClientCallDetails object with the injected metadata
4270 """
43- return with_metadata (call_details , _default_metadata )
71+ # Generate request ID and combine with default metadata
72+ request_id = _generate_request_id ()
73+ combined_metadata = Metadata (
74+ ("accept" , "application/grpc" ),
75+ ("x-request-id" , request_id ),
76+ )
77+ return with_metadata (call_details , combined_metadata )
4478
4579
4680class DefaultMetadataUnaryUnaryInterceptor (_BaseDefaultMetadataInterceptor , grpc .aio .UnaryUnaryClientInterceptor ):
0 commit comments