הרחבת Cloud Run באמצעות טריגרים של אירועים באמצעות פונקציות Cloud Run

בעזרת פונקציות Cloud Run, אתם יכולים לפרוס קוד לטיפול באירועים שמופעלים על ידי שינויים במסד הנתונים של Cloud Run. כך אפשר להוסיף פונקציונליות בצד השרת בלי להפעיל שרתים משלכם.

במדריך הזה מוסבר איך ליצור טריגרים לפונקציות Cloud Run מאירועים ב-Firestore.

אפשר להפעיל את פונקציות Cloud Run מאירועים במסד נתונים של Firestore. כשהפונקציה מופעלת, היא קוראת ומעדכנת מסד נתונים של Firestore בתגובה לאירועים האלה באמצעות ממשקי ה-API וספריות הלקוח של Firestore.

התהליך של הפעלת פונקציית Cloud Run על ידי אירועים ב-Firestore כולל את השלבים הבאים:

  1. השירות ממתין לשינויים במסמך מסוים.

  2. כשמתרחש שינוי, השירות מופעל ומבצע את המשימות שלו.

  3. השירות מקבל אובייקט נתונים עם תמונת מצב של המסמך המושפע. באירועים מסוג write או update, אובייקט הנתונים מכיל תמונות מצב שמייצגות את מצב המסמך לפני ואחרי אירוע ההפעלה.

לפני שמתחילים

  1. חשוב לוודא שהגדרתם פרויקט חדש ל-Cloud Run כמו שמתואר בדף ההגדרה.
  2. מפעילים את ממשקי ה-API של Artifact Registry,‏ Cloud Build,‏ Cloud Run Admin,‏ Eventarc,‏ Cloud Logging של Firestore ו-Pub/Sub:‏

    הפעלת ממשקי ה-API

התפקידים הנדרשים

אתם או האדמין שלכם צריכים להעניק הרשאות לחשבון הפריסה ולזהות הטריגר. אפשר גם להעניק לסוכן השירות של Pub/Sub את תפקידי ה-IAM הבאים.

התפקידים הנדרשים לחשבון הפריסה

כדי לקבל את ההרשאות שדרושות להפעלת פונקציות מאירועים ב-Firestore, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

שימו לב: כברירת מחדל, ההרשאות של Cloud Build כוללות הרשאות להעלאה ולהורדה של ארטיפקטים של Artifact Registry.

התפקידים הנדרשים עבור זהות הטריגר

  1. חשוב לשים לב לחשבון השירות שמוגדר כברירת מחדל ב-Compute Engine, כי תצטרכו לצרף אותו לטריגר של Eventarc כדי לייצג את הזהות של הטריגר למטרות בדיקה. חשבון השירות הזה נוצר באופן אוטומטי אחרי שמפעילים או משתמשים בשירות Google Cloud שמשתמש ב-Compute Engine, והוא בפורמט האימייל הבא:

    PROJECT_NUMBER-compute@developer.gserviceaccount.com

    מחליפים את PROJECT_NUMBER במספר הפרויקט. אפשר למצוא את מספר הפרויקט בדף Welcome במסוף Google Cloud או על ידי הפעלת הפקודה הבאה: Google Cloud

    gcloud projects describe PROJECT_ID --format='value(projectNumber)'

    בסביבות ייצור, מומלץ מאוד ליצור חשבון שירות חדש ולהקצות לו תפקיד IAM אחד או יותר שמכילים את ההרשאות המינימליות הנדרשות, ולפעול לפי העיקרון של הרשאות מינימליות.

  2. כברירת מחדל, רק בעלי פרויקטים, עורכי פרויקטים, אדמינים ומפעילים של Cloud Run יכולים להפעיל שירותים של Cloud Run. אפשר לשלוט בגישה לכל שירות בנפרד, אבל למטרות בדיקה, כדאי להעניק את התפקיד 'הפעלת Cloud Run' (run.invoker) בפרויקט Google Cloud לחשבון השירות של Compute Engine. ההרשאה הזו ניתנת לכל השירותים והמשימות של Cloud Run בפרויקט.
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
        --role=roles/run.invoker

    שימו לב: אם יוצרים טריגר לשירות מאומת ב-Cloud Run בלי להעניק את התפקיד Cloud Run Invoker (הפעלת Cloud Run), הטריגר נוצר בהצלחה והוא פעיל. עם זאת, הטריגר לא יפעל כמצופה ותופיע הודעה דומה לזו שמופיעה ביומנים:

    The request was not authenticated. Either allow public access or set the proper Authorization header.
  3. מקצים את התפקיד 'מקבל אירועים' ב-Eventarc (roles/eventarc.eventReceiver) בפרויקט לחשבון השירות שמוגדר כברירת מחדל ב-Compute Engine, כדי שהטריגר של Eventarc יוכל לקבל אירועים מספקי אירועים.
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
        --role=roles/eventarc.eventReceiver

תפקיד אופציונלי לסוכן השירות של Pub/Sub

  • אם הפעלתם את סוכן השירות של Cloud Pub/Sub ב-8 באפריל 2021 או לפני כן, כדי לתמוך בבקשות push מאומתות של Pub/Sub, צריך להקצות לסוכן השירות את התפקיד 'יצירת אסימונים בחשבון שירות' (roles/iam.serviceAccountTokenCreator). אחרת, התפקיד הזה מוענק כברירת מחדל:
    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-pubsub.iam.gserviceaccount.com \
        --role=roles/iam.serviceAccountTokenCreator

הגדרת מסד נתונים ב-Firestore

לפני שמפעילים את השירות, צריך ליצור מסד נתונים של Firestore:

  1. עוברים אל הדף של Firestore.

  2. בוחרים באפשרות יצירת מסד נתונים של Firestore.

  3. בשדה Name your database (מתן שם למסד הנתונים), מזינים מזהה מסד נתונים, כמו firestore-db.

  4. בקטע Configuration options (אפשרויות הגדרה), האפשרות Firestore native (מקומי ל-Firestore) מסומנת כברירת מחדל יחד עם כללי האבטחה הרלוונטיים.

  5. בקטע Location type, בוחרים באפשרות Region ובוחרים את האזור שבו רוצים שהמסד הנתונים יהיה ממוקם. הבחירה הזו היא סופית.

  6. לוחצים על יצירת מסד נתונים.

מודל הנתונים של Firestore מורכב מאוספים שמכילים מסמכים. מסמך מכיל קבוצה של צמדי מפתח/ערך.

כתיבת פונקציה שמופעלת על ידי Firestore

כדי לכתוב פונקציה שמגיבה לאירועים ב-Firestore, צריך לציין את הפרטים הבאים במהלך הפריסה:

סוגי אירועים

‫Firestore תומך באירועים create,‏ update,‏ delete ו-write. האירוע write כולל את כל השינויים במסמך.

סוג אירוע הטריגר
google.cloud.firestore.document.v1.created (ברירת מחדל) מופעל כשמסמך נכתב בפעם הראשונה.
google.cloud.firestore.document.v1.updated מופעל כשמסמך כבר קיים וערך כלשהו בו משתנה.
google.cloud.firestore.document.v1.deleted מופעל כשמסמך עם נתונים נמחק.
google.cloud.firestore.document.v1.written מופעל כשמסמך נוצר, מעודכן או נמחק.
google.cloud.firestore.document.v1.created.withAuthContext זהה ל-created אבל כולל פרטי אימות.
google.cloud.firestore.document.v1.updated.withAuthContext זהה ל-updated אבל כולל פרטי אימות.
google.cloud.firestore.document.v1.deleted.withAuthContext זהה ל-deleted אבל כולל פרטי אימות.
google.cloud.firestore.document.v1.written.withAuthContext זהה ל-written אבל כולל פרטי אימות.

תווים כלליים לחיפוש נכתבים בטריגרים באמצעות סוגריים מסולסלים, לדוגמה: projects/YOUR_PROJECT_ID/databases/(default)/documents/collection/{document_wildcard}

מסנני אירועים להפעלת טריגר

כדי להפעיל את השירות, צריך לציין נתיב למסמך להאזנה. הנתיב למסמך צריך להיות באותו פרויקט Google Cloud כמו השירות.

אלו כמה דוגמאות לנתיבי מסמכים תקינים:

  • users/marie: מעקב אחרי מסמך יחיד, /users/marie.

  • users/{username}: מעקב אחרי כל המסמכים של המשתמשים. תווים כלליים משמשים למעקב אחרי כל המסמכים באוסף.

  • users/{username}/addresses/home: מעקב אחרי מסמך כתובת המגורים של כל המשתמשים.

  • users/{username}/addresses/{addressId}: מעקב אחרי כל מסמכי הכתובות.

  • users/{user=**}: עוקב אחרי כל המסמכים של המשתמשים וכל המסמכים בקולקציות משנה מתחת לכל מסמך של משתמש, כמו /users/userID/address/home או /users/userID/phone/work.

  • users/{username}/addresses: נתיב כתובת לא תקין. ההפניה היא לאוסף המשנה addresses, ולא למסמך.

תווים כלליים לחיפוש ופרמטרים

אם אתם לא יודעים מהו המסמך הספציפי שאתם רוצים לעקוב אחריו, אתם יכולים להשתמש ב-{wildcard} במקום במזהה המסמך:

  • users/{username} מאזין לשינויים בכל המסמכים של המשתמשים.

בדוגמה הזו, כשמשנים שדה כלשהו במסמך כלשהו ב-users, הוא תואם לתו כל כללי שנקרא {username}.

אם במסמך ב-users יש אוספי משנה, ושדה באחד מהמסמכים של אוספי המשנה האלה משתנה, תו כללי {username} לא מופעל. אם רוצים להגיב לאירועים גם באוספי משנה, צריך להשתמש בתו כללי רב-מקפי {username=**}.

התאמות של תווים כלליים לחיפוש מחולצות מנתיבי מסמכים. אפשר להגדיר כמה תווים כלליים שרוצים במקום מזהים מפורשים של אוספים או מסמכים. אפשר להשתמש בתו כללי אחד לחיפוש של כמה פלחים, כמו {username=**}.

קוד הפונקציה

בדוגמאות מוסבר איך להשתמש באירועים של Firestore במצב Native כדי להפעיל פונקציית Cloud Run.

הכללת יחסי התלות של ה-proto במקור

צריך לכלול את קובץ Cloud Run data.proto בספריית קובצי המקור של הפונקציה. הקובץ הזה מייבא את קובצי ה-proto הבאים, שצריך לכלול גם אותם בספריית קובצי המקור:

משתמשים באותו מבנה ספריות עבור התלויות. לדוגמה, ממקמים את struct.proto בתוך google/protobuf.

הקבצים האלה נדרשים כדי לפענח נתוני אירועים. אם מקור הפונקציה לא כולל את הקבצים האלה, הפונקציה מחזירה שגיאה כשהיא מופעלת.

מאפייני אירוע

כל אירוע כולל מאפייני נתונים שכוללים מידע על האירוע, כמו השעה שבה האירוע הופעל. ‫Cloud Run מוסיף נתונים נוספים על מסד הנתונים והמסמך שקשורים לאירוע. כך ניגשים למאפיינים האלה:

Java
logger.info("Function triggered by event on: " + event.getSource());
logger.info("Event type: " + event.getType());
logger.info("Event time " + event.getTime());
logger.info("Event project: " + event.getExtension("project"));
logger.info("Event location: " + event.getExtension("location"));
logger.info("Database name: " + event.getExtension("database"));
logger.info("Database document: " + event.getExtension("document"));
// For withAuthContext events
logger.info("Auth information: " + event.getExtension("authid"));
logger.info("Auth information: " + event.getExtension("authtype"));
Node.js
console.log(`Function triggered by event on: ${cloudEvent.source}`);
console.log(`Event type: ${cloudEvent.type}`);
console.log(`Event time: ${cloudEvent.time}`);
console.log(`Event project: ${cloudEvent.project}`);
console.log(`Event location: ${cloudEvent.location}`);
console.log(`Database name: ${cloudEvent.database}`);
console.log(`Document name: ${cloudEvent.document}`);
// For withAuthContext events
console.log(`Auth information: ${cloudEvent.authid}`);
console.log(`Auth information: ${cloudEvent.authtype}`);
Python
print(f"Function triggered by change to: {cloud_event['source']}")
print(f"Event type: {cloud_event['type']}")
print(f"Event time: {cloud_event['time']}")
print(f"Event project: {cloud_event['project']}")
print(f"Location: {cloud_event['location']}")
print(f"Database name: {cloud_event['database']}")
print(f"Document: {cloud_event['document']}")
// For withAuthContext events
print(f"Auth information: {cloud_event['authid']}")
print(f"Auth information: {cloud_event['authtype']}")

מבנים של אירועים

הטריגר הזה מפעיל את השירות שלכם עם אירוע שדומה ל:

{
    "oldValue": { // Update and Delete operations only
        A Document object containing a pre-operation document snapshot
    },
    "updateMask": { // Update operations only
        A DocumentMask object that lists changed fields.
    },
    "value": {
        // A Document object containing a post-operation document snapshot
    }
}

כל אובייקט Document מכיל אובייקט Value אחד או יותר. למידע על הפניות לסוגים, אפשר לעיין בValueמסמכים.

יצירת טריגרים לפונקציות

לוחצים על הכרטיסייה עם ההוראות לשימוש בכלי הרצוי.

המסוף

כשמשתמשים במסוף Google Cloud כדי ליצור פונקציה, אפשר גם להוסיף לה טריגר. כדי ליצור טריגר לפונקציה:

  1. נכנסים ל-Cloud Run במסוף Google Cloud :

    כניסה ל-Cloud Run

  2. לוחצים על Write a function (כתיבת פונקציה) ומזינים את פרטי הפונקציה. מידע נוסף על הגדרת פונקציות במהלך הפריסה זמין במאמר פריסת פונקציות.

  3. בקטע Trigger (טריגר), לוחצים על Add trigger (הוספת טריגר).

  4. בוחרים באפשרות Firestore trigger (טריגר של Firestore).

  5. בחלונית Eventarc trigger משנים את פרטי הטריגר באופן הבא:

    1. מזינים שם לטריגר בשדה Trigger name או משתמשים בשם ברירת המחדל.

    2. בוחרים סוג טריגר מהרשימה:

      • מקורות Google כדי לציין טריגרים ל-Pub/Sub, ל-Cloud Storage, ל-Firestore ולספקי אירועים אחרים של Google.

      • צד שלישי כדי לבצע שילוב עם ספקים שאינם של Google שמציעים מקור Eventarc. מידע נוסף זמין במאמר בנושא אירועים של צד שלישי ב-Eventarc.

    3. בוחרים באפשרות Firestore מתוך רשימת ספקי האירועים כדי לבחור מוצר שמספק את סוג האירוע להפעלת הפונקציה. רשימת ספקי האירועים מופיעה במאמר ספקי אירועים ויעדים.

    4. ברשימה Event type (סוג האירוע), בוחרים באפשרות type=google.cloud.firestore.document.v1.created. הגדרת הטריגר משתנה בהתאם לסוג האירוע הנתמך. מידע נוסף זמין במאמר בנושא סוגי אירועים.

    5. בקטע Filters, בוחרים מסד נתונים, פעולה וערכי מאפיינים, או משתמשים בבחירות ברירת המחדל.

    6. אם השדה אזור מופעל, בוחרים מיקום לטריגר Eventarc. באופן כללי, המיקום של טריגר Eventarc צריך להיות זהה למיקום של Google Cloud המשאב שרוצים לעקוב אחרי האירועים שלו. ברוב התרחישים, כדאי גם לפרוס את הפונקציה באותו אזור. מידע נוסף על מיקומי טריגרים של Eventarc זמין במאמר הסבר על מיקומי Eventarc.

    7. בשדה Service account, בוחרים חשבון שירות. טריגרים של Eventarc מקושרים לחשבונות שירות כדי לשמש כזהות כשמפעילים את הפונקציה. לחשבון השירות של טריגר Eventarc צריכה להיות הרשאה להפעיל את הפונקציה. כברירת מחדל, Cloud Run משתמש בחשבון השירות של Compute Engine שמוגדר כברירת מחדל.

    8. אפשר גם לציין את נתיב כתובת ה-URL של השירות כדי לשלוח את הבקשה הנכנסת. זהו הנתיב היחסי בשירות היעד שאליו יישלחו האירועים של הטריגר. לדוגמה: /,‏ /route,‏ route ו-route/subroute.

  6. אחרי שממלאים את שדות החובה, לוחצים על שמירת הטריגר.

  7. לוחצים על יצירה.

  8. בכרטיסייה מקור, עורכים את קוד המקור אם צריך, ואז בוחרים באפשרות שמירה ופריסה מחדש.

gcloud

כשיוצרים פונקציה באמצעות ה-CLI של gcloud, קודם צריך לפרוס את הפונקציה ואז ליצור טריגר. כדי ליצור טריגר לפונקציה:

  1. מריצים את הפקודה הבאה בספרייה שמכילה את הקוד לדוגמה כדי לפרוס את הפונקציה:

    gcloud run deploy FUNCTION \
            --source . \
            --function FUNCTION_ENTRYPOINT \
            --base-image BASE_IMAGE_ID \
            --region REGION
    

    מחליפים את:

    • FUNCTION עם שם הפונקציה שאתם פורסים. אפשר להשמיט את הפרמטר הזה לחלוטין, אבל אם תשמיטו אותו, תתבקשו לציין את השם.

    • FUNCTION_ENTRYPOINT עם נקודת הכניסה לפונקציה בקוד המקור. זה הקוד ש-Cloud Run מריץ כשהפונקציה פועלת. הערך של הדגל הזה צריך להיות שם של פונקציה או שם מלא של מחלקה שקיימים בקוד המקור.

    • BASE_IMAGE_ID עם סביבת התמונה הבסיסית של הפונקציה. לפרטים נוספים על תמונות בסיסיות ועל החבילות שנכללות בכל תמונה, אפשר לעיין במאמר תמונות בסיסיות של סביבות ריצה.

    • REGION עם Google Cloud האזור שבו רוצים לפרוס את הפונקציה. לדוגמה, europe-west1.

  2. מריצים את הפקודה הבאה כדי ליצור טריגר שמסנן אירועים:

    gcloud eventarc triggers create TRIGGER_NAME  \
        --location=EVENTARC_TRIGGER_LOCATION \
        --destination-run-service=FUNCTION  \
        --destination-run-region=REGION \
        --event-filters="type=google.cloud.firestore.document.v1.created" \
        --service-account=PROJECT_NUMBER-compute@developer.gserviceaccount.com
    

    מחליפים את:

    • TRIGGER_NAME בשם של הטריגר.

    • EVENTARC_TRIGGER_LOCATION עם המיקום של טריגר Eventarc. באופן כללי, המיקום של טריגר Eventarc צריך להיות זהה למיקום של Google Cloud המשאב שרוצים לעקוב אחרי האירועים שלו. ברוב התרחישים, כדאי גם לפרוס את הפונקציה באותו אזור. מידע נוסף זמין במאמר בנושא מיקומי Eventarc.

    • FUNCTION בשם הפונקציה שאתם פורסים.

    • REGION עם האזור של פונקציית Cloud Run.

    • PROJECT_NUMBER עם מספר הפרויקט שלכם. טריגרים של Eventarc מקושרים לחשבונות שירות כדי לשמש כזהות כשמפעילים את הפונקציה. לחשבון השירות של טריגר Eventarc צריכה להיות הרשאה להפעלת הפונקציה. כברירת מחדל, Cloud Run משתמש בחשבון השירות של מחשוב ברירת המחדל. Google Cloud

    כל דגל event-filters מציין סוג של אירוע, והפונקציה מופעלת רק כשאירוע עומד בכל הקריטריונים שצוינו בדגלי event-filters שלו. לכל טריגר צריך להיות event-filters flag שמציין סוג אירוע נתמך, כמו מסמך חדש שנכתב ב-Firestore או קובץ שהועלה ל-Cloud Storage. אי אפשר לשנות את סוג המסנן של האירוע אחרי שיוצרים אותו. כדי לשנות את סוג המסנן של האירוע, צריך ליצור טריגר חדש ולמחוק את הטריגר הישן. אפשר גם לחזור על הדגל --event-filters עם מסנן נתמך בפורמט ATTRIBUTE=VALUE כדי להוסיף עוד מסננים.

Terraform

כדי ליצור טריגר Eventarc לפונקציית Cloud Run, אפשר לעיין במאמר יצירת טריגר באמצעות Terraform.

דוגמאות

בדוגמאות הבאות מוסבר איך להשתמש באירועים של Firestore במצב Native כדי להפעיל פונקציית Cloud Run.

דוגמה 1: פונקציית Hello Firestore

הדוגמה הבאה מדפיסה את השדות של אירוע Firestore שמפעיל את הפונקציה:

Node.js

/**
 * Cloud Event Function triggered by a change to a Firestore document.
 */
const functions = require('@google-cloud/functions-framework');
const protobuf = require('protobufjs');

functions.cloudEvent('helloFirestore', async cloudEvent => {
  console.log(`Function triggered by event on: ${cloudEvent.source}`);
  console.log(`Event type: ${cloudEvent.type}`);

  console.log('Loading protos...');
  const root = await protobuf.load('data.proto');
  const DocumentEventData = root.lookupType(
    'google.events.cloud.firestore.v1.DocumentEventData'
  );

  console.log('Decoding data...');
  const firestoreReceived = DocumentEventData.decode(cloudEvent.data);

  console.log('\nOld value:');
  console.log(JSON.stringify(firestoreReceived.oldValue, null, 2));

  console.log('\nNew value:');
  console.log(JSON.stringify(firestoreReceived.value, null, 2));
});

Python

from cloudevents.http import CloudEvent
import functions_framework
from google.events.cloud import firestore


@functions_framework.cloud_event
def hello_firestore(cloud_event: CloudEvent) -> None:
    """Triggers by a change to a Firestore document.

    Args:
        cloud_event: cloud event with information on the firestore event trigger
    """
    firestore_payload = firestore.DocumentEventData()
    firestore_payload._pb.ParseFromString(cloud_event.data)

    print(f"Function triggered by change to: {cloud_event['source']}")

    print("\nOld value:")
    print(firestore_payload.old_value)

    print("\nNew value:")
    print(firestore_payload.value)

המשך


// Package hellofirestore contains a Cloud Event Function triggered by a Cloud Firestore event.
package hellofirestore

import (
	"context"
	"fmt"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/cloud/firestoredata"
	"google.golang.org/protobuf/proto"
)

func init() {
	functions.CloudEvent("helloFirestore", HelloFirestore)
}

// HelloFirestore is triggered by a change to a Firestore document.
func HelloFirestore(ctx context.Context, event event.Event) error {
	var data firestoredata.DocumentEventData

	// If you omit `DiscardUnknown`, protojson.Unmarshal returns an error
	// when encountering a new or unknown field.
	options := proto.UnmarshalOptions{
		DiscardUnknown: true,
	}
	err := options.Unmarshal(event.Data(), &data)

	if err != nil {
		return fmt.Errorf("proto.Unmarshal: %w", err)
	}

	fmt.Printf("Function triggered by change to: %v\n", event.Source())
	fmt.Printf("Old value: %+v\n", data.GetOldValue())
	fmt.Printf("New value: %+v\n", data.GetValue())
	return nil
}

Java

import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.cloud.firestore.v1.DocumentEventData;
import com.google.protobuf.InvalidProtocolBufferException;
import io.cloudevents.CloudEvent;
import java.util.logging.Logger;

public class FirebaseFirestore implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(FirebaseFirestore.class.getName());

  @Override
  public void accept(CloudEvent event) throws InvalidProtocolBufferException {
    DocumentEventData firestoreEventData = DocumentEventData
        .parseFrom(event.getData().toBytes());

    logger.info("Function triggered by event on: " + event.getSource());
    logger.info("Event type: " + event.getType());

    logger.info("Old value:");
    logger.info(firestoreEventData.getOldValue().toString());

    logger.info("New value:");
    logger.info(firestoreEventData.getValue().toString());
  }
}

C#‎

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.Firestore.V1;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace FirebaseFirestore;

public class Function : ICloudEventFunction<DocumentEventData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, DocumentEventData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Function triggered by event on {subject}", cloudEvent.Subject);
        _logger.LogInformation("Event type: {type}", cloudEvent.Type);
        MaybeLogDocument("Old value", data.OldValue);
        MaybeLogDocument("New value", data.Value);

        // In this example, we don't need to perform any asynchronous operations, so the
        // method doesn't need to be declared async.
        return Task.CompletedTask;
    }

    /// <summary>
    /// Logs the names and values of the fields in a document in a very simplistic way.
    /// </summary>
    private void MaybeLogDocument(string message, Document document)
    {
        if (document is null)
        {
            return;
        }

        // ConvertFields converts the Firestore representation into a .NET-friendly
        // representation.
        IReadOnlyDictionary<string, object> fields = document.ConvertFields();
        var fieldNamesAndTypes = fields
            .OrderBy(pair => pair.Key)
            .Select(pair => $"{pair.Key}: {pair.Value}");
        _logger.LogInformation(message + ": {fields}", string.Join(", ", fieldNamesAndTypes));
    }
}

פריסת הפונקציה

כדי לפרוס את הפונקציה Hello Firestore, מריצים את הפקודה הבאה:

אם עוד לא עשיתם את זה, אתם צריכים להגדיר את מסד הנתונים של Firestore.

הוראות לפריסת הפונקציה מופיעות במאמר יצירת טריגרים לפונקציות.

בדיקת הפונקציה

כדי לבדוק את הפונקציה Hello Firestore, מגדירים אוסף בשם users במסד הנתונים של Firestore:

  1. נכנסים לדף Firestore databases במסוף Google Cloud :

    כניסה אל Firestore

  2. לוחצים על התחלת אוסף.

  3. מציינים את הערך users כמזהה הקולקציה.

  4. כדי להתחיל להוסיף את המסמך הראשון לאוסף, מקבלים את מזהה המסמך שנוצר אוטומטית בקטע הוספת המסמך הראשון.

  5. מוסיפים לפחות שדה אחד למסמך, ומציינים שם וערך. לדוגמה, בשדה שם שדה מזינים username, ובשדה ערך שדה מזינים rowan.

  6. כשתסיים, לחץ על שמור.

    הפעולה הזו יוצרת מסמך חדש, וכך מפעילה את הפונקציה.

  7. כדי לוודא שהפונקציה הופעלה, לוחצים על השם המקושר של הפונקציה בדף הסקירה הכללית של Cloud Run במסוף Google Cloud כדי לפתוח את הדף פרטי השירות.

  8. לוחצים על הכרטיסייה יומנים ומחפשים את המחרוזת הבאה:

Function triggered by change to: //firestore.googleapis.com/projects/your-project-id/databases/(default)'

דוגמה 2: הפונקציה Convert to Uppercase

בדוגמה הבאה, המערכת מאחזרת את הערך שהמשתמש הוסיף, ממירה את המחרוזת במיקום הזה לאותיות רישיות ומחליפה את הערך במחרוזת באותיות רישיות:

Node.js

משתמשים ב-protobufjs כדי לפענח את נתוני האירוע. צריך לכלול את google.events.cloud.firestore.v1 data.proto במקור.

const functions = require('@google-cloud/functions-framework');
const Firestore = require('@google-cloud/firestore');
const protobuf = require('protobufjs');

const firestore = new Firestore({
  projectId: process.env.GOOGLE_CLOUD_PROJECT,
});

// Converts strings added to /messages/{pushId}/original to uppercase
functions.cloudEvent('makeUpperCase', async cloudEvent => {
  console.log('Loading protos...');
  const root = await protobuf.load('data.proto');
  const DocumentEventData = root.lookupType(
    'google.events.cloud.firestore.v1.DocumentEventData'
  );

  console.log('Decoding data...');
  const firestoreReceived = DocumentEventData.decode(cloudEvent.data);

  const resource = firestoreReceived.value.name;
  const affectedDoc = firestore.doc(resource.split('/documents/')[1]);

  const curValue = firestoreReceived.value.fields.original.stringValue;
  const newValue = curValue.toUpperCase();

  if (curValue === newValue) {
    // Value is already upper-case
    // Don't perform a(nother) write to avoid infinite loops
    console.log('Value is already upper-case.');
    return;
  }

  console.log(`Replacing value: ${curValue} --> ${newValue}`);
  affectedDoc.set({
    original: newValue,
  });
});

Python

from cloudevents.http import CloudEvent
import functions_framework
from google.cloud import firestore
from google.events.cloud import firestore as firestoredata

client = firestore.Client()


# Converts strings added to /messages/{pushId}/original to uppercase
@functions_framework.cloud_event
def make_upper_case(cloud_event: CloudEvent) -> None:
    firestore_payload = firestoredata.DocumentEventData()
    firestore_payload._pb.ParseFromString(cloud_event.data)

    path_parts = firestore_payload.value.name.split("/")
    separator_idx = path_parts.index("documents")
    collection_path = path_parts[separator_idx + 1]
    document_path = "/".join(path_parts[(separator_idx + 2) :])

    print(f"Collection path: {collection_path}")
    print(f"Document path: {document_path}")

    affected_doc = client.collection(collection_path).document(document_path)

    cur_value = firestore_payload.value.fields["original"].string_value
    new_value = cur_value.upper()

    if cur_value != new_value:
        print(f"Replacing value: {cur_value} --> {new_value}")
        affected_doc.set({"original": new_value})
    else:
        # Value is already upper-case
        # Don't perform a second write (which can trigger an infinite loop)
        print("Value is already upper-case.")

המשך


// Package upper contains a Firestore Cloud Function.
package upper

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"strings"

	"cloud.google.com/go/firestore"
	firebase "firebase.google.com/go/v4"
	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/cloud/firestoredata"
	"google.golang.org/protobuf/proto"
)

// set the GOOGLE_CLOUD_PROJECT environment variable when deploying.
var projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")

// client is a Firestore client, reused between function invocations.
var client *firestore.Client

func init() {
	// Use the application default credentials.
	conf := &firebase.Config{ProjectID: projectID}

	// Use context.Background() because the app/client should persist across
	// invocations.
	ctx := context.Background()

	app, err := firebase.NewApp(ctx, conf)
	if err != nil {
		log.Fatalf("firebase.NewApp: %v", err)
	}

	client, err = app.Firestore(ctx)
	if err != nil {
		log.Fatalf("app.Firestore: %v", err)
	}

	// Register cloud event function
	functions.CloudEvent("MakeUpperCase", MakeUpperCase)
}

// MakeUpperCase is triggered by a change to a Firestore document. It updates
// the `original` value of the document to upper case.
func MakeUpperCase(ctx context.Context, e event.Event) error {
	var data firestoredata.DocumentEventData

	// If you omit `DiscardUnknown`, protojson.Unmarshal returns an error
	// when encountering a new or unknown field.
	options := proto.UnmarshalOptions{
		DiscardUnknown: true,
	}
	err := options.Unmarshal(e.Data(), &data)

	if err != nil {
		return fmt.Errorf("proto.Unmarshal: %w", err)
	}

	if data.GetValue() == nil {
		return errors.New("Invalid message: 'Value' not present")
	}

	fullPath := strings.Split(data.GetValue().GetName(), "/documents/")[1]
	pathParts := strings.Split(fullPath, "/")
	collection := pathParts[0]
	doc := strings.Join(pathParts[1:], "/")

	var originalStringValue string
	if v, ok := data.GetValue().GetFields()["original"]; ok {
		originalStringValue = v.GetStringValue()
	} else {
		return errors.New("Document did not contain field \"original\"")
	}

	newValue := strings.ToUpper(originalStringValue)
	if originalStringValue == newValue {
		log.Printf("%q is already upper case: skipping", originalStringValue)
		return nil
	}
	log.Printf("Replacing value: %q -> %q", originalStringValue, newValue)

	newDocumentEntry := map[string]string{"original": newValue}
	_, err = client.Collection(collection).Doc(doc).Set(ctx, newDocumentEntry)
	if err != nil {
		return fmt.Errorf("Set: %w", err)
	}
	return nil
}

Java

import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
import com.google.cloud.firestore.SetOptions;
import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.cloud.firestore.v1.DocumentEventData;
import com.google.events.cloud.firestore.v1.Value;
import com.google.protobuf.InvalidProtocolBufferException;
import io.cloudevents.CloudEvent;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

public class FirebaseFirestoreReactive implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(FirebaseFirestoreReactive.class.getName());
  private final Firestore firestore;

  private static final String FIELD_KEY = "original";
  private static final String APPLICATION_PROTOBUF = "application/protobuf";

  public FirebaseFirestoreReactive() {
    this(FirestoreOptions.getDefaultInstance().getService());
  }

  public FirebaseFirestoreReactive(Firestore firestore) {
    this.firestore = firestore;
  }

  @Override
  public void accept(CloudEvent event)
      throws InvalidProtocolBufferException, InterruptedException, ExecutionException {
    if (event.getData() == null) {
      logger.warning("No data found in event!");
      return;
    }

    if (!event.getDataContentType().equals(APPLICATION_PROTOBUF)) {
      logger.warning(String.format("Found unexpected content type %s, expected %s",
          event.getDataContentType(),
          APPLICATION_PROTOBUF));
      return;
    }

    DocumentEventData firestoreEventData = DocumentEventData
        .parseFrom(event.getData().toBytes());

    // Get the fields from the post-operation document snapshot
    // https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents#Document
    Map<String, Value> fields = firestoreEventData.getValue().getFieldsMap();
    if (!fields.containsKey(FIELD_KEY)) {
      logger.warning("Document does not contain original field");
      return;
    }
    String currValue = fields.get(FIELD_KEY).getStringValue();
    String newValue = currValue.toUpperCase();

    if (currValue.equals(newValue)) {
      logger.info("Value is already upper-case");
      return;
    }

    // Retrieve the document name from the resource path:
    // projects/{project_id}/databases/{database_id}/documents/{document_path}
    String affectedDoc = firestoreEventData.getValue()
        .getName()
        .split("/documents/")[1]
        .replace("\"", "");

    logger.info(String.format("Replacing values: %s --> %s", currValue, newValue));

    // Wait for the async call to complete
    this.firestore
        .document(affectedDoc)
        .set(Map.of(FIELD_KEY, newValue), SetOptions.merge())
        .get();
  }
}

C#‎

using CloudNative.CloudEvents;
using Google.Cloud.Firestore;
using Google.Cloud.Functions.Framework;
using Google.Cloud.Functions.Hosting;
using Google.Events.Protobuf.Cloud.Firestore.V1;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace FirestoreReactive;

public class Startup : FunctionsStartup
{
    public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services) =>
        services.AddSingleton(FirestoreDb.Create());
}

// Register the startup class to provide the Firestore dependency.
[FunctionsStartup(typeof(Startup))]
public class Function : ICloudEventFunction<DocumentEventData>
{
    private readonly ILogger _logger;
    private readonly FirestoreDb _firestoreDb;

    public Function(ILogger<Function> logger, FirestoreDb firestoreDb) =>
        (_logger, _firestoreDb) = (logger, firestoreDb);

    public async Task HandleAsync(CloudEvent cloudEvent, DocumentEventData data, CancellationToken cancellationToken)
    {
        // Get the recently-written value. This expression will result in a null value
        // if any of the following is true:
        // - The event doesn't contain a "new" document
        // - The value doesn't contain a field called "original"
        // - The "original" field isn't a string
        string currentValue = data.Value?.ConvertFields().GetValueOrDefault("original") as string;
        if (currentValue is null)
        {
            _logger.LogWarning($"Event did not contain a suitable document");
            return;
        }

        string newValue = currentValue.ToUpperInvariant();
        if (newValue == currentValue)
        {
            _logger.LogInformation("Value is already upper-cased; no replacement necessary");
            return;
        }

        // The CloudEvent subject is "documents/x/y/...".
        // The Firestore SDK FirestoreDb.Document method expects a reference relative to
        // "documents" (so just the "x/y/..." part). This may be simplified over time.
        if (cloudEvent.Subject is null || !cloudEvent.Subject.StartsWith("documents/"))
        {
            _logger.LogWarning("CloudEvent subject is not a document reference.");
            return;
        }
        string documentPath = cloudEvent.Subject.Substring("documents/".Length);

        _logger.LogInformation("Replacing '{current}' with '{new}' in '{path}'", currentValue, newValue, documentPath);
        await _firestoreDb.Document(documentPath).UpdateAsync("original", newValue, cancellationToken: cancellationToken);
    }
}

פריסת הפונקציה

כדי לפרוס את הפונקציה Convert to Uppercase, מריצים את הפקודה הבאה:

אם עוד לא עשיתם את זה, אתם צריכים להגדיר את מסד הנתונים של Firestore.

הוראות לפריסת הפונקציה מופיעות במאמר יצירת טריגרים לפונקציות.

בדיקת הפונקציה

כדי לבדוק את הפונקציה Convert to Uppercase שפרסתם, צריך להגדיר אוסף בשם messages במסד הנתונים של Firestore:

  1. נכנסים לדף Firestore databases במסוף Google Cloud :

    כניסה אל Firestore

  2. לוחצים על התחלת אוסף.

  3. מציינים את הערך messages כמזהה הקולקציה.

  4. כדי להתחיל להוסיף את המסמך הראשון לאוסף, מקבלים את מזהה המסמך שנוצר אוטומטית בקטע הוספת המסמך הראשון.

  5. כדי להפעיל את הפונקציה שפרסתם, מוסיפים מסמך שבו שם השדה הוא original וערך השדה הוא minka.

  6. כששומרים את המסמך, אפשר לראות את המילה באותיות קטנות בשדה הערך הופכת לאותיות גדולות.

    אם לאחר מכן עורכים את הערך בשדה כך שיכיל אותיות קטנות, הפונקציה מופעלת שוב וממירה את כל האותיות הקטנות לאותיות רישיות.

מגבלות על פונקציות

  • אנחנו לא מתחייבים לגבי סדר ההזמנה. שינויים מהירים יכולים להפעיל קריאות לפונקציות בסדר לא צפוי.
  • האירועים מועברים לפחות פעם אחת, אבל אירוע יחיד עשוי להפעיל כמה קריאות לפונקציה. אל תסתמכו על מנגנונים של 'פעם אחת בלבד', ותכתבו פונקציות אידמפוטנטיות.
  • טריגר משויך למסד נתונים יחיד. אי אפשר ליצור טריגר שתואם לכמה מסדי נתונים.
  • מחיקה של מסד נתונים לא תגרום למחיקה אוטומטית של טריגרים שקשורים למסד הנתונים הזה. הטריגר מפסיק לשלוח אירועים, אבל הוא ממשיך להתקיים עד שמוחקים אותו.