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".
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:
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.
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.
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
You need not plan about the deployment of the Serverless opensource solutions. From the start, you can deploy production ready code
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.
Hosted solutions support the geo replications with ease
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
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.
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
The application consists of 2 core functions, we use a web form
There are two parts in building the application,
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.
Whether or not your function will have internet access?
Pushing the logs to the log store for further processing
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
Function console will look something similar to the below:
We have multiple runtimes and versions to choose from, for this tutorial we have selected NodeJS Ver 8 with an empty function template
After clicking 'select'. Next step would be configuring triggers.
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.
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.
The default service role information and permission configuration will do good. Click verify to proceed.
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)
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.
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.
You can navigate to 'code' section in the function & select 'Upload Zip file' as shown below
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.
You can create a trigger, to the OSS by selecting 'triggers' section in your function console and clicking "Create Trigger" as below
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.
You can test your function online by triggering the function with the request right from the console. To perform that,
{
"firstname": "Sai Sarath",
"message": "This String will captialize",
"doMail": true,
"toMail": "<Receiver's mail ID>"
}
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.
Bootstrapping Function Compute for Web Using NodeJS SDK: Part 2
2,599 posts | 764 followers
FollowAlibaba Clouder - December 7, 2018
Alibaba Clouder - May 6, 2019
Alibaba Cloud Serverless - August 21, 2019
Alibaba Clouder - November 20, 2018
afzaalvirgoboy - June 17, 2020
Alibaba Clouder - September 11, 2020
2,599 posts | 764 followers
FollowElastic and secure virtual cloud servers to cater all your cloud hosting needs.
Learn MoreAn encrypted and secure cloud storage service which stores, processes and accesses massive amounts of data from anywhere in the world
Learn MoreAlibaba Cloud Function Compute is a fully-managed event-driven compute service. It allows you to focus on writing and uploading code without the need to manage infrastructure such as servers.
Learn MoreMore Posts by Alibaba Clouder
5307446175862455 December 30, 2018 at 1:18 pm
best taxi service in chandigarh taxi in chandigarh