טריגרים של התראות ב-Firebase

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

  • במקרה של Crashlytics, אנחנו יכולים לשלוח לכם התראה אם חלה עלייה משמעותית במספר הקריסות באפליקציה.
  • במקרה של Performance Monitoring, אנחנו יכולים לשלוח לכם התראה אם זמן ההפעלה של האפליקציה חורג מהסף שהגדרתם.
  • במהלך App Distribution, אנחנו יכולים לשלוח לכם התראה אם אחד מהבודקים שלכם ירשום מכשיר iOS חדש.

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

בדף הזה מוסבר איך לכתוב פונקציות ב-Cloud Functions for Firebase (דור שני) שמטפלות באירועי התראות.

איך זה עובד?

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

במחזור חיים טיפוסי, פונקציה שמופעלת על ידי אירוע התראה מבצעת את הפעולות הבאות:

  1. הפונקציה מאזינה לסוג מסוים של התראה שמופקת מ-Firebase או ממתינה להפקת התראה כזו.
  2. הטריגר מופעל כשההתראה נשלחת, ומקבל את מטען הנתונים של האירוע שמכיל מידע ספציפי על האירוע.
  3. מפעיל את הקוד של הפונקציה כדי לטפל במטען הייעודי (payload) של האירוע.

הפעלת פונקציה באירועי התראות

אפשר להשתמש בחבילת המשנה firebase-functions/v2/alerts כדי לכתוב פונקציה שמטפלת באירועים של התראות. בדוגמאות הבאות, שמתייחסות למוצרים ספציפיים, מוצג תהליך עבודה שבו פונקציה משתמשת ב-webhook כדי לפרסם הודעה בערוץ Discord כשמתקבלת התראה לגבי המוצר מ-Firebase.

טיפול באירוע התראה Crashlytics

בדוגמה הבאה Crashlytics, משתמשים ב-Cloud Functions for Firebase כדי לטפל באירוע התראה על בעיה חדשה של קריסה חמורה. הפונקציה הזו מפרסמת את פרטי ההתראה בהודעה בערוץ Discord.

דוגמה להתראה על קריסה ב-Discord

הודעה לדוגמה על בעיה חדשה של קריסה קטלנית

הפונקציה מאזינה לאירוע שמתאים לפרסום בעיה חמורה חדשה ב-Firebase:

exports.postfatalissuetodiscord = onNewFatalIssuePublished(async (event) => {
@crashlytics_fn.on_new_fatal_issue_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_fatal_issue_to_discord(event: crashlytics_fn.CrashlyticsNewFatalIssueEvent) -> None:
    """Publishes a message to Discord whenever a new Crashlytics fatal issue occurs."""

הפונקציה מנתחת את אובייקט האירוע שמוחזר, מנתחת מידע שימושי ממטען הנתונים של האירוע ויוצרת הודעה לפרסום בערוץ Discord:

  // construct a helpful message to send to Discord
  const appId = event.appId;
  const {id, title, subtitle, appVersion} = event.data.payload.issue;
  const message = `
🚨 New fatal issue for ${appId} in version ${appVersion} 🚨

**${title}**

${subtitle}

id: \`${id}\`
`;
    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    issue = event.data.payload.issue
    message = f"""
🚨 New fatal issue for {app_id} in version {issue.app_version} 🚨

# {issue.title}

{issue.subtitle}

ID: `{issue.id}`
""".strip()

לבסוף, הפונקציה שולחת את ההודעה שנבנתה ל-Discord באמצעות בקשת HTTP:

const response = await postMessageToDiscord("Crashlytics Bot", message);
if (response.ok) {
  logger.info(
      `Posted fatal Crashlytics alert ${id} for ${appId} to Discord`,
      event.data.payload,
  );
} else {
  throw new Error(response.error);
}
response = post_message_to_discord("Crashlytics Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted fatal Crashlytics alert {issue.id} for {app_id} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

כדי לקבל מידע על כל Crashlytics אירועי ההתראות שאפשר לתעד, אפשר לעבור למסמכי העזר בנושא Crashlytics התראות.

טיפול באירוע התראה Performance Monitoring

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

exports.postperformancealerttodiscord = onThresholdAlertPublished(
    async (event) => {
@performance_fn.on_threshold_alert_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_performance_alert_to_discord(event: performance_fn.PerformanceThresholdAlertEvent) -> None:
    """Publishes a message to Discord whenever a performance threshold alert is fired."""

הפונקציה מנתחת את אובייקט האירוע שמוחזר, מנתחת מידע שימושי ממטען הנתונים של האירוע ויוצרת הודעה לפרסום בערוץ Discord:

      // construct a helpful message to send to Discord
      const appId = event.appId;
      const {
        eventName,
        metricType,
        eventType,
        numSamples,
        thresholdValue,
        thresholdUnit,
        conditionPercentile,
        appVersion,
        violationValue,
        violationUnit,
        investigateUri,
      } = event.data.payload;
      const message = `
    ⚠️ Performance Alert for ${metricType} of ${eventType}: **${eventName}** ⚠️
    
    App id: ${appId}
    Alert condition: ${thresholdValue} ${thresholdUnit}
    Percentile (if applicable): ${conditionPercentile}
    App version (if applicable): ${appVersion}
    
    Violation: ${violationValue} ${violationUnit}
    Number of samples checked: ${numSamples}
    
    **Investigate more:** ${investigateUri}
    `;
    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    perf = event.data.payload
    message = f"""
⚠️ Performance Alert for {perf.metric_type} of {perf.event_type}: **{perf.event_name}** ⚠️

App ID: {app_id}
Alert condition: {perf.threshold_value} {perf.threshold_unit}
Percentile (if applicable): {perf.condition_percentile}
App version (if applicable): {perf.app_version}

Violation: {perf.violation_value} {perf.violation_unit}
Number of samples checked: {perf.num_samples}

**Investigate more:** {perf.investigate_uri}
""".strip()

לבסוף, הפונקציה שולחת את ההודעה שנבנתה ל-Discord באמצעות בקשת HTTP:

const response = await postMessageToDiscord(
    "Firebase Performance Bot", message);
if (response.ok) {
  logger.info(
      `Posted Firebase Performance alert ${eventName} to Discord`,
      event.data.payload,
  );
} else {
  throw new Error(response.error);
}
response = post_message_to_discord("App Performance Bot", message,
                                   DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted Firebase Performance alert {perf.event_name} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

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

טיפול באירוע התראה App Distribution

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

בדוגמה הזו, הפונקציה מאזינה לאירועים שנשלחים בכל פעם שבודק רושם מכשיר iOS חדש. כשרושמים מכשיר iOS חדש, צריך לעדכן את פרופיל ההקצאה עם ה-UDID של המכשיר ואז להפיץ מחדש את האפליקציה.

exports.postnewduuidtodiscord = onNewTesterIosDevicePublished(async (event) => {
@app_distribution_fn.on_new_tester_ios_device_published(secrets=["DISCORD_WEBHOOK_URL"])
def post_new_udid_to_discord(event: app_distribution_fn.NewTesterDeviceEvent) -> None:
    """Publishes a message to Discord whenever someone registers a new iOS test device."""

לאחר מכן הפונקציה מנתחת את האובייקט שמוחזר, מנתחת מידע שימושי ממטען הייעודי (Payload) של האירוע ויוצרת הודעה לפרסום בערוץ Discord:

  // construct a helpful message to send to Discord
  const appId = event.appId;
  const {
    testerDeviceIdentifier,
    testerDeviceModelName,
    testerEmail,
    testerName,
  } = event.data.payload;
  const message = `
📱 New iOS device registered by ${testerName} <${testerEmail}> for ${appId}

UDID **${testerDeviceIdentifier}** for ${testerDeviceModelName}
`;
    # Construct a helpful message to send to Discord.
    app_id = event.app_id
    app_dist = event.data.payload
    message = f"""
📱 New iOS device registered by {app_dist.tester_name} <{app_dist.tester_email}> for {app_id}

UDID **{app_dist.tester_device_identifier}** for {app_dist.tester_device_model_name}
""".strip()

לבסוף, הפונקציה שולחת את ההודעה שנבנתה ל-Discord באמצעות בקשת HTTP:

const response = await postMessageToDiscord("AppDistribution Bot", message);
if (response.ok) {
  logger.info(
      `Posted iOS device registration alert for ${testerEmail} to Discord`,
  );
} else {
  throw new Error(response.error);
}
response = post_message_to_discord("App Distro Bot", message, DISCORD_WEBHOOK_URL.value)
if response.ok:
    print(f"Posted iOS device registration alert for {app_dist.tester_email} to Discord.")
    pprint.pp(event.data.payload)
else:
    response.raise_for_status()

כדי לקבל מידע על כל App Distribution אירועי ההתראות שאפשר לתעד, אפשר לעבור למסמכי העזר בנושא App Distribution התראות.

כדי ללמוד איך להשתמש בפונקציה שמופעלת על ידי התראה על משוב בתוך האפליקציה מ-Firebase מ-App Distribution, אפשר לעיין במאמר בנושא שליחת משוב בתוך האפליקציה אל Jira.