CodeSampleX

샘플

tinypool 1.1.1: Tinypool

검증된 샘플 — npm tinypool 1.1.1: Tinypool. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: createIsolatedPool initializes Tinypool with…

sha256:058546b5c29618fd9f05b450c8e7c194649777c548cf67a3cf84f373b91d9d46

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-03

케이스

HOW
목표
verify tinypool.Tinypool in pkg:npm/tinypool@1.1.1
패키지
심벌
  • tinypool.Tinypool
환경
node 22.23.2
생성일
2026-09-03T14:05:18Z

컨트랙트

  1. createIsolatedPool initializes Tinypool with isolateWorkers option
  2. isolateWorkers resets worker execution state across consecutive tasks
  3. createConfiguredPool passes workerData accessible via Tinypool.workerData
  4. queueSize tracks pending tasks and cancelPendingTasks aborts queued tasks
  5. createChildProcessPool executes tasks under child_process runtime
  6. destroy gracefully terminates worker pool threads

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • src/worker.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: verify tinypool.Tinypool in pkg:npm/tinypool@1.1.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tinypool@1.1.1
Demonstrate these symbols/APIs:
  - tinypool.Tinypool
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:f4a4459b7895a97d38433945e4fe3cfb5acfda6d166d6367be121065fbbb6d84","constraints":{"executionContext":"node"},"contract":["createIsolatedPool initializes Tinypool with isolateWorkers option","isolateWorkers resets worker execution state across consecutive tasks","createConfiguredPool passes workerData accessible via Tinypool.workerData","queueSize tracks pending tasks and cancelPendingTasks aborts queued tasks","createChildProcessPool executes tasks under child_process runtime","destroy gracefully terminates worker pool threads"],"goal":"verify tinypool.Tinypool in pkg:npm/tinypool@1.1.1","kind":"HOW","packages":["pkg:npm/tinypool@1.1.1"],"schemaVersion":1,"symbols":["tinypool.Tinypool"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/tinypool@1.1.1"],"schemaVersion":1,"subject":"pkg:npm/tinypool@1.1.1","symbols":["tinypool.Tinypool"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tinypool",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tinypool",
      "version": "1.0.0",
      "dependencies": {
        "tinypool": "1.1.1"
      }
    },
    "node_modules/tinypool": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
      "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
      "license": "MIT",
      "engines": {
        "node": "^18.0.0 || >=20.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-tinypool",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of tinypool worker isolation, workerData configuration, and queue task cancellation",
  "main": "src/index.js",
  "dependencies": {
    "tinypool": "1.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify tinypool.Tinypool in pkg:npm/tinypool@1.1.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tinypool@1.1.1"
  ],
  "symbols": [
    "tinypool.Tinypool"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict';

const { Tinypool } = require('tinypool');
const path = require('node:path');

/**
 * Creates a Tinypool worker pool with isolated workers.
 * @param {object} [options] - Additional Tinypool options
 * @returns {Tinypool}
 */
function createIsolatedPool(options = {}) {
  const workerPath = path.resolve(__dirname, 'worker.js');
  return new Tinypool({
    filename: workerPath,
    minThreads: 1,
    maxThreads: 1,
    isolateWorkers: true,
    ...options
  });
}

/**
 * Creates a Tinypool worker pool with custom workerData.
 * @param {any} workerData - Data passed to workers
 * @param {object} [options] - Additional Tinypool options
 * @returns {Tinypool}
 */
function createConfiguredPool(workerData, options = {}) {
  const workerPath = path.resolve(__dirname, 'worker.js');
  return new Tinypool({
    filename: workerPath,
    minThreads: 1,
    maxThreads: 2,
    workerData,
    ...options
  });
}

/**
 * Creates a Tinypool worker pool using child_process runtime.
 * @param {object} [options] - Additional Tinypool options
 * @returns {Tinypool}
 */
function createChildProcessPool(options = {}) {
  const workerPath = path.resolve(__dirname, 'worker.js');
  return new Tinypool({
    filename: workerPath,
    runtime: 'child_process',
    minThreads: 1,
    maxThreads: 1,
    ...options
  });
}

/**
 * Runs a task on the pool.
 * @param {Tinypool} pool
 * @param {object} payload
 * @returns {Promise<any>}
 */
async function runTask(pool, payload) {
  return pool.run(payload);
}

module.exports = {
  Tinypool,
  createIsolatedPool,
  createConfiguredPool,
  createChildProcessPool,
  runTask
};
src/worker.js
'use strict';

const { Tinypool } = require('tinypool');

let state = 0;

/**
 * Worker task handler.
 * @param {object} task - Task payload
 * @returns {Promise<any>|any}
 */
module.exports = async (task) => {
  if (!task || typeof task !== 'object') {
    throw new TypeError('task payload must be an object');
  }

  if (task.type === 'increment') {
    state += 1;
    return state;
  }

  if (task.type === 'getWorkerData') {
    return Tinypool.workerData;
  }

  if (task.type === 'delay') {
    await new Promise((resolve) => setTimeout(resolve, task.ms || 100));
    return { delayed: true, ms: task.ms || 100 };
  }

  if (task.type === 'compute') {
    const mult = (Tinypool.workerData && Tinypool.workerData.multiplier) || 1;
    return (task.val || 0) * mult;
  }

  return { status: 'ok', task };
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  Tinypool,
  createIsolatedPool,
  createConfiguredPool,
  createChildProcessPool,
  runTask
} = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof Tinypool, 'function', 'Tinypool should be exported as a class/constructor');
assert.strictEqual(typeof createIsolatedPool, 'function', 'createIsolatedPool should be a function');
assert.strictEqual(typeof createConfiguredPool, 'function', 'createConfiguredPool should be a function');
assert.strictEqual(typeof createChildProcessPool, 'function', 'createChildProcessPool should be a function');

// 2. isolateWorkers execution
const isolatedPool = createIsolatedPool();
assert.ok(isolatedPool instanceof Tinypool, 'isolatedPool should be an instance of Tinypool');
assert.strictEqual(isolatedPool.options.isolateWorkers, true, 'isolatedPool should have isolateWorkers option enabled');

try {
  const inc1 = await runTask(isolatedPool, { type: 'increment' });
  assert.strictEqual(inc1, 1, 'First increment task should return 1');

  const inc2 = await runTask(isolatedPool, { type: 'increment' });
  assert.strictEqual(inc2, 1, 'Second increment task should also return 1 with isolateWorkers');
} finally {
  await isolatedPool.destroy();
}

// 3. workerData configuration
const configuredPool = createConfiguredPool({ multiplier: 5, namespace: 'worker-scope' });
assert.ok(configuredPool instanceof Tinypool, 'configuredPool should be an instance of Tinypool');

try {
  const data = await runTask(configuredPool, { type: 'getWorkerData' });
  assert.deepStrictEqual(data, { multiplier: 5, namespace: 'worker-scope' }, 'Worker should access workerData via Tinypool.workerData');

  const computed = await runTask(configuredPool, { type: 'compute', val: 7 });
  assert.strictEqual(computed, 35, 'Task computation should use multiplier from workerData');
} finally {
  await configuredPool.destroy();
}

// 4. queueSize tracking and cancelPendingTasks
const queuePool = createIsolatedPool();
try {
  const blockingTask = runTask(queuePool, { type: 'delay', ms: 120 });
  const queuedTask = runTask(queuePool, { type: 'delay', ms: 50 });

  assert.strictEqual(queuePool.queueSize, 1, 'queueSize should be 1 for pending queued task');

  queuePool.cancelPendingTasks();
  assert.strictEqual(queuePool.queueSize, 0, 'queueSize should be 0 after cancelPendingTasks');

  await assert.rejects(
    queuedTask,
    (err) => err && (err.message === 'The task has been cancelled' || err.message.includes('cancel')),
    'Queued task should reject when cancelled by cancelPendingTasks'
  );

  const blockResult = await blockingTask;
  assert.strictEqual(blockResult.delayed, true, 'Active task should complete normally');
} finally {
  await queuePool.destroy();
}

// 5. child_process runtime
const childPool = createChildProcessPool();
assert.ok(childPool instanceof Tinypool, 'childPool should be an instance of Tinypool');
assert.strictEqual(childPool.options.runtime, 'child_process', 'childPool should use child_process runtime');

try {
  const childResult = await runTask(childPool, { type: 'compute', val: 12 });
  assert.strictEqual(childResult, 12, 'child_process runtime should execute tasks and return result');
} finally {
  await childPool.destroy();
}

// 6. Graceful pool termination via destroy
const testPool = createIsolatedPool();
assert.ok(testPool.threads.length >= 0);
await testPool.destroy();
assert.strictEqual(testPool.threads.length, 0, 'threads should be empty after destroy');

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

오리진 시더

익명