@@ -42,8 +42,43 @@ extern __thread bthread::LocalStorage tls_bls;
4242
4343namespace brpc {
4444
45+ // ============================================================================
46+ // Span Lifecycle Management API Compatibility Layer
47+ // ============================================================================
48+ //
49+ // COMPATIBILITY NOTE:
50+ // brpc uses std::shared_ptr<Span> internally
51+ // to prevent use-after-free bugs in async RPC callbacks.
52+ //
53+ // For backward compatibility with existing protocol extensions, external APIs
54+ // can return raw pointers (Span*) by default. To enable the modern shared_ptr
55+ // API, compile with -DBRPC_SPAN_ENABLE_SHARED_PTR_API=1.
56+ //
57+ // MIGRATION GUIDE:
58+ // - Legacy mode (default): SpanPtr = Span*
59+ // Users must ensure the Span outlives their usage (typically by keeping
60+ // the Controller alive).
61+ //
62+ // - Modern mode (recommended): SpanPtr = std::shared_ptr<Span>
63+ // Automatic lifetime management, safer for async operations.
64+ //
65+ // ============================================================================
66+
67+ #ifndef BRPC_SPAN_ENABLE_SHARED_PTR_API
68+ #define BRPC_SPAN_ENABLE_SHARED_PTR_API 0 // Default: legacy mode for compatibility
69+ #endif
70+
4571class Span ;
4672
73+ #if BRPC_SPAN_ENABLE_SHARED_PTR_API
74+ // Modern API: Return shared_ptr for safe lifecycle management
75+ using SpanPtr = std::shared_ptr<Span>;
76+ #else
77+ // Legacy API: Return raw pointer for backward compatibility
78+ // WARNING: Users must ensure the Span outlives their usage
79+ using SpanPtr = Span*;
80+ #endif
81+
4782void SetTlsParentSpan (std::shared_ptr<Span> span);
4883std::shared_ptr<Span> GetTlsParentSpan ();
4984void ClearTlsParentSpan ();
@@ -252,7 +287,7 @@ friend class SpanContainer;
252287
253288class SpanContainer : public bvar ::Collected {
254289public:
255- explicit SpanContainer (std::shared_ptr<Span> span) : _span(span) {}
290+ explicit SpanContainer (const std::shared_ptr<Span>& span) : _span(span) {}
256291 ~SpanContainer () {}
257292
258293 // Implementations of bvar::Collected
0 commit comments