🔗

Cloud Pub/SubのPull式でdatadog Spanをリンクする

に公開

背景

Cloud Pub/Subでdatadogの分散トレーシングとしてPub側とSub側を紐づけたい。
Push式の場合はSubscriptionで no_wrapper に設定した上で、以下のようにしてPublishすることで同じトレース(ルートSpanが同じ)に紐づいて子Spanになる。

await topic.publishMessage({
  json: payload,
  attributes: {
    'Content-Type': 'application/json',
    'x-datadog-trace-id': tracer.scope().active()?.context().toTraceId() || '',
    'x-datadog-parent-id': tracer.scope().active()?.context().toSpanId() || '',
  },
});

Pull式の場合はAuto Instrumentationの仕組みが効かなくて関連付かない。

方法

Subscribeしたmessageに対して、以下のようにすると spanContext が得られる。
(Publish側は背景同様)

const spanContext = tracer.extract('text_map', message.attributes)

その上で以下のようにするとSpan Linksとして関連付けることができる。

await tracer.trace('pubsub.message', {links: spanContext ? [{context: spanContext}] : undefined}, async () => {
 // ...
})

links の代わりに childOf を使用すれば子Spanになる(はず)。

Discussion