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

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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);
});

原始种子者

匿名