| 1 | # Subtask Span propagation example. |
| 2 | |
| 3 | This example shows an active `Span` being simply propagated to the subtasks -either threads or coroutines-, and finished **by** the parent task. In real-life scenarios instrumentation libraries may help with `Span` propagation **if** not offered by default (see implementation details below), but we show here the case without such help. |
| 4 | |
| 5 | Implementation details: |
| 6 | - For `threading`, `gevent` and `asyncio` the `Span` is manually passed down the call chain, being manually reactivated it in each corotuine/task. |
| 7 | - For `tornado` and `contextvars`, the active `Span` is not passed down the chain nor activated because the context is implicitly propagated. |
| 8 | |
| 9 | `threading` implementation: |
| 10 | ```python |
| 11 | def parent_task(self, message): |
| 12 | with self.tracer.start_active_span('parent') as scope: |
| 13 | f = self.executor.submit(self.child_task, message, scope.span) |
| 14 | res = f.result() |
| 15 | |
| 16 | return res |
| 17 | |
| 18 | def child_task(self, message, span): |
| 19 | with self.tracer.scope_manager.activate(span, False): |
| 20 | with self.tracer.start_active_span('child'): |
| 21 | return '%s::response' % message |
| 22 | ``` |
| 23 | |
| 24 | `tornado` implementation: |
| 25 | ```python |
| 26 | def parent_task(self, message): |
| 27 | with self.tracer.start_active_span('parent'): |
| 28 | res = yield self.child_task(message) |
| 29 | |
| 30 | raise gen.Return(res) |
| 31 | |
| 32 | @gen.coroutine |
| 33 | def child_task(self, message): |
| 34 | # No need to pass/activate the parent Span, as |
| 35 | # it stays in the context. |
| 36 | with self.tracer.start_active_span('child'): |
| 37 | raise gen.Return('%s::response' % message) |
| 38 | ``` |