Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@supertenant/core / src / tracing / taskManager.js
Size: Mime:
// (c) Copyright 2023 Supertenant Ltd. - all rights reserved.
// See LICENSE file in project root for license terms.
'use strict';
const SuperBrain = require('@supertenant/superbrain');
const consts = require('@supertenant/superconsts');
const ns = require('./cls').ns;

const taskKey = 'st.task';
const cleanupKey = 'st.cleanup';

// we don't know when the continuation scope really gets cleared since we don't have access
// to the underlying async hooks. Since we can live with tasks finish later than their immediate finish
// time, we use finalizers which exist since node 14:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
const finishTaskRegistry = new FinalizationRegistry((taskId) => {
    SuperBrain.finishTask(taskId);
});

/**
 * @param {boolean} [fallbackToSharedContext=false]
 * @returns {number}
 */
function getOrCreateTask(fallbackToSharedContext = false) {
    let taskId = ns.get(taskKey, fallbackToSharedContext);
    if (taskId === null || taskId === undefined) {
        taskId = SuperBrain.createTaskAutoInc(0, consts.Task.Coroutine);
        if (taskId != 0) {
            ns.set(taskKey, taskId);
            let cleanup = new Object();
            ns.set(cleanupKey, cleanup);
            finishTaskRegistry.register(cleanup, taskId);
        }
    }
    return taskId;
}

module.exports.getOrCreateTask = getOrCreateTask;