In this lab, you enhance the online Quiz application by creating a Cloud Function to process Cloud Pub/Sub messages.
This process harnesses several GCP products in a serverless environment: Cloud Pub/Sub, Cloud Natural Language API, and Cloud Spanner.
Objectives
In this lab, you learn how to perform the following tasks:
Create a Cloud Function that responds to Cloud Pub/Sub messages.
Deploy multiple files to a Cloud Function.
Setup and requirements
For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.
Sign in to Qwiklabs using an incognito window.
Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
There is no pause feature. You can restart if needed, but you have to start at the beginning.
When ready, click Start lab.
Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.
Click Open Google Console.
Click Use another account and copy/paste credentials for this lab into the prompts.
If you use other credentials, you'll receive errors or incur charges.
Accept the terms and skip the recovery resource page.
Activate Google Cloud Shell
Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.
Google Cloud Shell provides command-line access to your Google Cloud resources.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
You can list the active account name with this command:
[core]
project = qwiklabs-gcp-44776a13dea667a6
Note:
Full documentation of gcloud is available in the
gcloud CLI overview guide
.
Task 1. Preparing the case study application
In this section, you access Cloud Shell, clone the git repository containing the Quiz application, configure environment variables, and run the application.
Clone source code in Cloud Shell
To clone the repository for the class, enter the following command:
To change the working directory, enter the following command:
cd ~/cloudfunctions/start
To replace the default region in a file with the lab-assigned region, you can use the following commands:
export APP_REGION={{{project_0.startup_script.app_gcp_region | APP_REGION}}}
export REGION={{{project_0.default_region | REGION}}}
sed -i 's/us-central1/'"$REGION"'/g' prepare_environment.sh
sed -i 's/us-central/'"$APP_REGION"'/g' prepare_environment.sh
To configure the Quiz application, enter the following command:
. prepare_environment.sh
Note: This script file:
Creates an App Engine application.
Exports the environment variables GCLOUD_PROJECT and GCLOUD_BUCKET.
Runs npm install.
Creates entities in Cloud Datastore.
Creates a Cloud Pub/Sub topic.
Creates a Cloud Spanner Instance, Database, and Table.
Prints out the Google Cloud Project ID.
To run the web application, enter the following command:
npm start
Click Check my progress to verify the objective.
Configure and run the case study application
Task 2. Working with Cloud Functions
In this section, you create a Cloud Function in your Google Cloud project that is triggered by publishing a message to Cloud Pub/Sub, runs the application, and monitors the Cloud Function invocation.
Create a Cloud Function
To access Cloud Run functions, on the Navigation menu (), click Cloud Run.
Click Write a Function.
For Service name, type process-feedback.
For Region, select the region.
Click + Add Triggers and select Pub/Sub trigger from the dropdown.
If necessary, click Enable to enable the required APIs.
In the Pub/Sub trigger window, specify the following:
Property
Value
Trigger type
Google sources
Event provider
Cloud Pub/Sub
Event type
google.cloud.pubsub.topic.v1.messagePublished
Cloud Pub/Sub topic
projects/PROJECT_ID/topics/feedback
Region
If you're notified that Pub/Sub needs the role roles/iam.serviceAccountTokenCreator granted to the Pub/Sub service account, click Grant.
Click Save Trigger.
Click Create.
Review the provided function implementation.
Note: It might take a minute or two to create the Cloud Function.
Click Check my progress to verify the objective.
Create a Cloud Function
Run the web application
Return to the Cloud Shell window.
Preview the web application by clicking on the Web Preview button and selecting Preview on port 8080.
Click Take Test.
Click Places.
Complete the question.
Rate the quiz, enter some feedback, and then click Send Feedback.
View Cloud Function monitoring and logs
Return to the Cloud Platform Console, on the Cloud Run page.
Click process-feedback.
Note: You should see a monitoring graph for Cloud Function invocations.
It takes a few minutes for the graph to show the invocation of your function.
Click the Logs tab to view your logs.
You can view your logs in the logs explorer by clicking the link on the upper right of the page.
If your Cloud Pub/Sub message isn't displayed, click Refresh.
Note: You should see the log entries collected from the Cloud Function.
It takes a few minutes for the logs to show the invocation of your function.
Go to Cloud Shell to also see your feedback.
Task 3. Examining the case study application code
In this section, you use the Cloud Shell text editor to review the case study application code.
Launch the Cloud Shell Editor
In the Cloud Platform Console, click Open Editor.
Review the Cloud Function application code structure
Navigate to cloudfunctions/start.
Select the index.js file in the ...function folder.
Note: This file contains the same code as the sample from the Cloud Functions window in the Cloud Console, with one change: because the function you will write returns a Promise, the callback argument has been omitted.
Select the package.json file.
Note: This file contains the list of dependencies that this function needs to run.
Cloud Functions automatically install the dependencies.
Select the languageapi.js file.
Note: This file contains code to process feedback text and return the Natural Language ML API sentiment score.
Select the spanner.js file.
Note: This file contains code to insert a record into a Cloud Spanner database.
Task 4. Coding a Cloud Function
In this section you write the code to create a Cloud Function that retrieves the Cloud Pub/Sub message data, invokes the Natural Language ML API to perform sentiment detection, and inserts a record into Cloud Spanner.
Note: Update code within the sections marked as follows:
// TODO // END TODO
To maximize your learning, review the code, inline comments, and related API documentation.
Write code to modify a Cloud Function
Return to the ...function/index.js file.
Load the languageapi and spanner modules. These modules are in the same folder as the index.js file.
In the subscribe() method, after the existing code that loads the Cloud Pub/Sub message into a buffer, convert the PubSub message into a feedback object by parsing it as JSON data.
Return a promise that invokes the languageapi module's analyze method to analyze the feedback text.
Chain a .then(...) method to the end of the return statement.
Supply an arrow function as the value of the callback.
In the body of the arrow function, log the Natural Language API sentiment score to the console.
Add a new property called score to the feedback object.
Complete the arrow function body by returning the feedback object.
Chain a second .then(...) method to the end of the first one. This one uses the spanner module to save the feedback.
Write a third .then(...) chained method, including an arrow function with no arguments and an empty body as the value of the callback.
In the body of this callback, log a message to indicate that the feedback has been saved, and return a success message.
Attach a .catch(...) handler to the end of the chain, which logs the error message to the console.
Note: Here's how your function should look when you're done.
function/index.js
// TODO: Load the ./languageapi module
const languageAPI = require('./languageapi');
// END TODO
// TODO: Load the ./spanner module
const feedbackStorage = require('./spanner');
// END TODO
exports.subscribe = function subscribe(event) {
// The Cloud Pub/Sub Message object.
// TODO: Decode the Cloud Pub/Sub message
// extracting the feedbackObject data
// The message received from Pub/Sub is base64 encoded, and
// the data submitted by students is in a data property
const pubsubMessage = Buffer.from(event.data, 'base64').toString();
let feedbackObject = JSON.parse(pubsubMessage);
console.log('Feedback object data before Language API:' + JSON.stringify(feedbackObject));
// END TODO
// TODO: Run Natural Language API sentiment analysis
// The analyze(...) method expects to be passed the
// feedback text from the feedbackObject as an argument,
// and returns a Promise.
return languageAPI.analyze(feedbackObject.feedback).then(score => {
// TODO: Log the sentiment score
console.log(`Score: ${score}`);
// END TODO
// TODO: Add new score property to feedbackObject
feedbackObject.score = score;
// END TODO
// TODO: Pass feedback object to the next handler
return feedbackObject;
// END TODO
})
// TODO: insert record
.then(feedbackStorage.saveFeedback).then(() => {
// TODO: Log and return success
console.log('feedback saved...');
return 'success';
// END TODO
})
// END TODO
// TODO: Catch and Log error
.catch(console.error);
// End TODO
};
Save the file.
Package and deploy the Cloud Function code
Return to Cloud Shell and stop the web application by pressing Ctrl+C.
To change the working directory to the Cloud Function code, enter the following command:
cd function
To zip up the files needed to deploy the function, enter the following command:
zip cf.zip *.js*
Note: This generates a zip archive named cf.zip that includes all the JavaScript and JSON files in the folder.
To stage the zip file into Cloud Storage, enter the following command:
gcloud storage cp cf.zip gs://$GCLOUD_BUCKET/
Note: This copies the zip archive into the Cloud Storage bucket named after your project ID with a -media suffix.
To deploy the function from the Cloud Storage bucket, you can use the gcloud functions deploy command as follows.
gcloud functions deploy process-feedback1 \
--gen2 \
--region={{{project_0.default_region|set at lab start}}} \
--source=gs://$GCLOUD_BUCKET/cf.zip \
--entry-point=subscribe \
--runtime=nodejs22 \
--trigger-topic=feedback
Note: It may take a minute or two to update the process-feedback1 function with your new code that performs sentiment analysis with the Cloud Natural Language Machine Learning API and inserts data into Cloud Spanner.
Package and deploy the Cloud Function code
Task 5. Testing the case study application
Run the web application
Return to the Cloud Shell window.
Change the working folder back to the start folder for the cloudfunctions lab:
cd ..
To start the web application, execute the following command:
npm start
Preview the web application.
Click Take Test.
Click Places.
Complete the question.
Enter some feedback, and click Send Feedback.
View Cloud Function monitoring and logs
Return to the Cloud Run section of the Cloud Platform Console.
Click the function name, process-feedback1.
Note: You should see a monitoring graph for Cloud Function invocations.
It takes a few minutes for the graph to show the invocation of your function.
Click the Logs tab to view your logs.
You can view your logs in the logs explorer by clicking the link on the upper right of the page.
If your Cloud Pub/Sub message isn't displayed, click Refresh.
Refresh the logs every few minutes until the log entries show that your function executed.
Note: You should see the log entries collected from the Cloud Function.
You should now see a score from the Language API in the logs.
It may takes a few minutes for the logs to show the invocation of your function.
View Cloud Spanner data
On the Navigation menu, click on View All Products and click Spanner.
Click Quiz instance, Under the Databeses click quiz-database and then on the left pane select Spanner Studio.
Run the following query:
SELECT * FROM Feedback
Note: You should see that a new record has been added to the Feedback table.
Task 6. Bonus: Storing student answers using a Cloud Function
When a student completes a quiz, their answers are submitted in an API call back to the server. Your job is to capture the student-submitted answers and the correct answers and save them into Cloud Spanner. You should see that a new record has been added to the Feedback table.
To do this:
Create a Cloud Pub/Sub topic called answers.
Create a Cloud Spanner table called Answers with appropriate column names and data types.
Post the answer data to the answers topic.
Subscribe to the answers topic in the console application and insert the answer data into the Answers table.
The details are left up to you! You can find the solution to the bonus in the lab's bonus folder.
Review:
Which triggers can be used with Cloud Functions?
Cloud Pub/Sub
Cloud Spanner
Cloud Storage
HTTP
With a Cloud Function triggered by Cloud Pub/Sub, how is the message
delivered?
Base64 encoded
CSV encoded
Tarred and Gzipped
Zipped
What is the maximum execution time for a Cloud Function?
60 seconds
540 seconds
Unlimited
End your lab
When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
1 star = Very dissatisfied
2 stars = Dissatisfied
3 stars = Neutral
4 stars = Satisfied
5 stars = Very satisfied
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
Labs create a Google Cloud project and resources for a fixed time
Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
On the top left of your screen, click Start lab to begin
Use private browsing
Copy the provided Username and Password for the lab
Click Open console in private mode
Sign in to the Console
Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
Accept the terms, and skip the recovery resource page
Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project
This content is not currently available
We will notify you via email when it becomes available
Great!
We will contact you via email if it becomes available
One lab at a time
Confirm to end all existing labs and start this one
Use private browsing to run the lab
Use an Incognito or private browser window to run this lab. This
prevents any conflicts between your personal account and the Student
account, which may cause extra charges incurred to your personal account.
In this lab, you will enhance the online Quiz application by creating a Cloud Function to process Cloud Pub/Sub messages.