CodeSampleX

샘플

exponential-backoff 3.1.3: backOff

검증된 샘플 — npm exponential-backoff 3.1.3: backOff. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: backOff executes an async function and resolves…

sha256:5c54bec84008dd91d29a76ff3e26944d833a70bc3ac30ebfb200437c5bdadf65

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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-26
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-07

케이스

HOW
목표
verify pkg:npm/exponential-backoff@3.1.3
패키지
심벌
  • backOff
환경
node 22.23.2
생성일
2026-08-26T07:35:16Z

컨트랙트

  1. backOff executes an async function and resolves with its return value on the first attempt without delay
  2. backOff retries a failing async function with exponential delay and resolves when a subsequent attempt succeeds
  3. backOff rejects with the last encountered error when numOfAttempts is exceeded
  4. backOff invokes the retry callback with the error and attempt index and stops retrying when retry returns false
  5. backOff supports asynchronous retry callbacks to determine whether to continue reattempts
  6. retryWithBackoff wraps backOff and passes custom options including startingDelay, numOfAttempts, and jitter

파일

  • 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: verify pkg:npm/exponential-backoff@3.1.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/exponential-backoff@3.1.3
Demonstrate these symbols/APIs:
  - backOff

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:ab9ad279ebfd7943324a14414bb38576327fdf583a5aa42ebf15440fc3416f1e","contract":["backOff executes an async function and resolves with its return value on the first attempt without delay","backOff retries a failing async function with exponential delay and resolves when a subsequent attempt succeeds","backOff rejects with the last encountered error when numOfAttempts is exceeded","backOff invokes the retry callback with the error and attempt index and stops retrying when retry returns false","backOff supports asynchronous retry callbacks to determine whether to continue reattempts","retryWithBackoff wraps backOff and passes custom options including startingDelay, numOfAttempts, and jitter"],"goal":"verify pkg:npm/exponential-backoff@3.1.3","kind":"HOW","packages":["pkg:npm/exponential-backoff@3.1.3"],"schemaVersion":1,"symbols":["backOff"]},"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/exponential-backoff@3.1.3"],"schemaVersion":1,"subject":"pkg:npm/exponential-backoff@3.1.3","symbols":["backOff"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-exponential-backoff",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-exponential-backoff",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "exponential-backoff": "3.1.3"
      }
    },
    "node_modules/exponential-backoff": {
      "version": "3.1.3",
      "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
      "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==",
      "license": "Apache-2.0"
    }
  }
}
package.json
{
  "name": "sample-exponential-backoff",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for exponential-backoff@3.1.3",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "exponential-backoff": "3.1.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/exponential-backoff@3.1.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/exponential-backoff@3.1.3"
  ],
  "symbols": [
    "backOff"
  ]
}
src/index.js
'use strict';

const { backOff } = require('exponential-backoff');

/**
 * Retries an asynchronous operation with exponential backoff.
 *
 * @template T
 * @param {() => Promise<T>} fn - The asynchronous operation to execute.
 * @param {import('exponential-backoff').BackoffOptions} [options] - Backoff configuration options.
 * @returns {Promise<T>} Result of the operation.
 */
async function retryWithBackoff(fn, options = {}) {
  return backOff(fn, options);
}

module.exports = {
  backOff,
  retryWithBackoff
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { backOff, retryWithBackoff } = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof backOff, 'function', 'backOff export must be a function');
  assert.equal(typeof retryWithBackoff, 'function', 'retryWithBackoff export must be a function');

  // 2. Immediate success without retry
  let callCount1 = 0;
  const result1 = await backOff(async () => {
    callCount1++;
    return 'immediate-success';
  });
  assert.equal(result1, 'immediate-success');
  assert.equal(callCount1, 1, 'should only be called once on immediate success');

  // 3. Retries on failure and succeeds
  let callCount2 = 0;
  const attemptsSeen = [];
  const result2 = await backOff(async () => {
    callCount2++;
    if (callCount2 < 3) {
      throw new Error(`fail ${callCount2}`);
    }
    return 'recovered';
  }, {
    numOfAttempts: 5,
    startingDelay: 5,
    timeMultiple: 1.5,
    retry: (err, attemptNumber) => {
      assert(err instanceof Error);
      attemptsSeen.push(attemptNumber);
      return true;
    }
  });
  assert.equal(result2, 'recovered');
  assert.equal(callCount2, 3);
  assert.deepEqual(attemptsSeen, [1, 2], 'retry callback receives the 1-based attempt number that failed');

  // 4. Max attempts exceeded throws last error
  let callCount3 = 0;
  await assert.rejects(
    async () => {
      await backOff(async () => {
        callCount3++;
        throw new Error(`persistent error ${callCount3}`);
      }, {
        numOfAttempts: 3,
        startingDelay: 5
      });
    },
    {
      name: 'Error',
      message: 'persistent error 3'
    },
    'should reject with the last error when numOfAttempts is exhausted'
  );
  assert.equal(callCount3, 3);

  // 5. Abort early when retry callback returns false
  let callCount4 = 0;
  await assert.rejects(
    async () => {
      await backOff(async () => {
        callCount4++;
        const error = new Error('non-retryable error');
        error.code = 'UNRECOVERABLE';
        throw error;
      }, {
        numOfAttempts: 5,
        startingDelay: 5,
        retry: (err) => {
          return err.code !== 'UNRECOVERABLE';
        }
      });
    },
    (err) => {
      return err.message === 'non-retryable error' && err.code === 'UNRECOVERABLE';
    },
    'should stop retrying immediately when retry returns false'
  );
  assert.equal(callCount4, 1, 'should not retry after retry returns false');

  // 6. Async retry callback support
  let callCount5 = 0;
  const asyncResult = await backOff(async () => {
    callCount5++;
    if (callCount5 === 1) {
      throw new Error('transient error');
    }
    return 'async-recovered';
  }, {
    numOfAttempts: 3,
    startingDelay: 5,
    retry: async (err, attemptNumber) => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return attemptNumber < 2;
    }
  });
  assert.equal(asyncResult, 'async-recovered');
  assert.equal(callCount5, 2);

  // 7. Custom options and retryWithBackoff wrapper
  let wrapperCount = 0;
  const wrapperResult = await retryWithBackoff(async () => {
    wrapperCount++;
    if (wrapperCount < 2) {
      throw new Error('first try fail');
    }
    return 42;
  }, {
    numOfAttempts: 4,
    startingDelay: 5,
    delayFirstAttempt: false,
    jitter: 'none',
    maxDelay: 50
  });
  assert.equal(wrapperResult, 42);
  assert.equal(wrapperCount, 2);

  console.log('All exponential-backoff contract tests passed successfully.');
}

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

오리진 시더

익명