kleydon / prisma-session-store

Express session store for Prisma
MIT License
116 stars 18 forks source link

Invalid 'prisma.session.update()' invocation. #62

Closed tcikovsky closed 2 years ago

tcikovsky commented 2 years ago

I am on a WSL (Windows 10) machine and I am running nextjs with express and prisma for the backend. I am getting a error that I think is something inside the code from this package:

`Invalid 'prisma.session.update()' invocation:

  An operation failed because it depends on one or more records that were required but not found. Record to update not found.
    ==== Promise at: ==================
    at __awaiter (/home/tomas/coding/webhub/node_modules/@quixo3/prisma-session-store/dist/lib/prisma-session-store.js:32:12)
    at PrismaSessionStore._this.set (/home/tomas/coding/webhub/node_modules/@quixo3/prisma-session-store/dist/lib/prisma-session-store.js:446:64)
    at Session.save (/home/tomas/coding/webhub/api/node_modules/express-session/session/session.js:72:25)
    at Session.save (/home/tomas/coding/webhub/api/node_modules/express-session/index.js:406:15)
    at ServerResponse.end (/home/tomas/coding/webhub/api/node_modules/express-session/index.js:335:21)
    at ServerResponse.send (/home/tomas/coding/webhub/api/node_modules/express/lib/response.js:221:10)
    at /home/tomas/coding/webhub/api/routes/auth.ts:12:13
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/tomas/coding/webhub/api/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at /home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:335:12)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:174:3)
    at router (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:317:13)
    at /home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:335:12)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:275:10)
    at session (/home/tomas/coding/webhub/api/node_modules/express-session/index.js:479:7)
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:317:13)
    at /home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:335:12)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:275:10)
    at /home/tomas/coding/webhub/api/api.ts:23:5
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:317:13)
    at /home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:335:12)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:275:10)
    at jsonParser (/home/tomas/coding/webhub/api/node_modules/body-parser/lib/types/json.js:110:7)
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:317:13)
    at /home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:335:12)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:275:10)
    at expressInit (/home/tomas/coding/webhub/api/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:317:13)
    at /home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:335:12)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:275:10)
    at query (/home/tomas/coding/webhub/api/node_modules/express/lib/middleware/query.js:45:5)
    at Layer.handle [as handle_request] (/home/tomas/coding/webhub/api/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:317:13)
    at /home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:335:12)
    at next (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/home/tomas/coding/webhub/api/node_modules/express/lib/router/index.js:174:3)
    at Function.handle (/home/tomas/coding/webhub/api/node_modules/express/lib/application.js:174:10)
    at Server.app (/home/tomas/coding/webhub/api/node_modules/express/lib/express.js:39:9)
    at Server.emit (events.js:375:28)
    at Server.emit (domain.js:470:12)
    at parserOnIncoming (_http_server.js:897:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)

    ==== Error at: ====================
    at cb (/home/tomas/coding/webhub/node_modules/@prisma/client/runtime/index.js:35943:17)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

    ==== Shared trace: ================`

I am just really confused as to what this means. I have had this issue for about 3 months now and though this may just be me being dumb I can't seem to figure out what is wrong with it, and it seems no one else had a similar issue.

here is my code:

initializing the middleware (sidenote: makeSecretSession just generates a random string):

app.use(session({
    name: "pog",
    saveUninitialized: true,
    resave: true,
    secret: makeSessionSecret(),
    cookie: { maxAge: 1000 * 60 * 60 * 1, secure: false },
    store: new PrismaSessionStore(
        prisma,
        {
            checkPeriod: 2 * 60 * 1000,
            dbRecordIdFunction: undefined,
            dbRecordIdIsSessionId: true
        }
    )
}));

logging-in path middleware (req.session.userId = user.id should be the issue i think):

router.post('/login',
    (req: Request, res: Response) => {
        const findUniqueUserInDB = async (email: string) => {
            return await prisma.user.findUnique({
                where: { email: email }
            });
        };

        const { email, password } = req.body;

        if (email && password) {
            findUniqueUserInDB(email).then((user) => {
                if (user === null) {
                    res.send({ loginStatus: LoginStatus.WRONG_EMAIL });
                } else {
                    if (password === user.password) {
                        req.session.userId = user.id;
                        req.session.save(() => {
                            console.log("SAVED!")
                        })  
                        res.send({ loginStatus: LoginStatus.PASSED });
                        setTimeout(() => {
                        }, 5000)
                        req.session.reload()
                        console.log(req.session)
                    } else {
                        res.send({ loginStatus: LoginStatus.WRONG_PASSWORD });
                    }
                }
            });
        }
        console.log(req.session)
    });

also i had to add this fix because typescript wouldnt shut up about it:

declare global {
    namespace Express {
        namespace session {
            interface SessionData {
                cookie: Cookie,
                userId: number;
                [key: string]: any;
            }
        }
    }
}
kleydon commented 2 years ago

Hi @tcikovsky, I'm not immediately seeing anything here. Unfortunately, I'm on MacOS/Linux, so its hard to test if there may be something platform-specific going on... @wSedlacek, have you ever encountered anything like this before?

wSedlacek commented 2 years ago

Unfortunately, I'm on MacOS/Linux, so its hard to test if there may be something platform-specific going on...

I daily drive macOS, so I am in the same boat.

@wSedlacek, have you ever encountered anything like this before?

I have not seen this specific error before, that said, I don't have any active projects that are making use this library.

also i had to add this fix because typescript wouldnt shut up about it:

Adding the type definitions for SessionData is standard practice when using express-session with TypeScript. Nothing unusual there. Although I wouldn't have used any, but that's just me.

I am just really confused as to what this means.

@tcikovsky it sounds like there is an update() being called that does not meet the requirements of the prisma schema. Can I see your prisma schema for Session?

tcikovsky commented 2 years ago

I just checked and it matches the one on the npm setup page but still here you go:

model Session {
  id        String   @id
  sid       String   @unique
  data      String
  expiresAt DateTime
}
wSedlacek commented 2 years ago

🤔 @tcikovsky Could you clone our repo and run the test under WSL to see if any of the test fail?

git clone git@github.com:kleydon/prisma-session-store.git
cd prisma-session-store
yarn
yarn test
kleydon commented 2 years ago

@wSedlacek - Thanks for the help trying to diagnose this!

tcikovsky commented 2 years ago

image so the command you gave me didn't work but I still understood what you want me to do and so I cloned the repository and passed both tests.

wSedlacek commented 2 years ago

@tcikovsky 🤔 Alright, so the next step will be to create a minimal recreation. Can you create a repo with just express, express-session and prisma-session-store that uses the same logic you posted for your /login route? Note: This is explicitly excluding next to isolate variables.

Once you provide this repo I will be able to clone it and debug the issue further. Specifically I am to figure out what data and existingSession are at run time when the issue is occurring. https://github.com/kleydon/prisma-session-store/blob/b444380fc62398e51f17e5cbc480d2e069908937/src/lib/prisma-session-store.ts#L380-L385

I did notice that you have a res.send() and a req.session.reload() outside of the callback of the req.session.save() I am curious if there is some strangeness caused by the order of operations of those calls.

tcikovsky commented 2 years ago

will do but those commands are there just because i was trying them when debugging the issue. i think the error predates that code.

wSedlacek commented 2 years ago

@tcikovsky Were you still having issues?

kleydon commented 2 years ago

Closing this for now; we can re-open if concerns re-surface.

HartS commented 2 years ago

Hi, I'm seeing a similar error on macOS

touch(): Error:
Invalid `this.prisma.session.update()` invocation in
.../@quixo3/prisma-session-store/dist/lib/prisma-session-store.js:526:66

   523 existingSession = _b.sent();
   524 if (!(existingSession !== null)) return [3 /*break*/, 5];
   525 existingSessionData = __assign(__assign({}, this.serializer.parse((_a = existingSession.data) !== null && _a !== void 0 ? _a : '{}')), { cookie: session.cookie });
→  526 return [4 /*yield*/, this.prisma.session.update(
  Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: ConnectionError(Timed out during query execution.) })
Error:
Invalid `this.prisma.session.update()` invocation in
node_modules/@quixo3/prisma-session-store/dist/lib/prisma-session-store.js:526:66

   523 existingSession = _b.sent();
   524 if (!(existingSession !== null)) return [3 /*break*/, 5];
   525 existingSessionData = __assign(__assign({}, this.serializer.parse((_a = existingSession.data) !== null && _a !== void 0 ? _a : '{}')), { cookie: session.cookie });
→  526 return [4 /*yield*/, this.prisma.session.update(
  Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: ConnectionError(Timed out during query execution.) })
    at cb /node_modules/@prisma/client/runtime/index.js:38687:17)

I'm running the prisma session store v3.0.1 Prisma v3.6.0 Node v14.16.0

and using a sqlite database.

HartS commented 2 years ago

Never mind, the stack trace I just shared is likely related to https://github.com/prisma/prisma/issues/9562 (which is unrelated to this session-store package). @tcikovsky yours didn't include the same key phrase I've seen (error occurred during query execution), but are you using sqlite?