Arcade Adventure: Modern Cloud Architecture

Solution for Arcade Adventure: Modern Cloud Architecture. 1 lab: GSP080. Fast copy-paste commands for Google Cloud.

GSP080 — Cloud Run Functions: Qwik Start - Command Line

Estimated time: 15 minutes

# 🚀 Cloud Run Functions: Qwik Start - Command Line > ⚠️ **Disclaimer:** This is an independent, community-made walkthrough created for educational purposes, hands-on practice, and Google Cloud certification preparation. This guide is designed to help learners understand serverless functions, Node.js development, npm package management, Pub/Sub messaging, and Gen 2 Cloud Run functions through practical exercises. Always attempt the lab yourself first and follow Google Cloud Skills Boost / Qwikl

# ==============================================================================
# ORBIT OF OPS - GSP080 (COMMAND 1 OF 1)
# ==============================================================================
GREEN='\e[1;32m'
CYAN='\e[1;36m'
YELLOW='\e[1;33m'
MAGENTA='\e[1;35m'
WHITE='\e[1;37m'
RED='\e[1;31m'
RESET='\e[0m'
BOLD='\e[1m'

clear
echo -e "${CYAN}${BOLD}"
cat << "EOF"
  ____       _     _ _            __    ___            
 / __ \     | |   (_) |          / _|  / _ \           
| |  | |_ __| |__  _| |_   ___  | |_  | | | |_ __  ___ 
| |  | | '__| '_ \| | __| / _ \ |  _| | | | | '_ \/ __|
| |__| | |  | |_) | | |_ | (_) || |   | |_| | |_) \__ \
 \____/|_|  |_.__/|_|\__| \___/ |_|    \___/| .__/|___/
                                            | |        
                                            |_|        
EOF
echo -e "${RESET}"
echo -e "${MAGENTA}${BOLD}>>> ORBIT OF OPS: GSP080 INITIATED <<<${RESET}\n"

export PROJECT_ID=$(gcloud config get-value project 2>/dev/null)
export REGION=$(gcloud compute project-info describe --format="value(commonInstanceMetadata.items[google-compute-default-region])" 2>/dev/null | tail -n 1)
if [ -z "$REGION" ]; then export REGION="us-central1"; fi

echo -e "${YELLOW}${BOLD}[Orbit of Ops] Phase 1: Pre-warming APIs for IAM Sync...${RESET}"
gcloud services disable cloudfunctions.googleapis.com --quiet 2>/dev/null || true
gcloud services enable cloudfunctions.googleapis.com run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com pubsub.googleapis.com eventarc.googleapis.com --quiet
sleep 15

echo -e "${CYAN}${BOLD}[Orbit of Ops] Phase 2: Generating Node.js Function Code...${RESET}"
mkdir -p gcf_hello_world && cd gcf_hello_world

cat << 'EOF' > package.json
{
  "name": "gcf_hello_world",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "@google-cloud/functions-framework": "^3.0.0"
  }
}
EOF

cat << 'EOF' > index.js
const functions = require('@google-cloud/functions-framework');

// Register a CloudEvent callback with the Functions Framework that will
// be executed when the Pub/Sub trigger topic receives a message.
functions.cloudEvent('helloPubSub', cloudEvent => {
  // The Pub/Sub message is passed as the CloudEvent's data payload.
  const base64name = cloudEvent.data.message.data;

  const name = base64name
    ? Buffer.from(base64name, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);
});
EOF

echo -e "${BLUE}${BOLD}[Orbit of Ops] Phase 3: Installing npm dependencies...${RESET}"
npm install

echo -e "\n${MAGENTA}${BOLD}[Orbit of Ops] Phase 4: Deploying Cloud Run Function (Takes ~2-3 mins)...${RESET}"
echo -e "${WHITE}If it fails due to Qwiklabs API delays, the script will automatically retry.${RESET}"

MAX_RETRIES=3
RETRY_COUNT=0
DEPLOY_SUCCESS=false

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
  if gcloud functions deploy nodejs-pubsub-function \
    --gen2 \
    --runtime=nodejs20 \
    --region=$REGION \
    --source=. \
    --entry-point=helloPubSub \
    --trigger-topic cf-demo \
    --stage-bucket $PROJECT_ID-bucket \
    --service-account cloudfunctionsa@$PROJECT_ID.iam.gserviceaccount.com \
    --allow-unauthenticated \
    --quiet; then
    DEPLOY_SUCCESS=true
    break
  else
    RETRY_COUNT=$((RETRY_COUNT+1))
    echo -e "${YELLOW}${BOLD}Backend API propagation delayed. Retrying deployment ($RETRY_COUNT/$MAX_RETRIES) in 30 seconds...${RESET}"
    sleep 30
  fi
done

if [ "$DEPLOY_SUCCESS" = true ]; then
  echo -e "${GREEN}${BOLD}✅ Function deployed successfully!${RESET}"
  
  echo -e "\n${CYAN}${BOLD}[Orbit of Ops] Phase 5: Triggering Function via Pub/Sub (Task 3)...${RESET}"
  gcloud pubsub topics publish cf-demo --message="Cloud Function Gen2" --quiet

  echo -e "\n${GREEN}${BOLD}🎉 COMMAND 1 COMPLETE!${RESET}"
  echo -e "${YELLOW}${BOLD}You can now safely click 'Check my progress' on all tasks in your lab manual!${RESET}"
else
  echo -e "\n${RED}${BOLD}❌ Function deployment failed after multiple retries. Please check the Cloud Console for specific error logs.${RESET}"
fi