openfaas / faas

OpenFaaS - Serverless Functions Made Simple
https://www.openfaas.com
MIT License
24.75k stars 1.92k forks source link

Function execution is not stateless #1807

Closed LijieZhang1998 closed 9 months ago

LijieZhang1998 commented 11 months ago

My actions before raising this issue

Why do you need this?

I want to check if this platform support stateless function execution.

Current Behaviour

I tested a JS function to call gcp firebase SDK to save data. I found out that each execution of the JS function impacts each other. The "initializeApp" method will throw a "duplicated app" exception when invoking the function after the first time of invocation. Here is the code piece in my handler.js file.

module.exports = async (event, context) => {
  const invalidate = require("invalidate-module");
  invalidate(require.resolve("firebase-admin/firestore"));
  invalidate(require.resolve("firebase-admin/app"));
  const { getFirestore } = require("firebase-admin/firestore");
  const { initializeApp, cert } = require("firebase-admin/app");
  const app = initializeApp(
    {
      credential: cert({
        projectId: "my_project_id",
        clientEmail:
          "my_client_email",
        privateKey:
          "my_private_key",
      }),
    }
  );
  ...
}

I think the root cause is that JavaScript allows global variables and initializeApp initialize an app variable and won't allow to be initialized again in one Nodejs runtime process. Do you know what I can do to work around this? Function execution become not stateless in this case.

Any help is appreciated!

alexellis commented 9 months ago

This is working as intended, and the same way as AWS Lambda.

I'd suggest that you run your initialisation once then keep a variable to prevent it running again, if that's your desired behaviour. That or, run the initialisation in a closure in the file, not in the HTTP handler.

Alex

LijieZhang1998 commented 9 months ago

yes, I think containerized FaaS solutions are all work in this way. Thank you for your confirmation.