0

I have a library I share among several micro services. The library contains helper methods to read messages from Kafka. As part of the message, I have a trace id that I want to use to start new Activity:

(simplified pseudo code)

// code that is using my library
var message = await mylibrary.GetMessageFromKafka();

// I expect Activity.Current to be set here after calling the library, but it is null

In GetMessageFromKafka I'm trying to change the current Activity:

public async Task<Message> GetMessageFromKafka()
{
  // ... read message from Kafka (not important here) ...

  var activity = new Activity("NewMessageReceived");
  activity.SetParent(messageFromKafka.Traceparent);
  activity.Start();
  return message;
}

The current activity does not propagate back to the caller, after calling GetMessageFromKafka(), Activity.Current is null for the code that is using my library.

Is there any way to change the current activity of the parent context from my library code?

oocx
  • 780
  • 5
  • 8

1 Answers1

1

Is there any way to change the current activity of the parent context from my library code?

No. Asynchronous context doesn't ever "flow" in that direction. You'd have to either return a tuple, have a separate (synchronous) API to set the current activity, or restructure the API so that your consumers provide handler delegates instead.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 1
    Thanks! I already thought so, but hoped someone would have a clever "hack" or elegant workaround :). I currently return a result object that has a "GetResult" Method where I set the context. So the code looks something like "(await GetMessageFromKafka()).GetResult()". Not pretty, but it works. – oocx Aug 15 '22 at 17:15