CodeSampleX

Пример

tiny-async-pool 1.3.0: limit concurrent async execution with asyncPool

Проверенный пример — npm tiny-async-pool 1.3.0: limit concurrent async execution with asyncPool. Контракт выполнен на node 22 · linux alpine/x64 · docker и…

sha256:f54e39093952c59340b653408ce7b81f00a35e5a924d62aeb6a333aa1dd2347d

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Кейс

HOW
Цель
limit concurrent async execution with asyncPool
Пакеты
Символы
  • asyncPool
Создан
2026-08-27T20:28:20Z

Контракт

  1. assert asyncPool is exported and callable as a function
  2. assert asyncPool executes asynchronous tasks within a bounded concurrency limit
  3. assert asyncPool preserves the order of input items in the resolved results array
  4. assert asyncPool accepts various iterable objects including Array and Set
  5. assert asyncPool passes each item and the iterable source to the iterator callback function
  6. assert asyncPool rejects immediately when an iterator task throws or rejects
  7. assert asyncPool resolves to an empty array when given an empty iterable
  8. assert asyncPool runs tasks with concurrency limit greater than or equal to item count
  9. assert runWithPool and mapConcurrent helper functions wrap asyncPool for safe concurrent execution

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: limit concurrent async execution with asyncPool
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tiny-async-pool@1.3.0
Demonstrate these symbols/APIs:
  - asyncPool

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:c828f0652ff03f2b6c27bd0222a18f78b068005d4c559d51c64cd0c5db06700b","contract":["assert asyncPool is exported and callable as a function","assert asyncPool executes asynchronous tasks within a bounded concurrency limit","assert asyncPool preserves the order of input items in the resolved results array","assert asyncPool accepts various iterable objects including Array and Set","assert asyncPool passes each item and the iterable source to the iterator callback function","assert asyncPool rejects immediately when an iterator task throws or rejects","assert asyncPool resolves to an empty array when given an empty iterable","assert asyncPool runs tasks with concurrency limit greater than or equal to item count","assert runWithPool and mapConcurrent helper functions wrap asyncPool for safe concurrent execution"],"goal":"limit concurrent async execution with asyncPool","kind":"HOW","packages":["pkg:npm/tiny-async-pool@1.3.0"],"schemaVersion":1,"symbols":["asyncPool"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/tiny-async-pool@1.3.0"],"schemaVersion":1,"subject":"pkg:npm/tiny-async-pool@1.3.0","symbols":["asyncPool"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tiny-async-pool",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tiny-async-pool",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tiny-async-pool": "1.3.0"
      }
    },
    "node_modules/semver": {
      "version": "5.7.2",
      "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz",
      "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==",
      "license": "ISC",
      "bin": {
        "semver": "bin/semver"
      }
    },
    "node_modules/tiny-async-pool": {
      "version": "1.3.0",
      "resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz",
      "integrity": "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==",
      "license": "MIT",
      "dependencies": {
        "semver": "^5.5.0"
      }
    }
  }
}
package.json
{
  "name": "sample-tiny-async-pool",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of pkg:npm/tiny-async-pool@1.3.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "tiny-async-pool": "1.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "limit concurrent async execution with asyncPool",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tiny-async-pool@1.3.0"
  ],
  "symbols": [
    "asyncPool"
  ]
}
src/index.js
'use strict';

const asyncPool = require('tiny-async-pool');

/**
 * Runs an asynchronous iterator function over an iterable with a maximum concurrency limit.
 * @template T, R
 * @param {number} poolLimit - Maximum number of concurrent tasks (must be >= 1).
 * @param {Iterable<T>} iterable - Input items to iterate over.
 * @param {(item: T, iterable: Iterable<T>) => Promise<R>} iteratorFn - Async function executed for each item.
 * @returns {Promise<R[]>} Promise resolving to array of results in input order.
 */
async function runWithPool(poolLimit, iterable, iteratorFn) {
  if (typeof poolLimit !== 'number' || poolLimit < 1) {
    throw new TypeError('poolLimit must be a number greater than or equal to 1');
  }
  return asyncPool(poolLimit, iterable, iteratorFn);
}

/**
 * Maps items asynchronously with bounded concurrency.
 * @template T, R
 * @param {number} concurrency - Concurrency limit (must be >= 1).
 * @param {Iterable<T>} items - Items to iterate over.
 * @param {(item: T) => Promise<R>} mapper - Async mapping function.
 * @returns {Promise<R[]>} Mapped results array.
 */
async function mapConcurrent(concurrency, items, mapper) {
  if (typeof concurrency !== 'number' || concurrency < 1) {
    throw new TypeError('concurrency must be a number greater than or equal to 1');
  }
  return asyncPool(concurrency, items, async (item) => mapper(item));
}

module.exports = {
  asyncPool,
  runWithPool,
  mapConcurrent,
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const asyncPool = require('tiny-async-pool');
const {
  runWithPool,
  mapConcurrent,
} = require('../src/index.js');

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function runContract() {
  // 1. Module export verification
  assert(typeof asyncPool === 'function', 'asyncPool should be a function');
  assert(typeof runWithPool === 'function', 'runWithPool helper should be a function');
  assert(typeof mapConcurrent === 'function', 'mapConcurrent helper should be a function');

  // 2. Bounded concurrency limit verification
  {
    const poolLimit = 2;
    const items = [10, 20, 30, 40, 50];
    let currentlyRunning = 0;
    let maxObservedRunning = 0;

    const results = await asyncPool(poolLimit, items, async (item) => {
      currentlyRunning++;
      maxObservedRunning = Math.max(maxObservedRunning, currentlyRunning);
      await delay(15);
      currentlyRunning--;
      return item * 2;
    });

    assert.strictEqual(maxObservedRunning <= poolLimit, true, `Max concurrent tasks (${maxObservedRunning}) must not exceed poolLimit (${poolLimit})`);
    assert.deepStrictEqual(results, [20, 40, 60, 80, 100], 'Results must match mapped item values in input order');
  }

  // 3. Results order preservation with variable task execution durations
  {
    const items = [50, 10, 30, 5];
    const results = await asyncPool(2, items, async (duration) => {
      await delay(duration);
      return `done-${duration}`;
    });

    assert.deepStrictEqual(
      results,
      ['done-50', 'done-10', 'done-30', 'done-5'],
      'Results must be returned in original item order despite varied completion times'
    );
  }

  // 4. Support for generic iterables (Set, Map values)
  {
    const itemSet = new Set(['alpha', 'beta', 'gamma']);
    const setResults = await asyncPool(2, itemSet, async (str) => {
      await delay(5);
      return str.toUpperCase();
    });
    assert.deepStrictEqual(setResults, ['ALPHA', 'BETA', 'GAMMA'], 'asyncPool should accept a Set iterable');

    const itemMap = new Map([['k1', 1], ['k2', 2]]);
    const mapResults = await asyncPool(2, itemMap.values(), async (val) => {
      await delay(5);
      return val * 10;
    });
    assert.deepStrictEqual(mapResults, [10, 20], 'asyncPool should accept Map iterator');
  }

  // 5. Iterator callback arguments verification (item, iterable)
  {
    const sourceArray = ['first', 'second'];
    const seenArgs = [];
    await asyncPool(2, sourceArray, async (item, iterable) => {
      seenArgs.push({ item, iterable });
      return item;
    });

    assert.strictEqual(seenArgs.length, 2);
    assert.strictEqual(seenArgs[0].item, 'first');
    assert.strictEqual(seenArgs[0].iterable, sourceArray, 'iteratorFn should receive source iterable as 2nd arg');
    assert.strictEqual(seenArgs[1].item, 'second');
    assert.strictEqual(seenArgs[1].iterable, sourceArray);
  }

  // 6. Immediate rejection when a task fails
  {
    let rejected = false;
    try {
      await asyncPool(2, [1, 2, 3, 4], async (num) => {
        if (num === 2) {
          throw new Error('Task error on item 2');
        }
        await delay(20);
        return num;
      });
    } catch (err) {
      rejected = true;
      assert.strictEqual(err.message, 'Task error on item 2', 'asyncPool should reject with the error thrown by task');
    }
    assert.strictEqual(rejected, true, 'asyncPool must reject if any task fails');
  }

  // 7. Empty iterable handling
  {
    let called = false;
    const emptyResult = await asyncPool(3, [], async () => {
      called = true;
    });
    assert.strictEqual(called, false, 'iteratorFn must not be called for empty iterable');
    assert.deepStrictEqual(emptyResult, [], 'asyncPool should resolve to empty array for empty iterable');
  }

  // 8. Pool limit larger than or equal to item count
  {
    const items = [1, 2, 3];
    let maxRunning = 0;
    let running = 0;
    const results = await asyncPool(10, items, async (val) => {
      running++;
      maxRunning = Math.max(maxRunning, running);
      await delay(10);
      running--;
      return val * 3;
    });
    assert.deepStrictEqual(results, [3, 6, 9]);
    assert.strictEqual(maxRunning, 3, 'All tasks should run concurrently when poolLimit >= items.length');
  }

  // 9. Helper wrapper functions verification
  {
    const wrappedResults = await runWithPool(2, [10, 20], async (x) => x + 1);
    assert.deepStrictEqual(wrappedResults, [11, 21], 'runWithPool wrapper should return results');

    let poolLimitError = false;
    try {
      await runWithPool(0, [1], async (x) => x);
    } catch (err) {
      poolLimitError = true;
      assert(err instanceof TypeError, 'runWithPool should throw TypeError for poolLimit < 1');
    }
    assert.strictEqual(poolLimitError, true);

    const mapped = await mapConcurrent(2, ['a', 'b', 'c'], async (s) => s.repeat(2));
    assert.deepStrictEqual(mapped, ['aa', 'bb', 'cc'], 'mapConcurrent helper should map items');
  }

  console.log('All tiny-async-pool contract assertions passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Исходный сидер

аноним