• Tidak ada hasil yang ditemukan

develop and deploy a function using Serverless Framework instead of manually

Dalam dokumen Beginning Serverless Computing (Halaman 178-183)

Google Cloud

2. develop and deploy a function using Serverless Framework instead of manually

ChAPTer 5 ■ GooGLe CLoud

168

IMPROVING OUR SERVERLESS FUNCTION

Improve by separating logic and utilizing serverless framework

Separate AWS logic from handler:

1. use environment variables for AWS-specific logic or move AWS logic to a shared

ChAPTer 5 ■ GooGLe CLoud

• Data streaming from various processes or devices: A residential sensor can stream data to backend servers hosted in the cloud.

• Reliability improvement: A single-zone Compute Engine service can operate in additional zones by subscribing to a common topic, to recover from failures in a zone or region.

The main concepts in Pub/Sub include the publisher, message, topic, subscription, and subscriber.

Figure 5-32 illustrates how these components work together to create a unified message flow.

The following describes each of the resources used in the model. It is important to understand these concepts before jumping into the creation of our serverless function:

• Topic: A named resource to which messages are sent by publishers.

• Subscription: A named resource representing the stream of messages from a single, specific topic, to be delivered to the subscribing application.

• Message: The combination of data and (optional) attributes that a publisher sends to a topic and is eventually delivered to subscribers.

• Message attribute: A key-value pair that a publisher can define for a message.

Google Cloud has a concept of background functions, which operate differently than HTTP functions.

We use background functions whenever we want our function to be invoked indirectly via a message on a Google Cloud Pub/Sub topic or a change in a Google Cloud Storage bucket. The background functions take two parameters, an event and an optional callback function.

Figure 5-32. The publisher creates a message that is posted to a topic with a series of subscriptions that all receive the message

ChAPTer 5 ■ GooGLe CLoud

170

Creating Our Pub/Sub Function

We are going to go ahead and create our Pub/Sub triggered function. First, we will need to create a Pub/Sub topic that we want to trigger our function. From the Google Cloud console, navigate to the Pub/Sub service and click Create a Topic (Figure 5-33). We are going to create a topic called AlertService. This will be the topic that triggers our function.

After we have created our topic, we are going to navigate back to the Google Cloud Functions panel and create a new function within our current project. We will make our trigger the Pub/Sub topic we just created.

To test the functionality of using the Pub/Sub topic, we will initialize our function with the provided Google Cloud template. This simply writes the event to the logs.

/**

* Triggered from a message on a Cloud Pub/Sub topic.

*

* @param {!Object} event The Cloud Functions event.

* @param {!Function} The callback function.

*/

exports.subscribe = function subscribe(event, callback) { // The Cloud Pub/Sub Message object.

const pubsubMessage = event.data;

// We're just going to log the message to prove that // it worked.

console.log(Buffer.from(pubsubMessage.data, 'base64').toString());

Figure 5-33. Create a topic to trigger our function. Any posts to this topic will cause our function to execute.

ChAPTer 5 ■ GooGLe CLoud // Don't forget to call the callback.

callback();

};

When we go back to our Pub/Sub topic, we can click Publish Message, write a message, and send it to our topic. If all goes as planned, we can view our message in our logs in Google Cloud. When you get a success response, import our project into our Firebase console. To do this, navigate to console.firebase.

google.com and click Import Google Project. Import the overall project. Mine is still named Hello World.

You can then view the Pub/Sub function in the Functions tab. You should see the topic AlertService as the trigger and the execution that you just invoked. If you click on Logs, you will also see the logs for that Pub/Sub invocation we just created.

We are now going to add to our function so it does a little more than just logging to the console. Go ahead and do another firebase init in your project folder where your index.js file is stored. When prompted to select a project, select the Google Cloud project we have been developing in. Now, when we get a request through our topic, we want to store it in the alerts table in our Realtime database.

The following code demonstrates how we will handle the incoming request.

'use strict';

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.subscribe = functions.pubsub.topic('AlertService').onPublish(event => { const pubSubMessage = event.data;

// Get the `name` attribute of the PubSub message JSON body.

let alert = null;

try {

alert = pubSubMessage.json.alert;

console.log("Alert: " + alert);

admin.database().ref('/alerts').push({alert: alert}).then(snapshot => { console.log("success!");

});

} catch (e) {

console.error('PubSub message was not JSON', e);

} });

Deploy this code using the firebase deploy command in your terminal. We can then test this functionality by going back to our Pub/Sub topic and sending a message. Our function is looking for a JSON body with an alert field. So the request will look like Figure 5-34.

ChAPTer 5 ■ GooGLe CLoud

172

You should be able to track the progress of the function by looking at the logs in the Firebase

environment. You can also track this in the Google Cloud functions environment. Our function was renamed to subscribe and you can see its invocations under Function Details (Figure 5-35). Upon success, the alert that we sent along the Pub/Sub will appear under alerts/ in our Realtime database.

Figure 5-35. Our message is now stored in our project’s Realtime database Figure 5-34. Send a message to our topic to trigger our recently deployed function

ChAPTer 5 ■ GooGLe CLoud We now have a function that is hosted in Google Cloud and also accessed by Firebase. You can view logging and triggers in both environments and can easily update and deploy the function so it is accessible by both consoles. The purpose of this exercise was to show this communication between functions and to show how to access Cloud triggers and have them affect a Firebase database.

IMPROVING OUR SERVERLESS FUNCTION

Improve by integrating with our previous application

Add the Pub/Sub function to our original

index.js

file associated with Firebase.

1. use the same logic we used for our storage trigger and add our Pub/Sub function to

Dalam dokumen Beginning Serverless Computing (Halaman 178-183)