1313# limitations under the License.
1414from __future__ import annotations
1515
16- from typing import Tuple , cast , TYPE_CHECKING
16+ from typing import ClassVar , Tuple , cast , TYPE_CHECKING
17+
1718
1819import time
1920import re
2021import logging
2122import uuid
23+ import contextvars
2224
2325from enum import Enum
2426from functools import lru_cache
5456
5557INVALID_STATE_ERROR = "Invalid state for {}: {}"
5658
57- OPERATION_INTERCEPTOR_METADATA_KEY = "x-goog-operation-key"
58-
5959
6060class OperationType (Enum ):
6161 """Enum for the type of operation being performed."""
@@ -169,14 +169,12 @@ class ActiveOperationMetric:
169169 # time waiting on flow control, in nanoseconds
170170 flow_throttling_time_ns : int = 0
171171
172- @property
173- def interceptor_metadata (self ) -> tuple [str , str ]:
174- """
175- returns a tuple to attach to the grpc metadata.
176172
177- This metadata field will be read by the BigtableMetricsInterceptor to associate a request with an operation
178- """
179- return OPERATION_INTERCEPTOR_METADATA_KEY , self .uuid
173+ _active_operation_context : ClassVar [contextvars .ContextVar ] = contextvars .ContextVar ("active_operation_context" )
174+
175+ @classmethod
176+ def get_active (cls ):
177+ return cls ._active_operation_context .get (None )
180178
181179 @property
182180 def state (self ) -> OperationState :
@@ -190,6 +188,9 @@ def state(self) -> OperationState:
190188 else :
191189 return OperationState .ACTIVE_ATTEMPT
192190
191+ def __post_init__ (self ):
192+ self ._active_operation_context .set (self )
193+
193194 def start (self ) -> None :
194195 """
195196 Optionally called to mark the start of the operation. If not called,
@@ -200,6 +201,7 @@ def start(self) -> None:
200201 if self .state != OperationState .CREATED :
201202 return self ._handle_error (INVALID_STATE_ERROR .format ("start" , self .state ))
202203 self .start_time_ns = time .monotonic_ns ()
204+ self ._active_operation_context .set (self )
203205
204206 def start_attempt (self ) -> ActiveAttemptMetric | None :
205207 """
@@ -214,6 +216,7 @@ def start_attempt(self) -> ActiveAttemptMetric | None:
214216 return self ._handle_error (
215217 INVALID_STATE_ERROR .format ("start_attempt" , self .state )
216218 )
219+ self ._active_operation_context .set (self )
217220
218221 try :
219222 # find backoff value before this attempt
@@ -365,13 +368,6 @@ def end_with_success(self):
365368 """
366369 return self .end_with_status (StatusCode .OK )
367370
368- def cancel (self ):
369- """
370- Called to cancel an operation without processing emitting it.
371- """
372- for handler in self .handlers :
373- handler .on_operation_cancelled (self )
374-
375371 @staticmethod
376372 def _exc_to_status (exc : BaseException ) -> StatusCode :
377373 """
0 commit comments