Розробка Serverless Functions для сайту (Google Cloud Functions)
Google Cloud Functions (2nd gen) — serverless-функції на базі Cloud Run. На відміну від 1st gen, 2nd gen підтримує до 60 хвилин виконання, кілька одночасних запитів на один екземпляр та ширший вибір рантаймів: Node.js, Python, Go, Java, .NET, Ruby, PHP.
Перше покоління проти другого
2nd gen функції використовують Cloud Run під капотом. Це дає: concurrency до 1000 запитів на екземпляр (проти 1 у 1st gen), підтримку VPC Connector, більші ліміти пам'яті (32 GB), користувацькі домени без проксування.
Приклад функції: обробка webhook
import functions_framework
import json
import hmac
import hashlib
from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
TOPIC_PATH = "projects/my-project/topics/webhook-events"
@functions_framework.http
def process_webhook(request):
# Перевірка підпису
signature = request.headers.get("X-Signature-256", "")
secret = get_secret("webhook-secret")
expected = "sha256=" + hmac.new(
secret.encode(), request.data, hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature, expected):
return json.dumps({"error": "Invalid signature"}), 401, {"Content-Type": "application/json"}
event = request.get_json()
# Публікація у Pub/Sub для асинхронної обробки
publisher.publish(TOPIC_PATH, json.dumps(event).encode("utf-8"))
return json.dumps({"received": True}), 200, {"Content-Type": "application/json"}
Функція на Node.js з TypeScript
import { http, HttpFunction } from "@google-cloud/functions-framework";
import { SecretManagerServiceClient } from "@google-cloud/secret-manager";
const secretClient = new SecretManagerServiceClient();
const contactForm: HttpFunction = async (req, res) => {
res.set("Access-Control-Allow-Origin", "https://your-site.com");
if (req.method === "OPTIONS") {
res.set("Access-Control-Allow-Methods", "POST");
res.set("Access-Control-Allow-Headers", "Content-Type");
res.status(204).send("");
return;
}
if (req.method !== "POST") {
res.status(405).json({ error: "Method not allowed" });
return;
}
const { name, email, message } = req.body;
// Отримання API-ключа з Secret Manager
const [version] = await secretClient.accessSecretVersion({
name: "projects/my-project/secrets/sendgrid-api-key/versions/latest"
});
const apiKey = version.payload?.data?.toString();
await sendEmail({ name, email, message, apiKey });
res.json({ ok: true });
};
http("contactForm", contactForm);
Розгортання
# Node.js
gcloud functions deploy contact-form \
--gen2 \
--runtime nodejs20 \
--region europe-west1 \
--source . \
--entry-point contactForm \
--trigger-http \
--allow-unauthenticated \
--memory 256MB \
--timeout 30s
# Python
gcloud functions deploy process-webhook \
--gen2 \
--runtime python312 \
--region europe-west1 \
--source . \
--entry-point process_webhook \
--trigger-http \
--memory 512MB
Змінні оточення
gcloud functions deploy my-function \
--set-env-vars DATABASE_URL=postgresql://...,NODE_ENV=production
# Або через Secret Manager (рекомендується для секретів)
gcloud functions deploy my-function \
--set-secrets 'API_KEY=my-secret:latest'
Функція-підписчик Pub/Sub
@functions_framework.cloud_event
def process_pubsub_message(cloud_event):
import base64
data = base64.b64decode(cloud_event.data["message"]["data"]).decode("utf-8")
event = json.loads(data)
# Обробка події: синхронізація з CRM, сповіщення, тощо
handle_event(event)
Запускається автоматично при публікації повідомлення у топік Pub/Sub.
Підключення до Cloud SQL
Для PostgreSQL/MySQL використовуйте Cloud SQL Auth Proxy через Unix socket — не TCP:
import sqlalchemy
def create_engine():
return sqlalchemy.create_engine(
f"postgresql+pg8000://user:pass@/dbname",
creator=lambda: pg8000.connect(
user="user",
password="pass",
database="dbname",
unix_sock="/cloudsql/project:region:instance/.s.PGSQL.5432"
)
)
У Cloud Run (і Cloud Functions 2nd gen) Cloud SQL Auth Proxy запускається як sidecar автоматично при вказанні --add-cloudsql-instances.
CI/CD через Cloud Build
# cloudbuild.yaml
steps:
- name: node:20
entrypoint: npm
args: [install]
- name: node:20
entrypoint: npm
args: [run, build]
- name: gcr.io/google.com/cloudsdktool/cloud-sdk
args:
- gcloud
- functions
- deploy
- contact-form
- --gen2
- --region=europe-west1
- --source=.
- --runtime=nodejs20
- --entry-point=contactForm
- --trigger-http
Терміни
Базові функції з розгортанням та змінними оточення — 2–3 дні. Інтеграція Pub/Sub та Cloud SQL — плюс 2 дні.







