11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst sleep = require('util').promisify(setTimeout);
51cb0ef41Sopenharmony_ciconst assert = require('assert');
61cb0ef41Sopenharmony_ciconst { executionAsyncResource, createHook } = require('async_hooks');
71cb0ef41Sopenharmony_ciconst { createServer, get } = require('http');
81cb0ef41Sopenharmony_ciconst sym = Symbol('cls');
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ci// Tests continuation local storage with the currentResource API
111cb0ef41Sopenharmony_ci// through an async function
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ciassert.ok(executionAsyncResource());
141cb0ef41Sopenharmony_ci
151cb0ef41Sopenharmony_cicreateHook({
161cb0ef41Sopenharmony_ci  init(asyncId, type, triggerAsyncId, resource) {
171cb0ef41Sopenharmony_ci    const cr = executionAsyncResource();
181cb0ef41Sopenharmony_ci    resource[sym] = cr[sym];
191cb0ef41Sopenharmony_ci  }
201cb0ef41Sopenharmony_ci}).enable();
211cb0ef41Sopenharmony_ci
221cb0ef41Sopenharmony_ciasync function handler(req, res) {
231cb0ef41Sopenharmony_ci  executionAsyncResource()[sym] = { state: req.url };
241cb0ef41Sopenharmony_ci  await sleep(10);
251cb0ef41Sopenharmony_ci  const { state } = executionAsyncResource()[sym];
261cb0ef41Sopenharmony_ci  res.setHeader('content-type', 'application/json');
271cb0ef41Sopenharmony_ci  res.end(JSON.stringify({ state }));
281cb0ef41Sopenharmony_ci}
291cb0ef41Sopenharmony_ci
301cb0ef41Sopenharmony_ciconst server = createServer(function(req, res) {
311cb0ef41Sopenharmony_ci  handler(req, res);
321cb0ef41Sopenharmony_ci});
331cb0ef41Sopenharmony_ci
341cb0ef41Sopenharmony_cifunction test(n) {
351cb0ef41Sopenharmony_ci  get(`http://localhost:${server.address().port}/${n}`, common.mustCall(function(res) {
361cb0ef41Sopenharmony_ci    res.setEncoding('utf8');
371cb0ef41Sopenharmony_ci
381cb0ef41Sopenharmony_ci    let body = '';
391cb0ef41Sopenharmony_ci    res.on('data', function(chunk) {
401cb0ef41Sopenharmony_ci      body += chunk;
411cb0ef41Sopenharmony_ci    });
421cb0ef41Sopenharmony_ci
431cb0ef41Sopenharmony_ci    res.on('end', common.mustCall(function() {
441cb0ef41Sopenharmony_ci      assert.deepStrictEqual(JSON.parse(body), { state: `/${n}` });
451cb0ef41Sopenharmony_ci    }));
461cb0ef41Sopenharmony_ci  }));
471cb0ef41Sopenharmony_ci}
481cb0ef41Sopenharmony_ci
491cb0ef41Sopenharmony_ciserver.listen(0, common.mustCall(function() {
501cb0ef41Sopenharmony_ci  server.unref();
511cb0ef41Sopenharmony_ci  for (let i = 0; i < 10; i++) {
521cb0ef41Sopenharmony_ci    test(i);
531cb0ef41Sopenharmony_ci  }
541cb0ef41Sopenharmony_ci}));
55