01. What is Serverless?

The definition and understanding of Serverless can be interpreted differently from different perspectives and scenarios. AWS defines Serverless(on the AWS cloud) as “a way to describe services, practices, and policies that enable you to build more agile applications, A service that can innovate and respond to change more quickly.” Red Hat sees Serverless as a development model that “allows developers to focus on building and running applications without having to manage the server” and further divides Serverless’s products into two categories: BaaS(back-end as a service, which gives developers access to a wide variety of third-party services and applications) and FaaS(feature as a service, where developers write logic, deploy it into a container entirely managed by the platform, and execute it on demand). The Serverless Framework describes Serverless as “a developer and enterprise driven movement that allows a single developer to do high-traffic application development while focusing only on the areas that generate value.”

Regardless of aspect and Angle, Serverless has the following characteristics in common:

  1. Rapid development, rapid deployment
  2. Pay as you go and keep costs down
  3. Automatic expansion, no maintenance required

At present, they are all based on FAAS services of various cloud vendors, such as SCF of Tencent Cloud, Lambda of AWS, Azure Funcitons of Azure Cloud, etc.

What problem does Serverless solve?

As computing power increases, system complexity increases, and the size of users grows, software problems (also known as software crises) will also grow exponentially.

  • Software development schedules are hard to predict
  • Software development costs are hard to control
  • The quality of software products cannot be guaranteed
  • Software products are difficult to maintain

Serverless, on the other hand, provides a solution to the software crisis in the following ways:

  • The function of the system is broken down into smaller particles in a functional way, which is easier to design, develop, test and maintain.
  • The cost of server can be reduced by charging on a regular basis.
  • Through automatic capacity expansion and the support of cloud platform, the workload of operation and maintenance and the cost of software maintenance are greatly reduced.

At the same time, in a modern working environment where agile is the norm, Serverless provides best practices for quickly validating ideas and iterating functionality without having to worry about code changes affecting other features of the system, pre-deployment server configuration, and post-deployment maintenance.

02. Serverless Framework

Serverless Framework is a very popular Serverless application Framework in the industry. Through close cooperation with many first-class cloud providers such as Tencent Cloud and AWS, it provides developers with a Serverless development experience that they can write and deploy code without caring about the underlying infrastructure.

Serverless Framework also provides resource management, automatic scaling, statistical analysis and other capabilities, so that the majority of developers can save operation and maintenance costs, really do “pay as you go” at the same time, but also do not need to spend energy processing log collection, abnormal statistics and other tasks.

Serverless Framework works closely with Tencent Cloud through CLI tools to provide Chinese users with a complete solution based on Serverless Components. Covering the full life cycle of coding, testing, and deployment of unserviced applications, while adapting to the usage scenarios and habits of Chinese users.

Why Serverless Framework?

With just a few lines of Serverless Framework configuration files and CLI tools, developers can get additional:

  • Develop functions locally and deploy them to the cloud with one click, no additional cloud adaptations or console logins required.
  • Support for deployment of traditional development frameworks (e.g. Express, NeXT. Js, Flask, Laravel, etc.) as Serverless applications.
  • Debug the function code locally, or use remote development mode to view the log output of the deployed service locally in real time and debug it.
  • All infrastructure configuration can be done with simple configuration (e.g. API gateway, COS storage, DB link, etc.)
  • Quickly switch between application deployment environment (development, demonstration, production) and locale.
  • More detailed and easy to understand the status of the application, view the log, error statistics and other information.

03. Multiple function development examples

This example uses the Serverless Framework’s Multi-SCF and PostgreSQL implementations to implement the following three API interfaces.

  • GET /todos/Get all of the TODO transactions
  • POST /todos/Create a new todo event
  • POST /todos/{id}/actions/completeComplete TODO items

Use the Serverless Framework’s Invoke and Logs functions to debug and view the production environment’s real-time logs.

The code for this example is available in the Git repository.

Step 1: Install the Serverless Framework

Execute the following command to install the Serverless Framework

$ npm install serverless -g

If you have previously installed the Serverless Framework, you can upgrade to the latest version with the following command:

$ npm update serverless -g

This command installs the latest Serverless Framework on your computer. Once installed successfully, you can start using the Serverless Framework via Serverless or SLS

Step 2: Initialize the multi-function project

$ sls init multi-scf-nodejs --name sls-demo-msn-todo

This command initializes the application directory with the name my-multi-scf-demo using the application template multi-scf-nodejs. After successful initialization, the directory structure is

. Heavy Exercises ─ Readme.MD Heavy Exercises ─ Index.js └─ Serverless.yml

The purpose of the file here is as follows:

  • Index.js: A function file.
  • Serverless. yml: Serverless Framework configuration file.

    • App: The name of the app, which will be used as a unique identifier for the app.
    • Stage: Application environment. Deploy different application instances through different environments.
    • Component: Name of the component
    • Name: Component instance name
    • Inputs: Input parameters for component deployment

Step 3: Link to the database

Because Serverless is stateless (it is destroyed after it is run), you need to link to the database to persist the TODO information. Adding a database requires a VPC network connection.

1. Add the VPC

Create the subdirectory VPC and add the new serverless.yml file to the subdirectory as follows:

Component: VPC # [for] want to use components, more components see https://github.com/serverless-components name: SLS - demo - MSN - VPC # [for] a component instance name inputs: VpcName: ${name} # instance name with region: ap-guangzhou # zone: ${name} # instance name with region: ap-guangzhou # zone: ap-guangzhou # zone: ${name} # instance name with region: ap-guangzhou # zone: ap-guangzhou # zone: ap-guangzhou # zone: ${name} # instance name with region: ap-guangzhou # zone SubnetName: sls-demo-msn-subnet # Name of subnet: sls-demo-msn-subnet #

For more information on VPC configuration, see the VPC Private Network for more details.

In the configuration file of the child component, the app name automatically inherits the configuration in the serverless.yml of the parent directory. At the same time, the app name of the same app should be consistent.

2. Add database

Create the subdirectory db and add the new serverless.yml file to the subdirectory as follows:

Component: PostgreSQL #(required) refers to the name of the Component. The name of the PostgreSQL component is currently used: SLS-demo-msn-db # (required) : Inputs: region: ap-guangzhou # : Inputs: region: ap-guangzhou ${name}-${stage} # dbInstanceName: ${name}-${stage} # dbInstanceName: ${name}-${stage} # ExtranetAccess: true # enable vpcConfig: # VPC network configuration vpcId: ${output:${stage}:${app}:sls-demo-msn-vpc.vpcId} ${output:${stage}:${app}:sls-demo-msn-vpc.vpcId} ${output:${stage}:${app}:sls-demo-msn-vpc.subnetId} # subnet ID

Add the database to the VPC network in the database configuration, where the output variable is used to dynamically obtain the VPC ID information.

For more variable configuration information, see Serverless variables for more details.

See the PostgreSQL database for more details on the PostgreSQL configuration.

After the component is deployed, it can be used in the component directory
sls infoView the output variable of the component, or you can go to the application console of Tencent Cloud to view relevant information.

3. Initialize the application directory

  1. Create a subdirectorysrcAnd will create the generatedindex.js(Rename totodos.js) andserverless.ymlMove to a directory.
  2. insrcExecution in directorynpm initInitialize the Node.js project.
  3. insrcExecution in directorynpm i pg --saveInstall database link dependency packagespg.
  4. Add a root configuration file to the project root directoryserverless.yml, the document is as follows:
APP: SLS-Demo-MSN-TODO-3E5A2134 # Application unique identification, under the same account must be kept unique. Stage: dev # Apply the deployment environment name, where the value of the environment variable stage is used.

The configuration file information of the root directory is inherited from the component and does not need to be defined repeatedly in the child component. (App and Stage only).

The final project directory structure is as follows:

. Exercises ─ Reamme.md Exercises ─ DB # ├─ Serverless.yml # Database Profile Exercises ─ Serverless.yml # SRC # Mini-Function Application Exercises ─ Node_Modules │ ├─ Exercises │ ├─ Pass Exercises - Pass Exercises - Pass Exercises - Pass Exercises - Pass Exercises - Pass Exercises - VPC # VPC sigma ─ serverless.yml # VPC sigma

4. Modify the multi-function application configuration

Modify the configuration file in the multi-function directory SRC as follows:

component: multi-scf name: sls-demo-msn inputs: src: src: ./ exclude: -.env - "node_modules/**" # Ignor all files in the node_modules directory during deployment to speed up deployment environments: ${output:${stage}:${app}:sls-demo-msn-DB.private.connectionString} region: ap-guangzhou runtime: ${output:${stage}:${app}:sls-demo-msn-vpc.vpcId} # private network ID subnetId: ${output:${stage}:${app}:sls-demo-msn-vpc.subnetId} ${output:${stage}:${app}:sls-demo-msn-vpc.subnetId} Functions: # allTodo: # function alias handler: todo. all # function memorySize: 256 # addTodo: Handler: todos. Add timeout: 9 # completeTodo: handler: todos.comp timeout: 9 Triggers: # trigger configuration -type: Apigw parameters: name: todosAPIGW protocols: -https-http apis: # API configuration -path: /todos/ # routing path method: /todos/ method: POST function: addToDo-path: /todos/ method: POST function: addToDo-path: /todos/ method: POST function: addToDo-path: /todos/{id}/actions/complete method: POST function: completeTodo param: # dynamic route parameter configuration -name: id position: PATH required: true type: number desc: Todo ID

The main contents of modification are as follows:

  • useinstallDependencyDepends on automatic installation when deployment is enabled and is ignorednode_moduleAll files in the directory (no need to upload node_modules to speed up deployment)
  • usevpcAdd a VPC network and link it to the same VPC network for the project.
  • useenvironmentsAdd a project environment variable and use the OUTPUT variable to dynamically generate the database connection string.
  • usefunctionsTo declare functions and their aliases in your project.
  • usetriggersDeclares the function’s trigger, and the trigger’sapisConfigure the corresponding path of each function and parameter information in.

For more configuration content and details on function development, see the PostgreSQL database for more details.

For more information on function development, see Function Development for more details.

Step 4: Develop the functionality

Modify todos.js and complete the development of related functions. The final code of the file is as follows:

"use strict"; const { Client } = require("pg"); const client = new Client({ connectionString: process.env.PG_CONNECT_STRING, }); /** * const initDb = async () => {const isConnected = client && client._connected; if (! isConnected) { await client.connect(); await client.query(` CREATE TABLE IF NOT EXISTS todo ( ID SERIAL NOT NULL, TITLE VARCHAR NOT NULL, NOTE TEXT, IS_COMPLETE BOOLEAN DEFAULT FALSE ); `); }}; All = async (event, context) => {// async needs to turn off the event loop wait to avoid logging timeout or function not returning. context.callbackWaitsForEmptyEventLoop = false; await initDB(); const { rows } = await client.query({ text: "SELECT * FROM todo" }); return { message: "Tencent SCF execute successful!" , data: rows, }; }; /** * Add new Todo item */ export.add = async (event, context) => {// async needs to close the event loop wait to avoid logging timeout or function not returning. context.callbackWaitsForEmptyEventLoop = false; const { title, note } = JSON.parse(event.body); if (! title) { return { statusCode: 400, message: "Missing Todo Title", }; } await initDB(); const { rowCount } = await client.query({ text: "INSERT INTO todo (title, note) VALUES($1, $2)", values: [title, note], }); return rowCount === 1 ? { statusCode: 201, message: "Todo added success.", } : { statusCode: 400, message: "Todo added failed.", }; }; /** * completes Todo */ exports.comp = async (event, context) => {// async needs to turn off the event loop to avoid logging timeout or function not returning. context.callbackWaitsForEmptyEventLoop = false; const todoId = event.pathParameters.id; if (! todoId && ! isNaN(todoId)) { return { statusCode: 400, message: "Missing Todo Id", }; } await initDB(); const { rowCount } = await client.query({ text: "UPDATE todo SET is_complete = true WHERE id=$1", values: [todoId], }); return rowCount === 1 ? { statusCode: 200, message: "Todo Complete success.", } : { statusCode: 400, message: "Todo Complete failed.", }; };

Step 5: Debug the function

1. Invoke debugging

In addition to using third-party development tools to debug the code through the configured API gateway URL, you can also use the Serverless Framework’s Invoke function or remote debugging function. The invoke function is used here to demonstrate how to debug function functionality.

Invoke and remote debugging functions need to be performed in the component’s directory.

2. Get all TODO

Execute in the SRC directory

$ serverless invoke -f allTodo

The results can be obtained after execution

In default authorization, if you need to use a temporary key, use --login to relog in BillDuration: 36 Duration: 36 errMsg: functionRequestId: fe6d302d-f6db-42ad-9c7b-8d0c61ead9b3 invokeResult: 0 log: """ START RequestId: fe6d302d-f6db-42ad-9c7b-8d0c61ead9b3 Event RequestId: fe6d302d-f6db-42ad-9c7b-8d0c61ead9b3 END RequestId: fe6d302d-f6db-42ad-9c7b-8d0c61ead9b3 Report RequestId: Fe6d302d-f6db-42ad-9c7b-8d0c61ead9b3 Duration:36ms Memory:256MB """ Memusage :11.3984MB """ 11952128 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Serverless: {call success message: 'Tencent SCF execute successful! ', data: [] }

The result returned by invoke contains meta information about the execution of the function, such as runtime, error, requestId, the log of execution, and the result returned by the function.

3. Create a new TODO

Execute in the SRC directory

$  serverless invoke -f addTodo --data "{\"body\":\"{\\\"title\\\":\\\"Create multi-scf project demo\\\",\\\"note\\\":\\\"Todo App with postgreSQL\\\"}\"}"

The results can be obtained after execution

In default authorization, if you need to use a temporary key, use --login to relog in BillDuration: 35 Duration: 35 errMsg: functionRequestId: 93f50016-064f-468d-9e98-31645fc254fd invokeResult: 0 log: """ START RequestId: 93f50016-064f-468d-9e98-31645fc254fd Event RequestId: 93f50016-064f-468d-9e98-31645fc254fd END RequestId: 93f50016-064f-468d-9e98-31645fc254fd Report RequestId: 93F50016-064F-468D-9E98-31645FC254FD Duration:35ms Memory:128MB Memusage :11.293MB """ Memusage: 11841536 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Serverless: call succeeds {statusCode: 201, the message: 'Todo added success.' }

Step 6: Deploy and log

1. Deploy code to production

Use the following command to quickly deploy a project to a production environment (here named prod)

$ serverless deploy --stage prod

2. Instant viewing of the production environment log

To view the real-time log information for a project, execute the following command in the project directory SRC

$ sls logs --tail -f allTodo --stage prod

Here are the results returned:

In default authorization, if you need to use a temporary key, use --login to relog into serverless ⚡components Action: "logs" -stage: "prod" -app: "sls-demo-msn-todo-3e5a2134" - Name: "sls-demo-msn" START RequestId:6f31857109130f092c547337c073ea91 Response RequestId:dbb3a8ed63a32be8e6b7a2dd8a32bbe2 RetMsg:{"message":"Tencent SCF execute successful!" ,"data":[{"id":1,"title":"Create multi-scf project demo","note":"Todo App with postgreSQL","is_complete":false}]} END RequestId:dbb3a8ed63a32be8e6b7a2dd8a32bbe2 Report RequestId:dbb3a8ed63a32be8e6b7a2dd8a32bbe2 Duration:4ms Memory:256MB MemUsage: 12.113281 MB Response RequestId: 485 a87cfc6ad385b7e9c84343962391b RetMsg: {" message ":" Tencent SCF execute successful!" ,"data":[{"id":1,"title":"Create multi-scf project demo","note":"Todo App with postgreSQL","is_complete":false}]} END RequestId:485a87cfc6ad385b7e9c84343962391b Report RequestId:485a87cfc6ad385b7e9c84343962391b Duration:4ms Memory:256MB MemUsage: 11.886719 MB START RequestId: 0 ede6d26dca55362a701c10ff51c9021 Serverless holds the listening...

conclusion

Thanks to the developers who have been supporting the Serverless Framework for a long time. In the future, we will continue to iterate on the product, introduce new features and improve the product use experience. Finally, we will create a complete solution for Chinese developers that is in line with the habits of Chinese developers in server-less development.

You are also welcome to the Serverless Chinese community to share your experience and ideas, as well as feedback questions and bugs.

Serverless Chinese community: https://github.com/serverless/serverless-tencent/discussions

Last hope everyone can participate in our sweepstakes questionnaire: https://www.surveymonkey.com/…

One More Thing

Instantly experience Tencent cloud Serverless Demo, receive Serverless new user gift package 👉 Tencent cloud Serverless novice experience.