Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid state: Reader released #41858

Closed
essential-existence opened this issue Feb 5, 2022 · 10 comments
Closed

Invalid state: Reader released #41858

essential-existence opened this issue Feb 5, 2022 · 10 comments
Labels
doc Issues and PRs related to the documentations. web streams

Comments

@essential-existence
Copy link

Version

17.4.0

Platform

No response

Subsystem

No response

What steps will reproduce the bug?

import { ReadableStream } from 'node:stream/web';
import { setTimeout, setInterval } from 'node:timers/promises';

const input = new ReadableStream(
  {  // underlyingSource
    start( controller ) { },
    async pull( controller ) {
      await setInterval( 1000 );
      const chunk = performance.now();
      console.log( 'INPUT_READ_PULL', chunk );
      controller.enqueue( chunk );
    },
    cancel( reason ) { },
    type: undefined,
    autoAllocateChunkSize: undefined,
  },
  {  // strategy
    highWaterMark: undefined,
    size: undefined,
  },
);

const input_reader = input.getReader( {
  'mode': undefined,
} );

input_reader.closed.then( () => {
  console.log( 'INPUT_READ__CLOSE' );
} );

//await setTimeout( 2000 );

input_reader.releaseLock();

How often does it reproduce? Is there a required condition?

input_reader.closed.then( () => {} );

What is the expected behavior?

No response

What do you see instead?

TypeError [ERR_INVALID_STATE]: Invalid state: Reader released

Additional information

No response

@MattiasBuelens
Copy link
Contributor

This is expected behavior.

.then() returns a new promise, using the given fulfillment and rejection callbacks to transform the fulfillment value or rejection reason from the original promise. If you only pass a fulfillment handler, then a rejection from the original promise will also reject the new promise. But if rejections from this new promise are never handled, then Node will throw an unhandled rejection error.

Therefore, if you attach a .then() to input_reader.closed, you should make sure to handle both fulfillment and rejection.

input_reader.closed.then(() => {
  console.log( 'INPUT_READ__CLOSE' );
}, (reason) => {
  // Handle the rejection somehow
  console.error("Oh no, the input reader errored!", reason);
});

If you don't care about if or why the closed promise becomes rejected, you can pass an empty function instead:

input_reader.closed.then(() => {
  console.log( 'INPUT_READ__CLOSE' );
}, (reason) => {});

@essential-existence
Copy link
Author

essential-existence commented Feb 5, 2022

Not quite so, it is the line input_reader.releaseLock(); that generates the error. And, according to the documentation (https://nodejs.org/api/webstreams.html#readablestreamdefaultreaderclosed), the closed promise is resolved without exception when releaseLock is called

@MattiasBuelens
Copy link
Contributor

Not quite so, it is the line input_reader.releaseLock(); that generates the error.

That's where the error is created, which is what appears in error.stack. However, it is thrown by the closed promise. (I agree that this can be confusing while debugging...)

And, according to the documentation (https://nodejs.org/api/webstreams.html#readablestreamdefaultreaderclosed), the closed promise is resolved without exception when releaseLock is called

Huh, that seems to be a documentation error. The specification says:

Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or the reader’s lock is released before the stream finishes closing.

It looks like this was originally incorrectly documented in the spec, and was fixed a couple of years ago in whatwg/streams#914. But that hasn't stopped the mistake from propagating... MDN also has the incorrect documentation:

The closed read-only property of the ReadableStreamDefaultReader interface returns a Promise that fulfills when the stream closes or the reader's lock is released, or rejects if the stream throws an error.

We'll need to fix both MDN and Node's documentation then. 😛

benjamingr added a commit to benjamingr/io.js that referenced this issue Feb 5, 2022
The `closed` promise may reject. Document the states where it rejects
based on the spec.

Fixes: nodejs#41858
@benjamingr
Copy link
Member

@MattiasBuelens I'll make a PR for Node thanks for the MDN fix

@benjamingr benjamingr added the doc Issues and PRs related to the documentations. label Feb 5, 2022
@essential-existence
Copy link
Author

Yes, thanks for clearing up the misunderstandings!

@benjamingr
Copy link
Member

@essential-existence not your fault our docs were wrong 😅 thanks for the detailed report that resulted in a doc fix!

benjamingr added a commit to benjamingr/io.js that referenced this issue Feb 5, 2022
The `closed` promise may reject. Document the states where it rejects
based on the spec.

Fixes: nodejs#41858
Co-Authored-By: Mattias Buelens <mattias@buelens.com>
benjamingr added a commit to benjamingr/io.js that referenced this issue Feb 5, 2022
The `closed` promise may reject. Document the states where it rejects
based on the spec.

Fixes: nodejs#41858
Co-Authored-By: Mattias Buelens <mattias@buelens.com>
@benjamingr
Copy link
Member

Let's keep this open until the docs issue is fixed (hope that's ok with you!)?

@benjamingr benjamingr reopened this Feb 5, 2022
@essential-existence
Copy link
Author

all in your hands!

bengl pushed a commit to bengl/node that referenced this issue Feb 21, 2022
The `closed` promise may reject. Document the states where it rejects
based on the spec.

Fixes: nodejs#41858

PR-URL: nodejs#41860
Co-Authored-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
bengl pushed a commit to bengl/node that referenced this issue Feb 21, 2022
The `closed` promise may reject. Document the states where it rejects
based on the spec.

Fixes: nodejs#41858

PR-URL: nodejs#41860
Co-Authored-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
danielleadams pushed a commit to danielleadams/node that referenced this issue Apr 21, 2022
The `closed` promise may reject. Document the states where it rejects
based on the spec.

Fixes: nodejs#41858

PR-URL: nodejs#41860
Co-Authored-By: Mattias Buelens <mattias@buelens.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
@RishabhSolutionsArchitectTelecard

I have a next js project

here is the layout.tsx code

import "../globals.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { ThemeProvider } from "@/providers/theme-provider";
import ClientOnly from "@/components/clientOnly/clientOnly";
import Navbar from "@/components/navbar/navbar";
import RegisterModal from "@/components/modal/signupform";
import LoginModal from "@/components/modal/loginform";
import getCurrentUser from "../actions/getCurrentUser";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

async function RootLayout({ children }: { children: React.ReactNode }) {
  const currentUser = await getCurrentUser();
  return (
    <html lang="en">
      <body className={inter.className}>
        <ClientOnly>
          <LoginModal />
          <RegisterModal />
          {/* @ts-ignore */}
          <Navbar currentUser={currentUser} />
        </ClientOnly>
        <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}

export default RootLayout;

Here I am passing current User from backend
to Navbar

here is the type of users where I am editing the types

import { User } from "@prisma/client";

export type SafeUser = Omit<
  User,
  "createdAt" | "updatedAt" | "emailVerified"
> & {
  createdAt: string;
  updatedAt: string;
  emailVerified: string | null;
};

here is the user schema using mongodb and prisma orm

model User {
  id            String    @id @default(auto()) @map("_id") @db.ObjectId
  name          String?
  email         String ?  @unique
  emailVerified DateTime?
  password      String?
  image         String?
  country       String ?
  phoneNumber   String  ?   
  role          UserRoles @default(ADMIN)
  isActive      Boolean
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  accounts      Account[]
  sessions      Session[]
  workspaces     WorkSpace[] 
  company      Company[]

}

when ever I run the I am getting error unhandledRejection: TypeError [ERR_INVALID_STATE]: Invalid state: Unable to enqueue

@totallytavi
Copy link

totallytavi commented Sep 21, 2023

@RishabhSolutionsArchitectTelecard That error is unrelated to this one. I recommend you search again, or open a new issue if nobody has yet. I also recommend providing the trace for this as well so we can figure out if this is a NodeJS error or Prisma error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
doc Issues and PRs related to the documentations. web streams
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants