11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci// Test that async ids that are added to the destroy queue while running a
31cb0ef41Sopenharmony_ci// `destroy` callback are handled correctly.
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ciconst common = require('../common');
61cb0ef41Sopenharmony_ciconst assert = require('assert');
71cb0ef41Sopenharmony_ciconst async_hooks = require('async_hooks');
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ciconst initCalls = new Set();
101cb0ef41Sopenharmony_cilet destroyResCallCount = 0;
111cb0ef41Sopenharmony_cilet res2;
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ciasync_hooks.createHook({
141cb0ef41Sopenharmony_ci  init: common.mustCallAtLeast((id, provider) => {
151cb0ef41Sopenharmony_ci    if (provider === 'foobar')
161cb0ef41Sopenharmony_ci      initCalls.add(id);
171cb0ef41Sopenharmony_ci  }, 2),
181cb0ef41Sopenharmony_ci  destroy: common.mustCallAtLeast((id) => {
191cb0ef41Sopenharmony_ci    if (!initCalls.has(id)) return;
201cb0ef41Sopenharmony_ci
211cb0ef41Sopenharmony_ci    switch (destroyResCallCount++) {
221cb0ef41Sopenharmony_ci      case 0:
231cb0ef41Sopenharmony_ci        // Trigger the second `destroy` call.
241cb0ef41Sopenharmony_ci        res2.emitDestroy();
251cb0ef41Sopenharmony_ci        break;
261cb0ef41Sopenharmony_ci      case 2:
271cb0ef41Sopenharmony_ci        assert.fail('More than 2 destroy() invocations');
281cb0ef41Sopenharmony_ci        break;
291cb0ef41Sopenharmony_ci    }
301cb0ef41Sopenharmony_ci  }, 2)
311cb0ef41Sopenharmony_ci}).enable();
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ciconst res1 = new async_hooks.AsyncResource('foobar');
341cb0ef41Sopenharmony_cires2 = new async_hooks.AsyncResource('foobar');
351cb0ef41Sopenharmony_cires1.emitDestroy();
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_ciprocess.on('exit', () => assert.strictEqual(destroyResCallCount, 2));
38