File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -299,24 +299,40 @@ def _install_flush_completion_handshake(client: "sentry_sdk.Client") -> None:
299299
300300 Otherwise, test assertions can be run before envelopes are captured.
301301 The span batcher flushes pending items asynchronously with the main thread.
302+ Flushes triggered by segments finishing are asynchronous, and can collect buckets
303+ that would have otherwise been flushed synchronously by `sentry_sdk.flush()`.
302304 """
303305 batcher = client .span_batcher
304306 if batcher is None :
305307 return
306308
307309 orig_flush_raw = batcher ._flush
308310 orig_flush = batcher .flush
309- done = threading .Event ()
311+ lock = threading .Lock ()
312+ drained_count = 0
313+ wake = threading .Event ()
310314
311315 def _flush (* args : "Any" , ** kwargs : "Any" ) -> "Any" :
316+ nonlocal drained_count
312317 try :
313318 return orig_flush_raw (* args , ** kwargs )
314319 finally :
315- done .set ()
320+ with lock :
321+ drained_count += 1
322+ wake .set ()
316323
317324 def flush () -> None :
318- if not done .is_set ():
319- done .wait ()
325+ nonlocal drained_count
326+ with lock :
327+ target = drained_count
328+
329+ batcher ._flush_event .set ()
330+ while True :
331+ with lock :
332+ if drained_count > target :
333+ break
334+ wake .wait ()
335+ wake .clear ()
320336 orig_flush ()
321337
322338 object .__setattr__ (batcher , "_flush" , _flush )
You can’t perform that action at this time.
0 commit comments