CodeSampleX

샘플

promise-retry 2.0.1: retry async operation with retry callback and backoff options

검증된 샘플 — npm promise-retry 2.0.1: retry async operation with retry callback and backoff options. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:41fb4b9d6121293d532146a8df853227fd4fea451cf16c0ea24d305563c49182

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

컨트랙트

  1. promiseRetry executes an async operation and resolves with its returned value when successful on first attempt
  2. promiseRetry retries an operation when retry callback is invoked with an error until it succeeds
  3. promiseRetry provides 1-based attempt numbers to the operation callback on each retry attempt
  4. promiseRetry rejects with the last error when the configured retries count is exhausted
  5. promiseRetry immediately rejects without retrying when an unhandled error is thrown without calling retry
  6. promiseRetry accepts retry options as either the first or second argument
  7. promiseRetry applies exponential backoff with custom minTimeout and factor settings
  8. promiseRetry handles synchronous values returned from the operation function

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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: retry async operation with retry callback and backoff options
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/promise-retry@2.0.1
Demonstrate these symbols/APIs:
  - promiseRetry

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:d3f451d0258ec1e0dd2873c46b8e5dc9aa88b0daeee7d21e4574b3203964ef98","contract":["promiseRetry executes an async operation and resolves with its returned value when successful on first attempt","promiseRetry retries an operation when retry callback is invoked with an error until it succeeds","promiseRetry provides 1-based attempt numbers to the operation callback on each retry attempt","promiseRetry rejects with the last error when the configured retries count is exhausted","promiseRetry immediately rejects without retrying when an unhandled error is thrown without calling retry","promiseRetry accepts retry options as either the first or second argument","promiseRetry applies exponential backoff with custom minTimeout and factor settings","promiseRetry handles synchronous values returned from the operation function"],"goal":"retry async operation with retry callback and backoff options","kind":"HOW","packages":["pkg:npm/promise-retry@2.0.1"],"schemaVersion":1,"symbols":["promiseRetry"]},"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/promise-retry@2.0.1"],"schemaVersion":1,"subject":"pkg:npm/promise-retry@2.0.1","symbols":["promiseRetry"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-promise-retry",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-promise-retry",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "promise-retry": "2.0.1"
      }
    },
    "node_modules/err-code": {
      "version": "2.0.3",
      "resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",
      "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",
      "license": "MIT"
    },
    "node_modules/promise-retry": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",
      "integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",
      "license": "MIT",
      "dependencies": {
        "err-code": "^2.0.2",
        "retry": "^0.12.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/retry": {
      "version": "0.12.0",
      "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
      "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
      "license": "MIT",
      "engines": {
        "node": ">= 4"
      }
    }
  }
}
package.json
{
  "name": "sample-promise-retry",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "promise-retry": "2.0.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "retry async operation with retry callback and backoff options",
  "kind": "HOW",
  "packages": [
    "pkg:npm/promise-retry@2.0.1"
  ],
  "symbols": [
    "promiseRetry"
  ]
}
src/index.mjs
import promiseRetry from 'promise-retry';

/**
 * Execute an operation with retry logic using promise-retry.
 * @template T
 * @param {(retry: (err: any) => never, number: number) => Promise<T> | T} fn Operation callback
 * @param {object} [options] Retry options
 * @returns {Promise<T>} Result of the operation
 */
export function executeWithRetry(fn, options) {
  return promiseRetry(fn, options);
}

/**
 * Execute an operation with backoff options passed as first argument.
 * @template T
 * @param {object} options Retry options
 * @param {(retry: (err: any) => never, number: number) => Promise<T> | T} fn Operation callback
 * @returns {Promise<T>} Result of the operation
 */
export function executeWithOptionsFirst(options, fn) {
  return promiseRetry(options, fn);
}

export { promiseRetry };
export default promiseRetry;
test/contract.mjs
import assert from 'node:assert/strict';
import { promiseRetry, executeWithRetry, executeWithOptionsFirst } from '../src/index.mjs';

// 1. promiseRetry executes an async operation and resolves with its returned value when successful on first attempt
{
  let attempts = 0;
  const result = await promiseRetry(async (retry, number) => {
    attempts++;
    return 'success-value';
  });

  assert.equal(result, 'success-value');
  assert.equal(attempts, 1);

  const helperResult = await executeWithRetry(async () => 'helper-success');
  assert.equal(helperResult, 'helper-success');
}

// 2. promiseRetry retries an operation when retry callback is invoked with an error until it succeeds
{
  let attempts = 0;
  const result = await promiseRetry(async (retry, number) => {
    attempts++;
    if (attempts < 3) {
      return retry(new Error(`Attempt ${attempts} failed`));
    }
    return `recovered at attempt ${attempts}`;
  }, { retries: 5, minTimeout: 5, factor: 1 });

  assert.equal(result, 'recovered at attempt 3');
  assert.equal(attempts, 3);
}

// 3. promiseRetry provides 1-based attempt numbers to the operation callback on each retry attempt
{
  const recordedNumbers = [];
  await promiseRetry(async (retry, number) => {
    recordedNumbers.push(number);
    if (number < 3) {
      return retry(new Error('retry'));
    }
    return true;
  }, { retries: 3, minTimeout: 5, factor: 1 });

  assert.deepEqual(recordedNumbers, [1, 2, 3]);
}

// 4. promiseRetry rejects with the last error when the configured retries count is exhausted
{
  let attempts = 0;
  let caughtError = null;

  try {
    await promiseRetry(async (retry, number) => {
      attempts++;
      return retry(new Error(`Failure on attempt ${number}`));
    }, { retries: 2, minTimeout: 5, factor: 1 });
  } catch (err) {
    caughtError = err;
  }

  assert(caughtError instanceof Error);
  assert.equal(caughtError.message, 'Failure on attempt 3');
  assert.equal(attempts, 3);
}

// 5. promiseRetry immediately rejects without retrying when an unhandled error is thrown without calling retry
{
  let attempts = 0;
  let caughtError = null;

  try {
    await promiseRetry(async (retry, number) => {
      attempts++;
      throw new Error('Immediate fatal error');
    }, { retries: 3, minTimeout: 5, factor: 1 });
  } catch (err) {
    caughtError = err;
  }

  assert(caughtError instanceof Error);
  assert.equal(caughtError.message, 'Immediate fatal error');
  assert.equal(attempts, 1);
}

// 6. promiseRetry accepts retry options as either the first or second argument
{
  let attemptsFirst = 0;
  const resFirst = await executeWithOptionsFirst({ retries: 2, minTimeout: 5, factor: 1 }, async (retry, number) => {
    attemptsFirst++;
    if (attemptsFirst < 2) {
      return retry(new Error('retry-first'));
    }
    return 'options-first-ok';
  });
  assert.equal(resFirst, 'options-first-ok');
  assert.equal(attemptsFirst, 2);

  let attemptsSecond = 0;
  const resSecond = await executeWithRetry(async (retry, number) => {
    attemptsSecond++;
    if (attemptsSecond < 2) {
      return retry(new Error('retry-second'));
    }
    return 'options-second-ok';
  }, { retries: 2, minTimeout: 5, factor: 1 });
  assert.equal(resSecond, 'options-second-ok');
  assert.equal(attemptsSecond, 2);
}

// 7. promiseRetry applies exponential backoff with custom minTimeout and factor settings
{
  const timestamps = [];
  await promiseRetry(async (retry, number) => {
    timestamps.push(Date.now());
    if (number < 3) {
      return retry(new Error('retry-timing'));
    }
    return true;
  }, { retries: 3, minTimeout: 20, factor: 2, randomize: false });

  assert.equal(timestamps.length, 3);
  const firstDelay = timestamps[1] - timestamps[0];
  const secondDelay = timestamps[2] - timestamps[1];
  assert(firstDelay >= 15, `First delay was ${firstDelay}ms, expected >= 15ms`);
  assert(secondDelay >= 30, `Second delay was ${secondDelay}ms, expected >= 30ms`);
}

// 8. promiseRetry handles synchronous values returned from the operation function
{
  const syncResult = await promiseRetry((retry, number) => {
    return 'synchronous-return-value';
  });
  assert.equal(syncResult, 'synchronous-return-value');
}

console.log('Contract assertions passed.');

오리진 시더

익명