This article is not to teach you how to use Ali Cloud, Google Cloud and other cloud framework FaaS services, but to teach you how to build your own FaaS services from scratch.

Due to labor and cost constraints, FaaS service is basically a “plaything of the big factory”, and there is very little code implementation online, so I decided to write an article about how to build a Nodejs FaaS service from scratch.

The tiny-Node-Faas project in this article is online and open source on GitHub.

Access the link: www.shadowingszy.top/tiny-node-f…

Source code address: github.com/shadowings-…

I. Introduction of background and related concepts

1-1, Serverless

Serverless, literally, is the concept of building and running applications that do not require server management. Serverless provides back-end services on demand, allowing users to write and deploy code directly without worrying about the underlying infrastructure.

In short, how do you determine if a service is Serverless? If you develop the service without any knowledge of “server count”, “container environment”, and other infrastructure-related things, then the service is Serverless.

1-2, FaaS

FaaS stands for Function as a Service and can be simply understood as Function servitization. FaaS provides a software architecture paradigm for service fragmentation. FaaS allows r&d to focus only on business code logic, not technical architecture.

For example, if we were to write a Hello World service using the KOA framework, we would write:

const Koa = require("koa");
const app = new Koa();

const handler = async (ctx) => {
  ctx.body = "hello world";
};

app.use(handler);
app.listen(8080.() = > {
  console.log("Port 8080 started");
});
Copy the code

With FaaS, we only need to focus on the following parts, and the rest of the work, such as service creation, cold start, load balancing, etc., is done by the FaaS provider.

const handler = async (ctx) => {
  ctx.body = "hello world";
};
Copy the code

1-3. Why do WE make Nodejs FaaS service

Nodejs FaaS is being made because more and more developers, as well as backend services, are choosing to use Nodejs.

This is partly due to the simple and direct programming experience brought by Nodejs’ single-threaded asynchronous and non-blocking nature, and partly due to the trend of “front-end full stack”, which encourages some front-end engineers to write back-end code logic.

What is more noteworthy is that due to different technical directions, many front-end development engineers have weak knowledge of operation and maintenance and servers. Therefore, providing them with a Nodejs FaaS service can separate them from operation and maintenance and enable developers to focus more on business code logic, which is very promising.

Two, code implementation

2-1. Vm module

The question “How to implement Nodejs FaaS service” can be replaced with the following question:

How do I create a new sandbox in Nodejs, execute the specified code in the sandbox, and get the return value?

Nodejs actually already provides such a module, the VM module, as documented below: nodejs.org/api/vm.html

It’s also easy to use:

const vm = require("vm");

const code = 'console.log("hello world!" ) ';

const sandbox = { console };
vm.createContext(sandbox);

const data = vm.runInNewContext(code, sandbox);
Copy the code

With the VM module, we can execute JavaScript code in a new sandbox and get the return value

2-2. Overall architecture

As shown in the figure, tiny-Node-FAAS consists of four parts: 1. Front end of management platform; 2. Function management; 3

2, 3 and 4 are the three most important components of FaaS service.

2-3. Core code

const vm = require("vm");

const runFunction = async (code) => {
  let timer = null;
  const result = await new Promise((resolve, reject) = > {
    const sandbox = {
      require.console};try {
      timer = setTimeout(() = > {
        reject(new Error("Execute function time out"));
      }, 10000);

      vm.createContext(sandbox);

      const data = vm.runInNewContext(code, sandbox);

      resolve(data);
    } catch (error) {
      reject(error);
    }
  }).catch((err) = > {
    return err instanceof Error ? err : new Error(err.stack);
  });

  if (timer) {
    clearTimeout(timer);
    timer = null;
  }

  return result;
};
Copy the code

The runFunction method in the above code is the core method to execute the FaaS function. All we need to do is pass in the code, the code to run, and this method will create a new sandbox and run the code, and then return the results.

2-4. Safety related

Of course, using VM as serverless directly has certain security risks. For example, using require(‘ OS ‘) directly gives you access to the physical machine’s operating system, and there are a lot of interesting “sandbox escape” topics in this area. GitHub also has “implementations of more secure VM modules” such as VM2. But limited by space, and I really is not what attack and defense god, here will not unfold.