kwhitley / itty-router

A little router.
MIT License
1.79k stars 78 forks source link

corsify creating unused readable stream #261

Open shsteimer opened 2 months ago

shsteimer commented 2 months ago

Describe the Issue

When running locally with dev tools open, an error is produced that states:

"A ReadableStream branch was created but never consumed. Such branches can be created, for instance, by calling the tee() method on a ReadableStream, or by calling the clone() method on a Request or Response object. If a branch is created but never consumed, it can force the runtime to buffer the entire body of the stream in memory, which may cause the Worker to exceed its memory limit and be terminated. To avoid this, ensure that all branches created are consumed."

This seems to have been introduced in 5.0.17 with the change to clone the response https://github.com/kwhitley/itty-router/commit/74f63abb25d12666e7c05e5e82fcf7432f8dbda4#diff-a1624121bc1fee18f8a5c2b2f907f01ba9c56a50068007e4c5da2911e91ea6df

Example Router Code

Please provide the itty-router code related to the issue. If possible, create a minimal, reproducible example.

import { Router, cors } from 'itty-router';

const { preflight, corsify } = cors({
    origin: (origin) => {
        const patterns = ['.allowedurl.com', 'localhost:3000'];
        if (origin && patterns.some((p) => origin.endsWith(p))) {
            return origin;
        }

        return undefined;
    },
    allowMethods: ['GET', 'POST'],
    maxAge: 84600,
});

const router = Router({
    before: [preflight],
    finally: [corsify],
});

//register some routes
router.get('/api/myRoute', anAsyncRouteFunction);

Request Details

appears to happen on every request so I'm not sure it matters, but:

Steps to Reproduce

Steps to reproduce the behavior:

  1. create a worker project using Router and corsify
  2. run wrangler dev
  3. type 'd' to open dev tools
  4. send a request to your worker
  5. see in the dev tools console that the error is produced

Expected Behavior

It's not clear to me how big a problem this is in reality, but it is definitely a daunting error message, so should be avoided if at all possible.

Actual Behavior

A clear and concise description of what actually happens. Include any error messages or unexpected responses.

Environment (please complete the following information):

Additional Context

issues was also reported at https://github.com/kwhitley/itty.dev/issues/26

istarkov commented 2 months ago

Moreover it does not prevent from the error can’t modify immutable headers. response.clone() used is wrong