CodeSampleX

샘플

jest-worker 27.5.1: execute exported worker functions in parallel with Worker pool and shut down

검증된 샘플 — npm jest-worker 27.5.1: execute exported worker functions in parallel with Worker pool and shut down. node 22 · linux alpine/x64 · docker에서…

sha256:98f59ba510be78133f81990262a4b0c1bde5959243ec82052e7499080d666f78

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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
목표
execute exported worker functions in parallel with Worker pool and shut down
패키지
심벌
  • Worker
  • Worker.end
생성일
2026-08-27T23:15:51Z

컨트랙트

  1. Worker initializes worker pool with worker_threads and executes synchronous exported functions
  2. Worker executes asynchronous exported functions and resolves returned Promises
  3. Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end
  4. Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises
  5. Worker executes setup lifecycle hook with setupArgs during worker initialization
  6. Worker supports forked child process mode and terminates with Worker.end

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • src/worker.cjs
  • 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: execute exported worker functions in parallel with Worker pool and shut down
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jest-worker@27.5.1
Demonstrate these symbols/APIs:
  - Worker
  - Worker.end

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:8c8c9c25377cae62468ee59eda236d0d23b6efd867403de2a5644a68498f15eb","contract":["Worker initializes worker pool with worker_threads and executes synchronous exported functions","Worker executes asynchronous exported functions and resolves returned Promises","Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end","Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises","Worker executes setup lifecycle hook with setupArgs during worker initialization","Worker supports forked child process mode and terminates with Worker.end"],"goal":"execute exported worker functions in parallel with Worker pool and shut down","kind":"HOW","packages":["pkg:npm/jest-worker@27.5.1"],"schemaVersion":1,"symbols":["Worker","Worker.end"]},"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/jest-worker@27.5.1"],"schemaVersion":1,"subject":"pkg:npm/jest-worker@27.5.1","symbols":["Worker","Worker.end"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jest-worker",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-worker",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "jest-worker": "27.5.1"
      }
    },
    "node_modules/@types/node": {
      "version": "26.4.0",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz",
      "integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/has-flag": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
      "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/jest-worker": {
      "version": "27.5.1",
      "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",
      "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*",
        "merge-stream": "^2.0.0",
        "supports-color": "^8.0.0"
      },
      "engines": {
        "node": ">= 10.13.0"
      }
    },
    "node_modules/merge-stream": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
      "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
      "license": "MIT"
    },
    "node_modules/supports-color": {
      "version": "8.1.1",
      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
      "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
      "license": "MIT",
      "dependencies": {
        "has-flag": "^4.0.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/chalk/supports-color?sponsor=1"
      }
    },
    "node_modules/undici-types": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-jest-worker",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "jest-worker": "27.5.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "execute exported worker functions in parallel with Worker pool and shut down",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jest-worker@27.5.1"
  ],
  "symbols": [
    "Worker",
    "Worker.end"
  ]
}
src/index.mjs
import { Worker } from 'jest-worker';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const __dirname = dirname(fileURLToPath(import.meta.url));
export const DEFAULT_WORKER_PATH = join(__dirname, 'worker.cjs');

/**
 * Creates a jest-worker pool pointing to the specified worker file.
 * @param {string} [workerPath] Absolute path to worker module.
 * @param {object} [options] Worker options (numWorkers, enableWorkerThreads, etc.).
 * @returns {Worker} Worker instance.
 */
export function createWorkerPool(workerPath = DEFAULT_WORKER_PATH, options = {}) {
  return new Worker(workerPath, {
    numWorkers: options.numWorkers ?? 2,
    enableWorkerThreads: options.enableWorkerThreads ?? true,
    ...options
  });
}

/**
 * Runs a batch of tasks concurrently across worker threads and terminates the pool.
 * @param {Array<{ id: number, payload: number }>} items Items to process.
 * @param {object} [options] Worker options.
 * @returns {Promise<Array<any>>} Results of batch execution.
 */
export async function runBatchAndClose(items, options = {}) {
  const worker = createWorkerPool(DEFAULT_WORKER_PATH, options);
  try {
    const promises = items.map(item => worker.processTask(item.id, item.payload));
    return await Promise.all(promises);
  } finally {
    await worker.end();
  }
}

export { Worker };
export default Worker;
src/worker.cjs
/**
 * Worker module providing compute tasks for jest-worker pool.
 */

let initializedState = null;

function setup(initVal) {
  initializedState = initVal || 'ready';
}

function teardown() {
  initializedState = null;
}

function getStatus() {
  return initializedState;
}

function computeSum(a, b) {
  return a + b;
}

async function transformText(text) {
  return text.toUpperCase();
}

function processTask(id, payload) {
  return {
    taskId: id,
    processed: true,
    result: payload * 2
  };
}

function failingTask(msg) {
  throw new Error(msg || 'task failed');
}

module.exports = {
  setup,
  teardown,
  getStatus,
  computeSum,
  transformText,
  processTask,
  failingTask
};
test/contract.mjs
import assert from 'node:assert/strict';
import { Worker } from 'jest-worker';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { createWorkerPool, runBatchAndClose, DEFAULT_WORKER_PATH } from '../src/index.mjs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const workerPath = join(__dirname, '../src/worker.cjs');

// 1. Worker initializes worker pool with worker_threads and executes synchronous exported functions
{
  const worker = new Worker(workerPath, {
    numWorkers: 2,
    enableWorkerThreads: true
  });

  const sum = await worker.computeSum(15, 27);
  assert.equal(sum, 42);

  const endResult = await worker.end();
  assert.equal(endResult.forceExited, false);
}

// 2. Worker executes asynchronous exported functions and resolves returned Promises
{
  const worker = new Worker(workerPath, {
    numWorkers: 2,
    enableWorkerThreads: true
  });

  const res = await worker.transformText('hello jest worker');
  assert.equal(res, 'HELLO JEST WORKER');

  const endResult = await worker.end();
  assert.equal(endResult.forceExited, false);
}

// 3. Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end
{
  const items = [
    { id: 1, payload: 10 },
    { id: 2, payload: 20 },
    { id: 3, payload: 30 },
    { id: 4, payload: 40 }
  ];

  const results = await runBatchAndClose(items, { numWorkers: 2 });
  assert.deepEqual(results, [
    { taskId: 1, processed: true, result: 20 },
    { taskId: 2, processed: true, result: 40 },
    { taskId: 3, processed: true, result: 60 },
    { taskId: 4, processed: true, result: 80 }
  ]);
}

// 4. Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises
{
  const worker = new Worker(workerPath, {
    numWorkers: 1,
    enableWorkerThreads: true
  });

  let caughtError = null;
  try {
    await worker.failingTask('invalid payload input');
  } catch (err) {
    caughtError = err;
  }

  assert.ok(caughtError instanceof Error);
  assert.match(caughtError.message, /invalid payload input/);

  await worker.end();
}

// 5. Worker executes setup lifecycle hook with setupArgs during worker initialization
{
  const worker = new Worker(workerPath, {
    numWorkers: 1,
    enableWorkerThreads: true,
    setupArgs: ['custom-init-state']
  });

  const status = await worker.getStatus();
  assert.equal(status, 'custom-init-state');

  await worker.end();
}

// 6. Worker supports forked child process mode and terminates with Worker.end
{
  const worker = new Worker(workerPath, {
    numWorkers: 2,
    enableWorkerThreads: false
  });

  const res = await worker.computeSum(100, 200);
  assert.equal(res, 300);

  const endResult = await worker.end();
  assert.equal(endResult.forceExited, false);
}

console.log('Contract tests passed successfully.');

오리진 시더

익명