×
Community Blog Bootstrapping Function Compute for Web Using NodeJS SDK: Part 1

Bootstrapping Function Compute for Web Using NodeJS SDK: Part 1

In this article series, we will be learning how we can bootstrap Alibaba Cloud Function Compute to the web using NodeJS SDK.

By Sai Sarath Chandra, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

In this article, we are going to see how we can bootstrap Alibaba Cloud Function Compute to the web using node JS SDK. Before we begin, let's take a step back and have a brief discussion on what serverless is and why we should use it.

We have virtual machines that can serve applications pretty well. We can also optimize our machines with a microservices architecture, which helps break down a monolithic app into smaller single-purpose apps to increase the maintenance and margin by handling one unit at a time. Now with the serverless architecture, we can further increase the maintenance and margin. In my opinion, a serverless architecture is nothing but a "cloud deployment + automatic load balancer".

Considerations for Serverless Adoption

However, serverless shouldn't be taken lightly. It is one of the hottest paradigm-shift in cloud computing architecture right now. I see more and more applications are moving to the serverless model. But before we hop on the serverless bandwagon, here are some critical things to consider when moving your applications to a serverless architecture:

Simple Tasks

The task in your application should be simple, in other words, the execution time should be small. If not, at least we should be able to break the complex task/logic into simple ones.

Latency

There might be an increased latency when we are shifting the monolithic applications to the serverless model based on the event triggers. The application should be able to handle this additional latency.

Serverless = Function as a Service (FaaS)

Now we know when to use serverless and when not to, let's see whether it is good to use the self-hosted FaaS (Function as a Service) services or a hosted service.

There are several opensource alternatives available out there which can you can self-host to achieve the same OpenFaaS, Nuclio, Fn Project, Kubeless, Apache OpenWhisk.

The main idea of implementing serverless is to reduce the effort of provisioning resources, to maintain servers and to scale. However, if you plan to go for a hosted solution, the below are the advantages you can get

No Planning Required

You need not plan about the deployment of the Serverless opensource solutions. From the start, you can deploy production ready code

Great Integrations

With the introduction of cloud, if you opt for hosted solutions you get greater integrations with the products. This feature gives a higher edge and makes go to market much earlier.

Geo Replications

Hosted solutions support the geo replications with ease

Failover

Automatic failover is a much-needed feature, as we are not managing the resources. The hosted gives a definite execution guarantee which is something we need to implement ourselves if we choose self-hosted

Better Security

Cloud-hosted solutions give better security, for example, Function Compute in Alibaba cloud gets the same Anti-DDoS basic and several other security features which protect the service from all the malicious attacks compared to the self-hosted solutions where we need to implement proper security rules.

Better Improvements

Any improvements similar to NodeJS, Java, Python Environment upgrade in Function Compute can be made automatically for the users. In self-hosted we need to take the effort of doing the same for all the environments at our own cost.

To demonstrate some of the capabilities of Alibaba Cloud Function Compute, we are building a small web application

1

The application consists of 2 core functions, we use a web form

  1. To upload a file to OSS and that will trigger a function execution and we get the output.
  2. Invoke the function directly using the Function Compute NodeJS SDK.

There are two parts in building the application,

  1. Create function in Alibaba cloud Function Compute console, without using fcli.
  2. Creating & Integrating UI and testing the functionality.

Alibaba Cloud Function Compute

Alibaba Compute Function Compute can be used via fcli – Command line tool, Open API, SDK's and Alibaba Cloud Console. We are going to create a function in Cloud Console in NodeJS environment.

  1. Navigate to Alibaba Cloud console > Function Compute.
  2. If you are using it for the first time, Activate the service & Change the region to the desired one and you should console similar to below after that.

    2

  3. You might not see the metrics If you don't have any functions created in the region.
  4. We need to create a service first and then functions in the service. This is more in analogous to the Microservices architecture. Each service is a monolithic app and the function inside are tasks, this will increase the reusability and provides ease of maintenance.

Creating Service

  1. Click on the '+' icon, to create a new service. Once click the + icon you will see a form to mention name and description as below

    3

  2. Click OK
  3. You can also select the "Advanced Settings" option, to configure
    1. Network Config

      Whether or not your function will have internet access?

    2. NAS(Network Attached Storage) Service
    3. Log Config

      Pushing the logs to the log store for further processing

    4. Role Config

      Assigning any RAM roles to the functions

You can decide whether you want to do it at the service level or at the function level. If you want to do at the service level, all the functions under the service will inherit the properties.

Alibaba Cloud function compute provides us with the granularity to control all these properties at the function level.

This is all we need to do for creating a service, that's so simple

Once you click on the service, you are redirected to the particular service area where you can create functions

Creating a Function

Function console will look something similar to the below:

4

  1. You can create a function by using '+' icon or 'Create Function'
  2. Creation of a function is 5 step process
    1. Selecting a template/empty function
    2. Configuring triggers
    3. Configuring function settings
    4. Configuring Function permissions
    5. Verification of Configurations

Select a Template

We have multiple runtimes and versions to choose from, for this tutorial we have selected NodeJS Ver 8 with an empty function template

5

After clicking 'select'. Next step would be configuring triggers.

Configure Triggers

6

There are different types of triggers available like OSS, Log Service, Time, HTTP etc. But for now we select 'No Trigger'. We will see how to setup one for OSS in the upcoming steps. Choose 'Next' for function settings.

Configure Function Settings

Here we will give the necessary details related to creation of function like function name, description, runtime (Make sure you reselect the nodejs8 drop down, else it will show the first item in the list), code configuration, Environment Variables & Runtime Environment.

Defaults work well in Runtime Environment.

Configure Function Permissions

The default service role information and permission configuration will do good. Click verify to proceed.

Verify Configurations

Here you will see the consolidated information related to function, once verified click 'create'. Congratulations!! The function created.

Once you click on function, you will see four items in the console.(Overview, Code, Triggers Log)

7

We can navigate to Code and we choose to upload a folder, we will see why. I have made the code available at https://github.com/saichandu415/NodeJS_FunctionComputeDemo/tree/master/function%20compute%20code%20package

You can clone and checkout the code under 'function compute code package'. Let see though the 'index.js'

var nodemailer = require('nodemailer');

module.exports.handler = function (event, context, callback) {
  var evt = JSON.parse(event); // Parsing the event object
  console.log(JSON.stringify(evt)); // Logging it for debugging purposes
  if (evt.events !== undefined) { // if it is a OSS Trigger then evt.events will not be null
    callback(null, evt.events[0].oss.object.key);
  } else { //Function invoked directly
    var transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
    port: 587,
    secure: false, // use TLS
    auth: {
        user: '<YOUR EMAIL ID>',
        pass: '<YOUR EMAIL PASSWORD>'
    },
    tls: {
        // do not fail on invalid certs
        rejectUnauthorized: false
    }
    });
    if (evt.doMail) {
      const mailOptions = {
        from: '<YOUR EMAIL ID>', // sender address
        to: evt.toMail, // list of receivers
        subject: 'Serverless Demo with OSS Event', // Subject line
        html: 'Hi '+(evt.firstname)+',<br><h1>'+(evt.message).toUpperCase()+'</h1>'// plain text body
      };
      transporter.sendMail(mailOptions, function (err, info) {
        if (err) {
          console.log(err);
          // callback(null, 'Mail Failed');
          callback(null, "Mail Failed :" + (evt.message).toUpperCase());
        } else {
          console.log(info);
          // callback(null, 'Mail Sent');
          callback(null, "Mail Sent :" + (evt.message).toUpperCase());
        }
      });
    } else {
      callback(null, (evt.message).toUpperCase());
    }
  }
};

event, context, callback – are and should be the parameters for the NodeJS Handler.

event – Is of buffer type and all the input consists in the event.

context – this will have all the metadata/generated information of the request like the token, requestId. This is of object type

callback – this is used to return the result to the function that is called, this follows the standard signature of the function 'function(err,data)' The response will be converted if the data is object type else it will be converted to a string and sent.

How Does This Function Work?

The function above is written is such a way when there is an OSS Trigger it takes the file name and send it to the user as a response, if not then the function uses the request object and reads the message field, capitalizes it and triggers a mail to the user in the 'toMail' field.

There are only a set of dependencies allowed to as part of the function compute console editor, if you require any third-party dependencies we need to bundle the dependencies on own and upload it. We used nodemailer, which is a third-party dependency which needs to be bundled.

Instructions for Bundling Your Own Code

  1. Create a root 'index.js' file and a 'package.json'
  2. Add the dependencies in the package.json
  3. Write the function in 'module.exports.' in index.js
  4. 'cd' to the root directory and run 'npm install' or 'npm i'
  5. you can zip it by right cliking the parent folder along with your generated node_modules.

Uploading Your Function to Function Compute Console

You can navigate to 'code' section in the function & select 'Upload Zip file' as shown below

8

Once you select your zip file the upload will be completed and you can 'In-line edit' the function.

Unlike other cloud providers, where once you upload the code there is no provision of editing the function online, but in Alibaba Cloud you can do that.

Creating Trigger

You can create a trigger, to the OSS by selecting 'triggers' section in your function console and clicking "Create Trigger" as below

9

You need to give some information related to your OSS Bucket like Trigger Type, name, Bucket, Events and Clicking "OK" will create the trigger.

Oss:ObjectCreated:PutObject will trigger the function whenever there is a file upload to the bucket.

Testing Your Function

You can test your function online by triggering the function with the request right from the console. To perform that,

  1. Click on "Event" in the console as shown below

    10

  2. Then we have to define a custom message to make a request, if you want to trigger using OSS, you can do that by uploading a file to OSS bucket mentioned.
  3. We use the below message to trigger the function
    {
                "firstname": "Sai Sarath",
                "message": "This String will captialize",
                "doMail": true,
                "toMail": "<Receiver's mail ID>"
    }

    11

  4. Then you can see the output here

    12


You can see all the output here it has the final status of function invocation as "succeeds" & the response as "Mail Sent: THIS STRING WILL CAPTIALIZE". And the complete request logged in detail on the right side of the screen.

We have successfully created a function in the Alibaba Cloud Function Compute console and triggered it successfully. In the next part of the tutorial, we will create a form using which we upload a file and invoke a function using both NodeJS SDK for OSS and Function Compute.

1 0 0
Share on

Alibaba Clouder

2,599 posts | 762 followers

You may also like

Comments

5307446175862455 December 30, 2018 at 1:18 pm

best taxi service in chandigarh taxi in chandigarh