CodeSampleX

Beispiel

retry 0.12.0: retry operation with exponential backoff and custom timeouts

Verifiziertes Beispiel für npm retry 0.12.0: retry operation with exponential backoff and custom timeouts. Der Vertrag lief auf node 22 · linux alpine/x64 …

sha256:48c9c893aac9f3eec87938f0ac46c6f2de74559094daf5c2ef115d30cfcaf3f0

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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-28

Fall

HOW
Ziel
retry operation with exponential backoff and custom timeouts
Pakete
Symbole
  • retry.operation
  • retry.timeouts
Umgebung
node 22.23.2
Erstellt
2026-08-28T05:18:30Z

Contract

  1. retry.timeouts calculates ascending exponential backoff timeouts using retries, factor, minTimeout, and maxTimeout
  2. retry.timeouts throws an Error when minTimeout is greater than maxTimeout and returns a copy when given an array
  3. retry.operation creates a RetryOperation instance initialized with options or explicit timeouts
  4. operation.attempt invokes callback with current attempt count starting at 1
  5. operation.retry schedules next attempt and returns true on error when retries remain
  6. operation.retry returns false when no error is passed or retry attempts are exhausted
  7. operation.errors and operation.mainError track failure errors and identify the most frequent error
  8. operation.stop clears remaining timeouts and halts further retry scheduling
  9. operation.reset restores the initial timeouts and resets attempt count back to 1
  10. executeWithRetry executes an async function with exponential retry logic until resolution or rejection

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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 operation with exponential backoff and custom timeouts
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/retry@0.12.0
Demonstrate these symbols/APIs:
  - retry.operation
  - retry.timeouts

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:c97f9cb87086e6bc5554e7315d5acb4d1f51e4bfe46375b79ed7e630a2976a46","contract":["retry.timeouts calculates ascending exponential backoff timeouts using retries, factor, minTimeout, and maxTimeout","retry.timeouts throws an Error when minTimeout is greater than maxTimeout and returns a copy when given an array","retry.operation creates a RetryOperation instance initialized with options or explicit timeouts","operation.attempt invokes callback with current attempt count starting at 1","operation.retry schedules next attempt and returns true on error when retries remain","operation.retry returns false when no error is passed or retry attempts are exhausted","operation.errors and operation.mainError track failure errors and identify the most frequent error","operation.stop clears remaining timeouts and halts further retry scheduling","operation.reset restores the initial timeouts and resets attempt count back to 1","executeWithRetry executes an async function with exponential retry logic until resolution or rejection"],"goal":"retry operation with exponential backoff and custom timeouts","kind":"HOW","packages":["pkg:npm/retry@0.12.0"],"schemaVersion":1,"symbols":["retry.operation","retry.timeouts"]},"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/retry@0.12.0"],"schemaVersion":1,"subject":"pkg:npm/retry@0.12.0","symbols":["retry.operation","retry.timeouts"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-retry",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-retry",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "retry": "0.12.0"
      }
    },
    "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-retry",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for retry@0.12.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "retry": "0.12.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "retry operation with exponential backoff and custom timeouts",
  "kind": "HOW",
  "packages": [
    "pkg:npm/retry@0.12.0"
  ],
  "symbols": [
    "retry.operation",
    "retry.timeouts"
  ]
}
src/index.js
'use strict';

const retry = require('retry');

/**
 * Calculates exponential backoff timeout intervals.
 *
 * @param {object|number[]} [options] - Retry options or explicit timeout array.
 * @returns {number[]} Array of timeouts in milliseconds.
 */
function calculateTimeouts(options) {
  return retry.timeouts(options);
}

/**
 * Executes an asynchronous operation with retry logic and exponential backoff.
 *
 * @param {(currentAttempt: number) => Promise<any>} fn - Async function to execute.
 * @param {object|number[]} [options] - Retry options (retries, minTimeout, factor, maxTimeout).
 * @returns {Promise<any>} Resolves with result or rejects with mainError.
 */
function executeWithRetry(fn, options) {
  return new Promise((resolve, reject) => {
    const operation = retry.operation(options);

    operation.attempt(async (currentAttempt) => {
      try {
        const result = await fn(currentAttempt);
        resolve(result);
      } catch (err) {
        if (operation.retry(err)) {
          return;
        }
        reject(operation.mainError());
      }
    });
  });
}

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

const require = createRequire(import.meta.url);
const retry = require('retry');
const { calculateTimeouts, executeWithRetry } = require('../src/index.js');

async function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function testAll() {
  // 1. Export verification
  assert.equal(typeof retry.operation, 'function', 'retry.operation must be a function');
  assert.equal(typeof retry.timeouts, 'function', 'retry.timeouts must be a function');
  assert.equal(typeof retry.createTimeout, 'function', 'retry.createTimeout must be a function');
  assert.equal(typeof retry.wrap, 'function', 'retry.wrap must be a function');
  assert.equal(typeof calculateTimeouts, 'function', 'calculateTimeouts helper must be a function');
  assert.equal(typeof executeWithRetry, 'function', 'executeWithRetry helper must be a function');

  // 2. retry.timeouts calculation and options
  const defaultTimeouts = retry.timeouts();
  assert.equal(defaultTimeouts.length, 10, 'default timeouts array length must be 10');
  assert.deepEqual(
    defaultTimeouts,
    [1000, 2000, 4000, 8000, 16000, 32000, 64000, 128000, 256000, 512000],
    'default timeouts must follow 1s exponential backoff'
  );

  const customTimeouts = retry.timeouts({
    retries: 3,
    minTimeout: 50,
    factor: 2,
    maxTimeout: 150
  });
  assert.deepEqual(customTimeouts, [50, 100, 150], 'custom timeouts must respect retries, factor, and maxTimeout');

  // Array passthrough
  const explicitArray = [25, 50, 75];
  const passedArray = retry.timeouts(explicitArray);
  assert.deepEqual(passedArray, [25, 50, 75], 'timeouts should copy custom array');
  assert.notEqual(passedArray, explicitArray, 'returned array should be a new array copy');

  // minTimeout > maxTimeout error
  assert.throws(
    () => {
      retry.timeouts({ minTimeout: 200, maxTimeout: 100 });
    },
    {
      name: 'Error',
      message: 'minTimeout is greater than maxTimeout'
    },
    'retry.timeouts must throw if minTimeout > maxTimeout'
  );

  // 3. retry.operation instantiation and initial state
  const op = retry.operation({ retries: 2, minTimeout: 10, factor: 1 });
  assert.equal(op.attempts(), 1, 'initial attempts count before attempt() should be 1');
  assert.deepEqual(op.errors(), [], 'initial errors should be empty');
  assert.equal(op.mainError(), null, 'initial mainError should be null');

  // 4. RetryOperation lifecycle: retry, attempts, errors, mainError
  let attemptInCallback = 0;
  const retryPromise = new Promise((resolve) => {
    op.attempt((currentAttempt) => {
      attemptInCallback = currentAttempt;
      if (currentAttempt === 1) {
        assert.equal(op.attempts(), 1);
        const willRetry = op.retry(new Error('transient error'));
        assert.equal(willRetry, true, 'first retry should succeed');
      } else if (currentAttempt === 2) {
        assert.equal(op.attempts(), 2);
        const willRetry = op.retry(new Error('transient error'));
        assert.equal(willRetry, true, 'second retry should succeed');
      } else {
        assert.equal(op.attempts(), 3);
        const willRetry = op.retry(new Error('final error'));
        assert.equal(willRetry, false, 'retry should return false when retries exhausted');
        resolve();
      }
    });
  });

  await retryPromise;
  assert.equal(attemptInCallback, 3, 'total attempts should be 3');
  assert.equal(op.errors().length, 3, 'all 3 errors should be recorded');
  assert.equal(op.mainError().message, 'transient error', 'mainError should be most frequent error');

  // 5. operation.retry with falsy error
  const opNoErr = retry.operation({ retries: 3, minTimeout: 10 });
  assert.equal(opNoErr.retry(null), false, 'retry(null) should return false');
  assert.equal(opNoErr.retry(undefined), false, 'retry(undefined) should return false');

  // 6. operation.stop clears remaining timeouts and halts further retries
  const opStop = retry.operation({ retries: 3, minTimeout: 50 });
  opStop.stop();
  const stopRetryResult = opStop.retry(new Error('fail after stop'));
  assert.equal(stopRetryResult, false, 'retry() after stop() must return false');

  // 7. operation.reset restores state
  const opReset = retry.operation({ retries: 2, minTimeout: 10, factor: 1 });
  let resetRuns = 0;
  opReset.attempt((currentAttempt) => {
    resetRuns++;
    if (currentAttempt === 1) {
      opReset.retry(new Error('temp error'));
    }
  });
  await delay(30);
  assert.equal(resetRuns, 2, 'second attempt should have executed');
  assert.equal(opReset.attempts(), 2, 'attempts count should be 2');
  opReset.reset();
  assert.equal(opReset.attempts(), 1, 'reset() should reset attempts back to 1');

  // 8. executeWithRetry helper with success after retry
  let execAttempts = 0;
  const result = await executeWithRetry(
    async (attempt) => {
      execAttempts = attempt;
      if (attempt < 3) {
        throw new Error(`attempt ${attempt} failed`);
      }
      return 'success-value';
    },
    { retries: 3, minTimeout: 10, factor: 1 }
  );
  assert.equal(result, 'success-value', 'executeWithRetry should resolve with returned value');
  assert.equal(execAttempts, 3, 'executeWithRetry should execute 3 attempts');

  // 9. executeWithRetry helper with rejection after retries exhausted
  await assert.rejects(
    async () => {
      await executeWithRetry(
        async () => {
          throw new Error('always failing');
        },
        { retries: 2, minTimeout: 10, factor: 1 }
      );
    },
    {
      name: 'Error',
      message: 'always failing'
    },
    'executeWithRetry should reject with main error when retries exhausted'
  );

  console.log('All retry contract tests passed successfully.');
}

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

Ursprungs-Seeder

anonym