Prevent transaction from getting added after a http(Rest) call

My code

var transaction = apm.startTransaction("Add Random Hero from ui", "Person");
    var span = apm.startSpan('Adding data');
    var hero: Person = new Person();
    hero.id = Math.floor(Math.random() * 100);
    hero.name = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
    apm.addTags(hero);
    apm.setCustomContext(hero);
    this.heroService.addH(hero)
      .subscribe(hero => {
        console.log(hero['_body']);
        if (span) span.end();
        var span = apm.startSpan('fetching data');
        this.heroService.getHeroes()
          .subscribe(heroes => {
            console.log(heroes['_body']);
            this.heroes = JSON.parse(heroes['_body']) as Person[];
            if (span) span.end();
            var transaction = apm.getCurrentTransaction();
            if (transaction) transaction.end();
          });
      });

So, soon after I make a post call to add person object transaction gets added. But the other fetch get call isn't getting recorded, because the the transaction has already been added.

Logs:
Capture

Hi @venkat6,

Thanks for reaching out.

In the RUM agent we keep track of the tasks related to a transaction in order to end the transaction automatically once all of the tasks are finished. You can use the task API (still experimental) to manually add tasks as well. As long as there are tasks remaining the transaction would not end unless transaction.end() is called explicitly.

Something like:

const taskId = transaction.addTask()

...

/* This will end the transaction automatically if there are no tasks remaining  */
transaction.removeTask(taskId) 

/* Or you can call transaction.end() if you know at this point transaction has to end. */

Let me know how this works for you.

Cheers,
Hamid

1 Like

Hi @Hamidreza,

Thanks for the quick reply.

As you have suggested, task api works like a charm.
But as mentioned it's still in beta. So, is there any other way of preventing transaction from automatically ending.

Thank you.

Currently, using the task API is the only way to prevent the transaction from ending early. The reason for this is if a http request is executed after all the transaction tasks are finished then it is not considered part of that transaction. However, I have created this issue to address this issue for custom transactions.