CodeSampleX

Exemplo

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

Amostra verificada para npm promise-retry 2.0.1: retry async operation with retry callback and backoff options. O contrato rodou em node 22 · linux…

sha256:41fb4b9d6121293d532146a8df853227fd4fea451cf16c0ea24d305563c49182

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
retry async operation with retry callback and backoff options
Pacotes
Símbolos
  • promiseRetry
Criado
2026-08-27T16:37:11Z

Contrato

  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

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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.');

Seeder de origem

anônimo