CodeSampleX

샘플

undici 6.28.0: Stream response chunks with backpressure, opaque metadata, error propagation, and abort handling using undici.stream in undici 6.28.0

검증된 샘플 — npm undici 6.28.0: Stream response chunks with backpressure, opaque metadata, error propagation, and abort handling using undici.stream in undici…

sha256:6ab8c50d30a8dd360d867bf71579564e5cbbefb90f39d00291fda834650c1d25

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

케이스

HOW
목표
Stream response chunks with backpressure, opaque metadata, error propagation, and abort handling using undici.stream in undici 6.28.0
패키지
심벌
  • undici.stream
환경
node 22.23.2
생성일
2026-08-27T20:13:22Z

컨트랙트

  1. undici.stream streams response chunks into a custom Writable stream and returns opaque metadata and response trailers
  2. undici.stream allows inspecting status code and response headers in the factory function before accepting stream chunks
  3. undici.stream aborts in-flight stream consumption when an AbortSignal triggers
  4. undici.stream rejects and propagates errors when the destination Writable stream encounters a write error

파일

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

소스 아티팩트 내려받기 (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: Stream response chunks with backpressure, opaque metadata, error propagation, and abort handling using undici.stream in undici 6.28.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/undici@6.28.0
Demonstrate these symbols/APIs:
  - undici.stream

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:c79e2b0bf966fcc16f1da970d7ba92dedf7fd9cb33bf44285b361fa16ed84c50","contract":["undici.stream streams response chunks into a custom Writable stream and returns opaque metadata and response trailers","undici.stream allows inspecting status code and response headers in the factory function before accepting stream chunks","undici.stream aborts in-flight stream consumption when an AbortSignal triggers","undici.stream rejects and propagates errors when the destination Writable stream encounters a write error"],"goal":"Stream response chunks with backpressure, opaque metadata, error propagation, and abort handling using undici.stream in undici 6.28.0","kind":"HOW","packages":["pkg:npm/undici@6.28.0"],"schemaVersion":1,"symbols":["undici.stream"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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/undici@6.28.0"],"schemaVersion":1,"subject":"pkg:npm/undici@6.28.0","symbols":["undici.stream"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "undici-stream-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "undici-stream-sample",
      "version": "1.0.0",
      "dependencies": {
        "undici": "6.28.0"
      }
    },
    "node_modules/undici": {
      "version": "6.28.0",
      "resolved": "https://registry.npmjs.org/undici/-/undici-6.28.0.tgz",
      "integrity": "sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==",
      "license": "MIT",
      "engines": {
        "node": ">=18.17"
      }
    }
  }
}
package.json
{
  "name": "undici-stream-sample",
  "version": "1.0.0",
  "dependencies": {
    "undici": "6.28.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Stream response chunks with backpressure, opaque metadata, error propagation, and abort handling using undici.stream in undici 6.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/undici@6.28.0"
  ],
  "symbols": [
    "undici.stream"
  ]
}
src/index.js
const { Writable } = require('node:stream');
const undici = require('undici');

/**
 * Streams an HTTP response body to a factory-provided Writable stream.
 *
 * @param {string | URL} url - Target URL.
 * @param {import('undici').StreamOptions} options - Stream request options.
 * @param {import('undici').StreamFactory} factory - Stream factory function receiving { statusCode, headers, opaque }.
 * @returns {Promise<import('undici').StreamData>}
 */
async function streamResponse(url, options, factory) {
  return undici.stream(url, options, factory);
}

/**
 * Collects a streamed HTTP response into a single Buffer using undici.stream.
 *
 * @param {string | URL} url - Target URL.
 * @param {import('undici').StreamOptions} [options] - Stream request options.
 * @returns {Promise<{ statusCode: number, headers: import('undici').IncomingHttpHeaders, body: Buffer, opaque: unknown, trailers: Record<string, string> }>}
 */
async function collectStream(url, options = {}) {
  const chunks = [];
  let responseStatus = 0;
  let responseHeaders = {};

  const writable = new Writable({
    write(chunk, encoding, callback) {
      chunks.push(Buffer.from(chunk));
      callback();
    },
  });

  const result = await undici.stream(
    url,
    options,
    ({ statusCode, headers, opaque }) => {
      responseStatus = statusCode;
      responseHeaders = headers;
      return writable;
    }
  );

  return {
    statusCode: responseStatus,
    headers: responseHeaders,
    body: Buffer.concat(chunks),
    opaque: result.opaque,
    trailers: result.trailers,
  };
}

/**
 * Creates and configures an offline MockAgent for intercepting undici streaming requests.
 *
 * @param {string | URL} origin - Base origin to intercept.
 * @returns {{ agent: import('undici').MockAgent, pool: import('undici').MockPool | import('undici').MockClient }}
 */
function createMockStreamAgent(origin) {
  const agent = new undici.MockAgent();
  agent.disableNetConnect();
  const pool = agent.get(origin);
  return { agent, pool };
}

module.exports = {
  streamResponse,
  collectStream,
  createMockStreamAgent,
  undici,
};
test/contract.js
const assert = require('node:assert/strict');
const { Writable } = require('node:stream');
const {
  streamResponse,
  collectStream,
  createMockStreamAgent,
  undici,
} = require('../src/index.js');

async function runContracts() {
  // Contract 1: undici.stream streams response chunks into a custom Writable stream and returns opaque metadata and response trailers
  {
    const { agent, pool } = createMockStreamAgent('http://localhost:8080');

    pool.intercept({
      path: '/data/stream',
      method: 'GET',
    }).reply(200, 'chunk-alpha,chunk-beta', {
      headers: {
        'content-type': 'text/plain',
        'x-stream-id': 'stream-100',
      },
    });

    const receivedChunks = [];
    const writable = new Writable({
      write(chunk, encoding, callback) {
        receivedChunks.push(chunk);
        callback();
      },
    });

    let factoryStatus = 0;
    let factoryHeaders = null;
    const opaquePayload = { traceId: 'tr-999' };

    const streamResult = await streamResponse(
      'http://localhost:8080/data/stream',
      {
        dispatcher: agent,
        opaque: opaquePayload,
      },
      ({ statusCode, headers, opaque }) => {
        factoryStatus = statusCode;
        factoryHeaders = headers;
        assert.deepStrictEqual(opaque, opaquePayload);
        return writable;
      }
    );

    assert.strictEqual(factoryStatus, 200);
    assert.strictEqual(factoryHeaders['content-type'], 'text/plain');
    assert.strictEqual(factoryHeaders['x-stream-id'], 'stream-100');
    assert.deepStrictEqual(streamResult.opaque, opaquePayload);
    assert.ok(typeof streamResult.trailers === 'object');
    assert.strictEqual(Buffer.concat(receivedChunks).toString('utf-8'), 'chunk-alpha,chunk-beta');

    await agent.close();
  }

  // Contract 2: undici.stream allows inspecting status code and response headers in the factory function before accepting stream chunks
  {
    const { agent, pool } = createMockStreamAgent('http://localhost:8080');

    pool.intercept({
      path: '/api/resource/invalid',
      method: 'POST',
      body: JSON.stringify({ action: 'validate' }),
    }).reply(422, JSON.stringify({ error: 'Unprocessable Entity', code: 'INVALID_INPUT' }), {
      headers: { 'content-type': 'application/json' },
    });

    const collected = await collectStream('http://localhost:8080/api/resource/invalid', {
      method: 'POST',
      body: JSON.stringify({ action: 'validate' }),
      dispatcher: agent,
      opaque: { reqKey: 'k-1' },
    });

    assert.strictEqual(collected.statusCode, 422);
    assert.strictEqual(collected.headers['content-type'], 'application/json');
    assert.deepStrictEqual(collected.opaque, { reqKey: 'k-1' });

    const errorBody = JSON.parse(collected.body.toString('utf-8'));
    assert.deepStrictEqual(errorBody, { error: 'Unprocessable Entity', code: 'INVALID_INPUT' });

    await agent.close();
  }

  // Contract 3: undici.stream aborts in-flight stream consumption when an AbortSignal triggers
  {
    const { agent, pool } = createMockStreamAgent('http://localhost:8080');

    pool.intercept({
      path: '/slow-stream',
      method: 'GET',
    }).reply(200, 'slow stream data payload').delay(1000);

    const controller = new AbortController();
    setTimeout(() => {
      controller.abort();
    }, 20);

    const discardWritable = new Writable({
      write(chunk, encoding, callback) {
        callback();
      },
    });

    await assert.rejects(
      async () => {
        await streamResponse(
          'http://localhost:8080/slow-stream',
          {
            dispatcher: agent,
            signal: controller.signal,
          },
          () => discardWritable
        );
      },
      (err) => {
        assert.ok(
          err.name === 'AbortError' ||
          err.name === 'RequestAbortedError' ||
          err.code === 'UND_ERR_ABORTED' ||
          controller.signal.aborted,
          'Error must signal stream abortion'
        );
        return true;
      }
    );

    await agent.close();
  }

  // Contract 4: undici.stream rejects and propagates errors when the destination Writable stream encounters a write error
  {
    const { agent, pool } = createMockStreamAgent('http://localhost:8080');

    pool.intercept({
      path: '/streaming-target',
      method: 'GET',
    }).reply(200, 'stream content causing write failure');

    const failingWritable = new Writable({
      write(chunk, encoding, callback) {
        callback(new Error('Write pipeline failure'));
      },
    });

    await assert.rejects(
      async () => {
        await streamResponse(
          'http://localhost:8080/streaming-target',
          { dispatcher: agent },
          () => failingWritable
        );
      },
      (err) => {
        assert.strictEqual(err.message, 'Write pipeline failure');
        return true;
      }
    );

    await agent.close();
  }

  console.log('All undici.stream contract assertions passed successfully.');
}

runContracts().catch((err) => {
  console.error(err);
  process.exit(1);
});

오리진 시더

익명