샘플
retry 0.12.0: retry operation with exponential backoff and custom timeouts
검증된 샘플 — npm retry 0.12.0: retry operation with exponential backoff and custom timeouts. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.
sha256:48c9c893aac9f3eec87938f0ac46c6f2de74559094daf5c2ef115d30cfcaf3f0
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 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-28 |
케이스
HOW- 목표
- retry operation with exponential backoff and custom timeouts
- 패키지
- 심벌
-
- retry.operation
- retry.timeouts
- 환경
- node 22.23.2
- 생성일
- 2026-08-28T05:18:30Z
컨트랙트
- 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
파일
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.js
- test/contract.mjs
소스
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.
{"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"}
{
"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"
}
}
}
}
{
"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"
}
}
{
"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"
]
}
'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
};
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);
});
오리진 시더
익명